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    /// The request (turn) that saved it: later saves in the same request overwrite it
105    /// instead of adding versions (13.13; empty for older versions and saves without one).
106    #[serde(default, skip_serializing_if = "String::is_empty")]
107    pub turn: String,
108}
109
110#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
111pub struct Artifact {
112    /// `[a-z0-9-]`, unique in the workspace.
113    pub id: String,
114    /// For clients of protocol 13.0; [`Artifact::content_type`] is what it is.
115    pub kind: ArtifactKind,
116    /// What it is (13.1+; empty from older engines and in older index files: then
117    /// [`Artifact::content_type`] derives it from `kind`).
118    #[serde(default, skip_serializing_if = "String::is_empty")]
119    pub content_type: String,
120    pub title: String,
121    /// Name to export it as, e.g. `loan-calculator.html`.
122    pub filename: String,
123    /// Oldest first; never empty.
124    pub versions: Vec<ArtifactVersion>,
125    /// An HTML app may reach the web (HTTPS only: fetch, scripts, styles, fonts and images
126    /// by URL). Off unless the user or the model turned it on.
127    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
128    pub network: bool,
129}
130
131/// One artifact in the Library: every chat's artifacts in one place (17+, cap
132/// [`crate::version::CAP_LIBRARY`]).
133#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
134pub struct LibraryItem {
135    pub chat: String,
136    pub chat_title: String,
137    /// The project of its chat, if it has one.
138    #[serde(default, skip_serializing_if = "Option::is_none")]
139    pub workspace: Option<String>,
140    pub artifact: Artifact,
141    /// The chat it was made in has been deleted: the thing itself was kept.
142    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
143    pub chat_gone: bool,
144    /// A live file: the person's own file it follows (relative to its folder).
145    #[serde(default, skip_serializing_if = "Option::is_none")]
146    pub live: Option<String>,
147}
148
149impl Artifact {
150    /// Its content type: the one the engine sent if it is well-formed, else the one its
151    /// [`ArtifactKind`] stands for.
152    pub fn content_type(&self) -> &str {
153        if valid_content_type(&self.content_type) { &self.content_type } else { self.kind.content_type(&self.filename) }
154    }
155
156    pub fn latest(&self) -> Option<&ArtifactVersion> {
157        self.versions.iter().max_by_key(|v| v.n)
158    }
159
160    pub fn version(&self, n: u32) -> Option<&ArtifactVersion> {
161        self.versions.iter().find(|v| v.n == n)
162    }
163}
164
165/// "This step made version `version` of artifact `id`."
166#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
167pub struct ArtifactRef {
168    pub id: String,
169    pub version: u32,
170}
171
172/// An artifact id is safe to use as a folder name and a URL segment.
173pub fn valid_id(id: &str) -> bool {
174    (1..=64).contains(&id.len()) && id.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-') && !id.starts_with('-')
175}
176
177/// The theme an HTML app is given, as CSS custom properties (`--byob-bg`, …). Apps are told
178/// to style themselves with these so they match the window. Additive: names are only ever
179/// appended (the artifact helper accepts lowercase letters and dashes only, so no digits).
180pub const THEME_VARS: [&str; 26] = [
181    "--byob-bg",
182    "--byob-surface",
183    "--byob-fg",
184    "--byob-muted",
185    "--byob-accent",
186    "--byob-on-accent",
187    "--byob-border",
188    "--byob-danger",
189    "--byob-success",
190    "--byob-warning",
191    "--byob-link",
192    "--byob-strong",
193    "--byob-faint",
194    "--byob-panel",
195    "--byob-field",
196    "--byob-code-bg",
197    "--byob-code-fg",
198    "--byob-radius",
199    "--byob-chart-a",
200    "--byob-chart-b",
201    "--byob-chart-c",
202    "--byob-chart-d",
203    "--byob-chart-e",
204    "--byob-chart-f",
205    "--byob-chart-g",
206    "--byob-chart-h",
207];
208
209#[cfg(test)]
210mod tests {
211    use super::*;
212
213    #[test]
214    fn content_types_and_their_fallbacks() {
215        let a = |kind, content_type: &str, filename: &str| Artifact {
216            id: "a".into(),
217            kind,
218            content_type: content_type.into(),
219            title: "A".into(),
220            filename: filename.into(),
221            versions: vec![],
222            network: false,
223        };
224        // From a 13.1 engine: the type it sent, whatever the kind says.
225        assert_eq!(a(ArtifactKind::Text, "application/vnd.acme.sheet+json", "x.sheet").content_type(), "application/vnd.acme.sheet+json");
226        // From an older engine (or index file): derived from the kind.
227        assert_eq!(a(ArtifactKind::Image, "", "p.PNG").content_type(), TYPE_PNG);
228        assert_eq!(a(ArtifactKind::Image, "", "p.jpg").content_type(), TYPE_JPEG);
229        assert_eq!(a(ArtifactKind::Chart, "", "s.chart.json").content_type(), TYPE_CHART);
230        // Garbage is ignored.
231        assert_eq!(a(ArtifactKind::Html, "Text/HTML; x=<y>", "a.html").content_type(), TYPE_HTML);
232        assert!(valid_content_type("text/x-python") && !valid_content_type("text") && !valid_content_type("/x"));
233        assert!(!valid_content_type(&format!("a/{}", "b".repeat(100))));
234        assert_eq!(mime(TYPE_MARKDOWN), "text/markdown; charset=utf-8");
235        assert_eq!(mime(TYPE_CHART), "application/json");
236        assert_eq!(mime(TYPE_PNG), "image/png");
237        assert_eq!(mime("bad"), "application/octet-stream");
238        // Not sent when empty; old JSON without it parses.
239        let json = serde_json::to_string(&a(ArtifactKind::Text, "", "n")).unwrap();
240        assert!(!json.contains("content_type"));
241        let back: Artifact = serde_json::from_str(&json).unwrap();
242        assert_eq!(back.content_type(), TYPE_TEXT);
243    }
244
245    #[test]
246    fn ids() {
247        assert!(valid_id("loan-calculator-3f2a"));
248        for bad in ["", "-x", "A", "a/b", "..", "a b", &"x".repeat(65)] {
249            assert!(!valid_id(bad), "{bad}");
250        }
251    }
252
253    #[test]
254    fn latest_and_lookup() {
255        let v = |n| ArtifactVersion { n, path: format!("v{n}"), created_at: 0, note: String::new(), size: 1, turn: String::new() };
256        let a = Artifact {
257            id: "a".into(),
258            kind: ArtifactKind::Html,
259            content_type: TYPE_HTML.into(),
260            title: "A".into(),
261            filename: "a.html".into(),
262            versions: vec![v(1), v(3), v(2)],
263            network: false,
264        };
265        assert_eq!(a.latest().map(|v| v.n), Some(3));
266        assert_eq!(a.version(2).map(|v| v.path.as_str()), Some("v2"));
267        assert!(a.version(9).is_none());
268    }
269}