From 103edb61350f8faaa8b9c2681e6b55cc586bf417 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Tue, 24 Nov 2026 08:03:04 -0600 Subject: [PATCH] feat(id): add media/1 presentation surface with text projection (#13679, task 22932) --- .../crates/id-core/src/world_presentation.rs | 383 +++++++++++++++++- 1 file changed, 382 insertions(+), 1 deletion(-) diff --git a/pkgs/id/crates/id-core/src/world_presentation.rs b/pkgs/id/crates/id-core/src/world_presentation.rs index 50145286a9..448aa3278b 100644 --- a/pkgs/id/crates/id-core/src/world_presentation.rs +++ b/pkgs/id/crates/id-core/src/world_presentation.rs @@ -29,6 +29,15 @@ //! player uses the audio text projection; a host that does not know the //! kind at all drops the document to the legacy text path. //! +//! A program may instead return a versioned `kind: media` JSON document +//! (`media/1`, #13679): a bounded list of descriptive media items — +//! typed artifact-id references with a closed sort set, dimensions and +//! durations. Items carry no embedded bytes, URLs, scripts or mime +//! strings: a presenter resolves each artifact id against the world's +//! own media artifacts. A shell without a media presenter uses the +//! media text projection; a host that does not know the kind at all +//! drops the document to the legacy text path. +//! //! Semantic token adapter contract (xterm-256 foreground, bold; 1-bit): //! | token | terminal | 1-bit | text | //! |---|---|---|---| @@ -88,6 +97,15 @@ pub const MAX_AUDIO_DURATION_MS: u32 = 3_600_000; pub const MAX_WIDGET_CONTROLS: usize = 64; /// Maximum serialized widget document size in bytes. pub const MAX_WIDGET_BYTES: usize = 64 * 1024; +/// Maximum items accepted in one world media document. +pub const MAX_MEDIA_ITEMS: usize = 64; +/// Maximum serialized media document size in bytes. +pub const MAX_MEDIA_SURFACE_BYTES: usize = 64 * 1024; +/// Maximum width or height of one media item, in pixels. Keeps item +/// geometry in a range every presenter can scale without overflow. +pub const MAX_MEDIA_DIMENSION: u32 = 16384; +/// Maximum duration of one media item, in milliseconds (24 hours). +pub const MAX_MEDIA_DURATION_MS: u32 = 86_400_000; /// A validated view understood by more than one transport presenter. /// @@ -115,6 +133,11 @@ pub enum WorldSurface { /// shells with a widget presenter; other shells use its text /// projection. Widget(WidgetSurface), + /// A media item list (`media/1`): typed artifact-id references + /// with a closed sort set (image, audio, video), rendered natively + /// by shells with a media presenter; other shells use its text + /// projection. + Media(MediaSurface), } impl WorldSurface { @@ -131,6 +154,7 @@ impl WorldSurface { Self::Scene(scene) => scene.text_projection(), Self::Audio(audio) => audio.text_projection(), Self::Widget(widget) => widget.text_projection(), + Self::Media(media) => media.text_projection(), } } } @@ -1302,6 +1326,175 @@ impl WidgetSurface { } } +/// A versioned `media/1` document: a bounded list of descriptive media +/// items. Guest input is data only: an item names a sort from a closed +/// set and the id of a world media artifact — there are no embedded +/// bytes, URLs, scripts or mime strings, so a presenter resolves each +/// artifact id against the world's own media artifacts and derives +/// everything renderable from the referenced artifact. The document +/// shape is the struct shape, so a parsed media document round-trips +/// through [`parse_surface`]. +#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)] +#[serde(deny_unknown_fields)] +pub struct MediaSurface { + /// Media format version. `media/1` defines version 1. + pub version: u8, + /// Optional caption naming the item list; the text projection's + /// first line. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub title: Option, + /// The document's items, in document order. Ids are unique. + pub items: Vec, +} + +/// One named media reference in a [`MediaSurface`]. +#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)] +#[serde(deny_unknown_fields)] +pub struct MediaItem { + /// Stable identifier, unique within the document. + pub id: String, + /// Human-readable name, used by the text projection and by + /// presenters that label items. + pub label: String, + /// The referenced artifact's sort, from the closed sort set. + pub sort: MediaSort, + /// The world media artifact this item names, by id; a presenter + /// resolves it against the world's own media artifacts. An + /// unresolvable artifact is a presenter-side miss: the item still + /// appears in the text projection. + pub artifact: String, + /// The item's width in pixels, for image and video sorts. Width + /// and height are both given or both absent. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub width: Option, + /// The item's height in pixels, for image and video sorts. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub height: Option, + /// The item's length in milliseconds, for audio and video sorts. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub duration_ms: Option, +} + +/// The closed set of media sorts a `media/1` item may name, mirroring +/// the `id-store` media plane (`MediaSort`, #2342). Guest documents +/// reject unknown sorts. +#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Eq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum MediaSort { + /// Still pictures. + Image, + /// Sound. + Audio, + /// Moving pictures. + Video, +} + +impl MediaSort { + /// The document spelling of the sort, used by the text projection. + #[must_use] + pub const fn as_str(&self) -> &'static str { + match self { + Self::Image => "image", + Self::Audio => "audio", + Self::Video => "video", + } + } +} + +impl MediaSurface { + /// Validate the version, item set, identifiers, safe text, + /// artifact references, dimension/duration consistency and total + /// size. Hosts run this before any presenter sees the document + /// (via [`parse_surface`]). + /// + /// # Errors + /// + /// Rejects unsupported versions, unsafe titles, empty or oversized + /// item sets, duplicate ids, unsafe labels, unsafe artifact ids, + /// half-given or out-of-bound dimensions, dimensions on audio + /// items, durations on image items, and oversize documents. + pub fn validate(&self) -> Result<()> { + ensure!( + self.version == 1, + "unsupported world media version {}", + self.version + ); + ensure!( + self.title.as_deref().is_none_or(safe_form_text), + "invalid media title" + ); + ensure!( + !self.items.is_empty() && self.items.len() <= MAX_MEDIA_ITEMS, + "invalid media item count" + ); + let mut ids = std::collections::HashSet::new(); + for item in &self.items { + ensure!( + safe_form_id(&item.id) && safe_form_text(&item.label), + "invalid media item id or label" + ); + ensure!(ids.insert(item.id.as_str()), "duplicate media item id"); + ensure!(safe_form_id(&item.artifact), "invalid media item artifact"); + match (item.width, item.height) { + (None, None) => {} + (Some(width), Some(height)) => { + ensure!( + (1..=MAX_MEDIA_DIMENSION).contains(&width) + && (1..=MAX_MEDIA_DIMENSION).contains(&height), + "media item dimensions out of bounds" + ); + ensure!( + item.sort != MediaSort::Audio, + "audio media items carry no dimensions" + ); + } + _ => return Err(anyhow::anyhow!("media item width and height come together")), + } + if let Some(duration_ms) = item.duration_ms { + ensure!( + (1..=MAX_MEDIA_DURATION_MS).contains(&duration_ms), + "media item duration out of bounds" + ); + ensure!( + item.sort != MediaSort::Image, + "image media items carry no duration" + ); + } + } + ensure!( + serde_json::to_vec(self)?.len() <= MAX_MEDIA_SURFACE_BYTES, + "media exceeds {MAX_MEDIA_SURFACE_BYTES} bytes" + ); + Ok(()) + } + + /// Deterministic escape-free projection: the title (or `Media`), + /// then one numbered line per item naming its label, sort, + /// dimensions and duration. This is what a shell without a media + /// presenter shows, so it is designed here, with the kind, not + /// discovered by the renderer slice. + #[must_use] + pub fn text_projection(&self) -> String { + let mut lines = vec![self.title.clone().unwrap_or_else(|| "Media".to_owned())]; + for (index, item) in self.items.iter().enumerate() { + let mut parts = vec![item.sort.as_str().to_owned()]; + if let (Some(width), Some(height)) = (item.width, item.height) { + parts.push(format!("{width}x{height}")); + } + if let Some(duration_ms) = item.duration_ms { + parts.push(format!("{duration_ms} ms")); + } + lines.push(format!( + "{}. {} ({})", + index + 1, + item.label, + parts.join("; ") + )); + } + lines.join("\n") + } +} + /// A cell-run delta between two consecutive screens (F12.11, first slice). /// /// A patch carries only the cells that changed, grouped into maximal runs of @@ -1571,7 +1764,7 @@ pub fn parse_surface(data: &str) -> Result> { .and_then(Value::as_str); if matches!( kind, - Some("screen" | "text" | "form" | "scene" | "audio" | "widget") + Some("screen" | "text" | "form" | "scene" | "audio" | "widget" | "media") ) || top_level_kind_is_duplicated(data) { return Err(err).context("duplicate JSON object key in world presentation"); @@ -1622,6 +1815,16 @@ pub fn parse_surface(data: &str) -> Result> { widget.validate()?; return Ok(Some(WorldSurface::Widget(widget))); } + Some("media") => { + let mut value = value; + if let Some(object) = value.as_object_mut() { + object.remove("kind"); + } + let media: MediaSurface = + serde_json::from_value(value).context("decode world media presentation")?; + media.validate()?; + return Ok(Some(WorldSurface::Media(media))); + } Some("text") => { let payload: TextPayload = serde_json::from_value(value).context("decode world text presentation")?; @@ -2856,6 +3059,184 @@ mod tests { .is_err()); } + #[test] + fn media_surface_parses_projects_and_round_trips() { + // Oracle: #13679 — a versioned media document is accepted by + // host validation, projects deterministically to text (the + // old-shell fallback), and round-trips through serialization. + let document = serde_json::json!({ + "kind": "media", "version": 1, "title": "Harbor Media", + "items": [ + {"id": "sunset", "label": "Sunset", "sort": "image", + "artifact": "artifact_sunset", "width": 800, "height": 600}, + {"id": "theme", "label": "Theme", "sort": "audio", + "artifact": "artifact_theme", "duration_ms": 12000}, + {"id": "clip", "label": "Clip", "sort": "video", + "artifact": "artifact_clip", "width": 640, "height": 360, + "duration_ms": 5000} + ] + }); + let parsed = parse_surface(&document.to_string()).unwrap().unwrap(); + assert_eq!( + parsed.text_projection(), + "Harbor Media\n1. Sunset (image; 800x600)\n2. Theme (audio; 12000 ms)\n3. Clip (video; 640x360; 5000 ms)" + ); + let serialized = serde_json::to_string(&parsed).unwrap(); + assert_eq!(parse_surface(&serialized).unwrap(), Some(parsed)); + + // Without a title the projection still names what the view is. + let untitled = parse_surface( + r#"{"kind":"media","version":1,"items":[{"id":"a","label":"A","sort":"video","artifact":"artifact_a"}]}"#, + ) + .unwrap() + .unwrap(); + assert_eq!(untitled.text_projection(), "Media\n1. A (video)"); + } + + #[test] + fn media_surface_rejects_unsafe_or_oversize_documents() { + // Oracle: #13679 criterion — malformed or oversized media + // surfaces are refused by host validation (an Err from + // parse_surface, which the host turns into an error frame), + // never silently dropped to the legacy text path and never + // accepted. + let item = |id: &str| { + serde_json::json!({"id": id, "label": "A", "sort": "video", + "artifact": "artifact_a"}) + }; + let media = |items: Value| { + serde_json::json!({"kind": "media", "version": 1, "items": items}).to_string() + }; + // Bad versions. + assert!( + parse_surface( + &serde_json::json!({"kind": "media", "version": 2, "items": [item("a")]}) + .to_string() + ) + .is_err() + ); + assert!( + parse_surface( + &serde_json::json!({"kind": "media", "version": 0, "items": [item("a")]}) + .to_string() + ) + .is_err() + ); + // Unknown fields, top level and per item (deny_unknown_fields) — + // in particular an item carries no embedded bytes, URL or mime + // string. + assert!(parse_surface( + &serde_json::json!({"kind": "media", "version": 1, "src": "x.mp4", "items": [item("a")]}) + .to_string() + ) + .is_err()); + assert!( + parse_surface(&media(serde_json::json!([ + {"id": "a", "label": "A", "sort": "video", "artifact": "artifact_a", + "data": "AAAB"} + ]))) + .is_err() + ); + // Unknown sort: the sort set is closed. + assert!( + parse_surface(&media(serde_json::json!([ + {"id": "a", "label": "A", "sort": "gif", "artifact": "artifact_a"} + ]))) + .is_err() + ); + // Empty and duplicate-id item sets. + assert!(parse_surface(&media(serde_json::json!([]))).is_err()); + assert!(parse_surface(&media(serde_json::json!([item("a"), item("a")]))).is_err()); + // Too many items: the bound is 64 (MAX_MEDIA_ITEMS). + let many: Vec = (0..65).map(|index| item(&format!("i{index}"))).collect(); + assert!(parse_surface(&media(Value::Array(many))).is_err()); + // Unsafe artifact id. + assert!( + parse_surface(&media(serde_json::json!([ + {"id": "a", "label": "A", "sort": "video", "artifact": "artifact a!"} + ]))) + .is_err() + ); + // Unsafe label text (a JSON-escaped ESC). + assert!( + parse_surface(&media(serde_json::json!([ + {"id": "a", "label": "A\u{001b}[2J", "sort": "video", "artifact": "artifact_a"} + ]))) + .is_err() + ); + // Half-given dimensions: width and height come together. + assert!( + parse_surface(&media(serde_json::json!([ + {"id": "a", "label": "A", "sort": "image", "artifact": "artifact_a", + "width": 800} + ]))) + .is_err() + ); + // Dimensions out of bounds: 1..=16384 (MAX_MEDIA_DIMENSION). + assert!( + parse_surface(&media(serde_json::json!([ + {"id": "a", "label": "A", "sort": "image", "artifact": "artifact_a", + "width": 0, "height": 600} + ]))) + .is_err() + ); + assert!( + parse_surface(&media(serde_json::json!([ + {"id": "a", "label": "A", "sort": "image", "artifact": "artifact_a", + "width": 16385, "height": 600} + ]))) + .is_err() + ); + // Dimensions on audio items are refused. + assert!( + parse_surface(&media(serde_json::json!([ + {"id": "a", "label": "A", "sort": "audio", "artifact": "artifact_a", + "width": 800, "height": 600} + ]))) + .is_err() + ); + // Duration bounds: an item lasts 1..=86_400_000 ms + // (MAX_MEDIA_DURATION_MS, 24 hours). + assert!( + parse_surface(&media(serde_json::json!([ + {"id": "a", "label": "A", "sort": "video", "artifact": "artifact_a", + "duration_ms": 0} + ]))) + .is_err() + ); + assert!( + parse_surface(&media(serde_json::json!([ + {"id": "a", "label": "A", "sort": "video", "artifact": "artifact_a", + "duration_ms": 86400001} + ]))) + .is_err() + ); + // Duration on image items is refused. + assert!( + parse_surface(&media(serde_json::json!([ + {"id": "a", "label": "A", "sort": "image", "artifact": "artifact_a", + "duration_ms": 1000} + ]))) + .is_err() + ); + // Oversize document: the serialized cap is 65536 bytes + // (MAX_MEDIA_SURFACE_BYTES); a single huge label trips it. + assert!( + parse_surface(&media(serde_json::json!([ + {"id": "a", "label": "x".repeat(70_000), "sort": "video", "artifact": "artifact_a"} + ]))) + .is_err() + ); + // Duplicate JSON key: a media document with a duplicate key + // is rejected, never last-wins collapsed. + assert!( + parse_surface( + r#"{"kind":"media","version":1,"version":99,"items":[{"id":"a","label":"A","sort":"video","artifact":"artifact_a"}]}"# + ) + .is_err() + ); + } + #[test] fn widget_surface_parses_projects_and_round_trips() { // Oracle: #12657 slice 1c — a versioned widget document is