diff --git a/codex-rs/skills/src/assets/samples/create-statusline/references/statusline.d.ts b/codex-rs/skills/src/assets/samples/create-statusline/references/statusline.d.ts index 9252f53d1c..cd4f3301f7 100644 --- a/codex-rs/skills/src/assets/samples/create-statusline/references/statusline.d.ts +++ b/codex-rs/skills/src/assets/samples/create-statusline/references/statusline.d.ts @@ -14,8 +14,12 @@ export type ApprovalPolicy = "untrusted" | "on-request" | "granular" | "never"; export type ApprovalReviewer = "user" | "auto-review"; +export type BadgeChildren = [string] | [BadgeIcon] | [BadgeIcon, string] | [string, BadgeIcon]; + export type BadgeColor = "secondary" | "info" | "success" | "warning" | "danger"; +export type BadgeIcon = { "type": "icon" } & IconNode; + export type BadgeProps = { color?: BadgeColor, }; /** @@ -43,7 +47,7 @@ export type DirectedBox = { "direction": "row" } & RowProps | { "direction": "co export type DisplayMode = "standard" | "raw"; -export type Element = { "type": "text", props?: TextProps, children: Array, } | { "type": "link", props: LinkProps, children: Array, } | { "type": "row", props: RowProps, children: Array, } | { "type": "list", props?: ListProps, children: Array, } | { "type": "list-item", children: Array, } | { "type": "spacer", children?: [], } | { "type": "badge", props?: BadgeProps, children: [string], } | { "type": "box", props: BoxProps, children: Array, } | { "type": "col", props: ColProps, children: Array, } | { "type": "bold", children: Array, } | { "type": "italic", children: Array, } | { "type": "underline", children: Array, } | { "type": "code", children: Array, } | string; +export type Element = { "type": "text", props?: TextProps, children: Array, } | { "type": "link", props: LinkProps, children: Array, } | { "type": "row", props: RowProps, children: Array, } | { "type": "list", props?: ListProps, children: Array, } | { "type": "list-item", children: Array, } | { "type": "spacer", children?: [], } | { "type": "icon" } & IconNode | { "type": "badge", props?: BadgeProps, children: BadgeChildren, } | { "type": "box", props: BoxProps, children: Array, } | { "type": "col", props: ColProps, children: Array, } | { "type": "bold", children: Array, } | { "type": "italic", children: Array, } | { "type": "underline", children: Array, } | { "type": "code", children: Array, } | string; export type FileSystem = { "type": "restricted" } | { "type": "unrestricted" }; @@ -52,6 +56,16 @@ export type FileSystem = { "type": "restricted" } | { "type": "unrestricted" }; */ export type HexRgb = `#${string}`; +export type IconName = "check" | "x" | "error" | "warning" | "info" | "clock" | "circle" | "empty-circle" | "circle-dashed" | "arrow-up" | "arrow-down" | "arrow-left" | "arrow-right" | "timer" | "branch" | "code"; + +export type IconNode = { props: IconProps, children?: [], }; + +export type IconProps = { name: IconName, +/** + * Terminal icons always align with surrounding text. + */ +inline?: boolean, }; + /** * An absolute HTTP(S) URL without control characters, at most 8 KiB in UTF-8. */ @@ -135,6 +149,7 @@ export type BoxElement = Extract; export type ListElement = Extract; export type ListItemElement = Extract; export type BadgeElement = Extract; +export type IconElement = Extract; export type SpacerElement = Extract; export type CodeElement = Extract; type BoxColumnProps = ColProps & { [K in Exclude]?: never }; diff --git a/codex-rs/tui/src/chatwidget/statusline_contract_tests.rs b/codex-rs/tui/src/chatwidget/statusline_contract_tests.rs index 0876c642a3..997c1673cf 100644 --- a/codex-rs/tui/src/chatwidget/statusline_contract_tests.rs +++ b/codex-rs/tui/src/chatwidget/statusline_contract_tests.rs @@ -33,6 +33,7 @@ fn statusline_typescript_contract_matches_the_bundled_reference() -> color_eyre: "ListElement", "ListItemElement", "BadgeElement", + "IconElement", "SpacerElement", "CodeElement", "StatuslineItemId", @@ -77,6 +78,7 @@ fn generate_reference(output: &Path) -> color_eyre::Result { "List", "ListItem", "Badge", + "Icon", "Spacer", "Code", ] { diff --git a/codex-rs/tui/src/ui_tree.rs b/codex-rs/tui/src/ui_tree.rs index 9407656be5..2cd753d20c 100644 --- a/codex-rs/tui/src/ui_tree.rs +++ b/codex-rs/tui/src/ui_tree.rs @@ -63,12 +63,13 @@ pub(crate) enum UiNode { #[cfg_attr(test, ts(as = "Option<[(); 0]>", optional))] children: [(); 0], }, + Icon(IconNode), /// A compact, single-line state label. Badge { #[serde(default, skip_serializing_if = "is_default")] #[cfg_attr(test, ts(as = "Option", optional))] props: BadgeProps, - children: [String; 1], + children: BadgeChildren, }, Box { props: BoxProps, @@ -95,6 +96,84 @@ pub(crate) enum UiNode { String(String), } +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[cfg_attr(test, derive(ts_rs::TS), ts(export_to = "statusline.d.ts"))] +#[serde(deny_unknown_fields)] +pub(crate) struct IconNode { + #[serde(deserialize_with = "decode::icon_props")] + props: IconProps, + #[serde(default, skip_serializing_if = "is_default")] + #[cfg_attr(test, ts(as = "Option<[(); 0]>", optional))] + children: [(); 0], +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[cfg_attr(test, derive(ts_rs::TS), ts(export_to = "statusline.d.ts"))] +#[serde(deny_unknown_fields)] +pub(crate) struct IconProps { + #[serde(deserialize_with = "decode::token")] + name: IconName, + /// Terminal icons always align with surrounding text. + #[serde(default, skip_serializing_if = "is_default")] + #[cfg_attr(test, ts(as = "Option", optional))] + inline: bool, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[cfg_attr(test, derive(ts_rs::TS), ts(export_to = "statusline.d.ts"))] +#[serde(rename_all = "kebab-case")] +pub(crate) enum IconName { + Check, + X, + Error, + Warning, + Info, + Clock, + Circle, + EmptyCircle, + CircleDashed, + ArrowUp, + ArrowDown, + ArrowLeft, + ArrowRight, + Timer, + Branch, + Code, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[cfg_attr(test, derive(ts_rs::TS), ts(export_to = "statusline.d.ts"))] +#[serde(tag = "type", rename_all = "kebab-case")] +pub(crate) enum BadgeIcon { + Icon(IconNode), +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[cfg_attr(test, derive(ts_rs::TS), ts(export_to = "statusline.d.ts"))] +#[serde(untagged)] +pub(crate) enum BadgeChildren { + Label([String; 1]), + Icon([BadgeIcon; 1]), + Leading(BadgeIcon, String), + Trailing(String, BadgeIcon), +} + +impl BadgeChildren { + fn count(&self) -> usize { + match self { + Self::Label(_) | Self::Icon(_) => 1, + Self::Leading(..) | Self::Trailing(..) => 2, + } + } + + fn label(&self) -> &str { + match self { + Self::Label([label]) | Self::Leading(_, label) | Self::Trailing(label, _) => label, + Self::Icon(_) => "", + } + } +} + #[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] #[cfg_attr(test, derive(ts_rs::TS), ts(export_to = "statusline.d.ts"))] diff --git a/codex-rs/tui/src/ui_tree/decode.rs b/codex-rs/tui/src/ui_tree/decode.rs index e3cce30e75..545dad341d 100644 --- a/codex-rs/tui/src/ui_tree/decode.rs +++ b/codex-rs/tui/src/ui_tree/decode.rs @@ -1,5 +1,6 @@ //! Enforce the input byte limit before parsing and the UI tree limits after deserialization. +use super::IconProps; use super::MAX_SAFE_INTEGER; use super::MAX_TEXT_BYTES; use super::UiNode; @@ -22,26 +23,21 @@ impl std::str::FromStr for UiTree { let mut nodes = 0; let mut text_bytes = 0; while let Some((node, depth)) = pending.pop() { - // A badge stores its string child directly in the node. - let label = usize::from(matches!(node, UiNode::Badge { .. })); - if depth + label > 16 { + let badge_children = match node { + UiNode::Badge { children, .. } => children.count(), + _ => 0, + }; + if depth + usize::from(badge_children > 0) > 16 { return Err(Self::Err::custom("UI tree exceeds maximum depth 16")); } - nodes += 1 + label; + nodes += 1 + badge_children; if nodes > 256 { return Err(Self::Err::custom("UI tree exceeds 256 non-null nodes")); } match node { - UiNode::Spacer { .. } => {} - UiNode::String(text) - | UiNode::Badge { - children: [text], .. - } => { - text_bytes += text.len(); - if text_bytes > MAX_TEXT_BYTES { - return Err(Self::Err::custom("UI tree exceeds 16 KiB of text")); - } - } + UiNode::Spacer { .. } | UiNode::Icon(_) => {} + UiNode::String(text) => text_bytes += text.len(), + UiNode::Badge { children, .. } => text_bytes += children.label().len(), UiNode::List { children, .. } => { pending.extend(children.iter().map(|child| (child, depth + 1))); } @@ -59,10 +55,33 @@ impl std::str::FromStr for UiTree { } } } + if text_bytes > MAX_TEXT_BYTES { + return Err(Self::Err::custom("UI tree exceeds 16 KiB of text")); + } Ok(Self(root)) } } +// A derived struct also accepts positional arrays. Require an object while +// retaining IconProps' checks for duplicate and unknown fields. +pub(super) fn icon_props<'de, D: Deserializer<'de>>(d: D) -> Result { + struct Object; + + impl<'de> serde::de::Visitor<'de> for Object { + type Value = IconProps; + + fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("an icon props object") + } + + fn visit_map>(self, map: M) -> Result { + IconProps::deserialize(serde::de::value::MapAccessDeserializer::new(map)) + } + } + + d.deserialize_map(Object) +} + pub(super) fn optional_token<'de, D: Deserializer<'de>, T: DeserializeOwned>( d: D, ) -> Result, D::Error> { diff --git a/codex-rs/tui/src/ui_tree/render/prepare.rs b/codex-rs/tui/src/ui_tree/render/prepare.rs index e16fc1e9b7..10d14f8c6e 100644 --- a/codex-rs/tui/src/ui_tree/render/prepare.rs +++ b/codex-rs/tui/src/ui_tree/render/prepare.rs @@ -391,11 +391,12 @@ impl PreparedNode { )); return; } - UiNode::Badge { - props, - children: [label], - } => { - inline.push_badge(label, props.color, paint); + UiNode::Icon(icon) => { + inline.push_icon(icon.props.name, paint); + return; + } + UiNode::Badge { props, children } => { + inline.push_badge(children, props.color, paint); return; } UiNode::Code { children } => { diff --git a/codex-rs/tui/src/ui_tree/render/text.rs b/codex-rs/tui/src/ui_tree/render/text.rs index 8893f023dd..18d183d173 100644 --- a/codex-rs/tui/src/ui_tree/render/text.rs +++ b/codex-rs/tui/src/ui_tree/render/text.rs @@ -6,7 +6,10 @@ use super::RenderTheme; use super::Visit; use super::sanitize_leaf; use crate::line_truncation::span_width; +use crate::ui_tree::BadgeChildren; use crate::ui_tree::BadgeColor; +use crate::ui_tree::BadgeIcon; +use crate::ui_tree::IconName; use crate::ui_tree::theme::Color; use ratatui::buffer::CellWidth; use ratatui::style::Style; @@ -60,6 +63,7 @@ struct Run { // Splitting a leaf at style, whitespace or wrap boundaries shares its original buffer. #[derive(Debug)] enum RunText { + Icon(&'static str), Slice(Arc, Range), Space, } @@ -76,6 +80,7 @@ impl RunText { Arc::clone(text), bytes.start + range.start..bytes.start + range.end, ), + Self::Icon(text) => Self::Icon(&text[range]), Self::Space => Self::Space, } } @@ -87,6 +92,7 @@ impl Deref for RunText { fn deref(&self) -> &str { match self { Self::Slice(text, bytes) => &text[bytes.clone()], + Self::Icon(text) => text, Self::Space => " ", } } @@ -94,7 +100,7 @@ impl Deref for RunText { impl PartialEq for RunText { fn eq(&self, other: &Self) -> bool { - **self == **other + matches!(self, Self::Icon(_)) == matches!(other, Self::Icon(_)) && **self == **other } } @@ -129,6 +135,29 @@ pub(super) struct InlineText { space: Option, } +impl IconName { + fn glyph(&self) -> &'static str { + match self { + Self::Check => "✓", + Self::X => "✗", + Self::Error => "!", + Self::Warning => "⚠", + Self::Info => "ⓘ", + Self::Clock => "◷", + Self::Circle => "●", + Self::EmptyCircle => "○", + Self::CircleDashed => "◌", + Self::ArrowUp => "↑", + Self::ArrowDown => "↓", + Self::ArrowLeft => "←", + Self::ArrowRight => "→", + Self::Timer => "⏱", + Self::Branch => "⑂", + Self::Code => "", + } + } +} + impl InlineText { /// Returning to normal prose allows a break before a sibling’s first literal space. pub(super) fn end_span(&mut self) { @@ -148,31 +177,61 @@ impl InlineText { self.push_sanitized(sanitize_leaf(raw), paint); } - pub(super) fn push_badge(&mut self, label: String, color: BadgeColor, mut paint: Paint) { - let label = if label.contains('\r') { - label.replace('\r', " ") - } else { - label - }; - let label = sanitize_leaf(label); + pub(super) fn push_icon(&mut self, name: IconName, paint: Paint) { + self.push_box([RunText::Icon(name.glyph())], paint); + } + + pub(super) fn push_badge( + &mut self, + children: BadgeChildren, + color: BadgeColor, + mut paint: Paint, + ) { + let label = sanitize_leaf(children.label().replace('\r', " ")); let label = label.split_ascii_whitespace().collect::>().join(" "); - let text = RunText::new(format!(" {label} ")); + let gap = if label.is_empty() { "" } else { " " }; paint.badge = Some(color); - // An inline-flex badge forms one unbreakable box with a break on either side. + let glyph = |BadgeIcon::Icon(icon): BadgeIcon| RunText::Icon(icon.props.name.glyph()); + match children { + BadgeChildren::Label(_) => self.push_box([RunText::new(format!(" {label} "))], paint), + BadgeChildren::Icon([icon]) => { + self.push_box([RunText::Space, glyph(icon), RunText::Space], paint); + } + BadgeChildren::Leading(icon, _) => self.push_box( + [ + RunText::Space, + glyph(icon), + RunText::new(format!("{gap}{label} ")), + ], + paint, + ), + BadgeChildren::Trailing(_, icon) => self.push_box( + [ + RunText::new(format!(" {label}{gap}")), + glyph(icon), + RunText::Space, + ], + paint, + ), + } + } + + fn push_box(&mut self, parts: impl IntoIterator, paint: Paint) { self.completed .extend(chunks(std::mem::take(&mut self.line))); if let Some(last) = self.completed.last_mut() { last.trailing_space = self.space.take(); } - self.completed.push(Chunk { - width_cells: span_width(&Span::raw(&*text)), - runs: vec![Run { + let mut chunk = Chunk::default(); + for text in parts { + chunk.width_cells += span_width(&Span::raw(&*text)); + chunk.runs.push(Run { break_before: false, text, - paint, - }], - ..Chunk::default() - }); + paint: paint.clone(), + }); + } + self.completed.push(chunk); } fn finish_line(&mut self) { @@ -617,6 +676,10 @@ pub(super) fn visit_chunks<'a>( cells += w; bytes += g.len(); } + // An icon can span multiple graphemes (e.g. ) yet represents one glyph. + if bytes < text.len() && matches!(run.text, RunText::Icon(_)) { + return used; + } if bytes > 0 && (used < limit || bytes == text.len()) { draw(used, &text[..bytes], cells, &run.paint); } diff --git a/codex-rs/tui/src/ui_tree_tests.rs b/codex-rs/tui/src/ui_tree_tests.rs index df041d2beb..fa271bf5f4 100644 --- a/codex-rs/tui/src/ui_tree_tests.rs +++ b/codex-rs/tui/src/ui_tree_tests.rs @@ -2121,3 +2121,67 @@ fn list_markers_preserve_the_surface_under_each_cell() { } } } + +#[test] +fn icon_and_badge_compositions_wrap_as_units() { + let icons = [ + "circle", + "empty-circle", + "circle-dashed", + "arrow-up", + "arrow-down", + "arrow-left", + "arrow-right", + ] + .map(|name| json!({"type":"icon","props":{"name":name}})); + let group = tree(json!({"type":"text","children":icons})); + assert_eq!(painted_rows(&group, Size::new(7, 1)), ["●○◌↑↓←→"]); + let code = json!({"type":"icon","props":{"name":"code","inline":true}}); + let node = tree(json!({"type":"text","children":["AB",code]})); + assert_eq!(painted_rows(&node, Size::new(4, 2)), ["AB", ""]); + let icon = json!({"type":"icon","props":{"name":"arrow-right","inline":true}}); + let node = tree(json!({"type":"text","children":["AB",icon]})); + assert_eq!(painted_rows(&node, Size::new(3, 1)), ["AB→"]); + for (children, expected) in [ + (json!([icon]), " →"), + (json!([icon, " ok "]), " → ok"), + (json!(["ok", icon]), " ok →"), + ] { + let node = tree(json!({"type":"badge","children":children})); + assert_eq!(painted_rows(&node, Size::new(12, 1)), [expected]); + } +} + +#[test] +fn icons_require_a_supported_name_and_empty_children() { + for icon in [ + json!({"type":"icon","props":["check",false]}), + json!({"type":"icon","props":{"name":"terminal"}}), + json!({"type":"icon","props":{"name":"spinner"}}), + json!({"type":"icon","props":{"name":"x-circle"}}), + json!({"type":"icon","props":{"name":"check"},"children":["x"]}), + json!({"type":"icon","props":{"name":{"check":null}}}), + ] { + assert!(parse(icon.clone()).is_err()); + assert!(parse(json!({"type":"badge","children":[icon,"ok"]})).is_err()); + } + let icon = json!({"type":"icon","props":{"name":"check"},"children":[]}); + let badge = json!({"type":"badge","children":[icon,"ok"]}); + assert!(parse(json!({"type":"text","children":vec![badge.clone();85]})).is_ok()); + assert!(parse(json!({"type":"text","children":vec![badge;86]})).is_err()); +} + +#[test] +fn ellipsis_never_splits_a_multi_cell_icon() { + let icon = json!({"type":"icon","props":{"name":"code","inline":true}}); + for props in [json!({"maxLines":1}), json!({})] { + let node = tree(json!({"type":"text","props":props,"children":["A",icon,"B"]})); + assert_eq!(painted_rows(&node, Size::new(4, 1)), ["A…"]); + assert_eq!(painted_rows(&node, Size::new(5, 1)), ["AB"]); + } + let node = tree(json!({"type":"text","props":{"maxLines":1},"children":[icon,"B"]})); + assert_eq!(painted_rows(&node, Size::new(3, 1)), ["…"]); + let badge = tree(json!({"type":"badge","children":["A",icon]})); + assert_eq!(painted_rows(&badge, Size::new(5, 1)), [" A …"]); + assert_eq!(painted_rows(&badge, Size::new(6, 1)), [" A "]); +} diff --git a/codex-rs/tui/tests/fixtures/statusline/contract.check.ts b/codex-rs/tui/tests/fixtures/statusline/contract.check.ts index c1b760d0bd..d375b5be7d 100644 --- a/codex-rs/tui/tests/fixtures/statusline/contract.check.ts +++ b/codex-rs/tui/tests/fixtures/statusline/contract.check.ts @@ -3,6 +3,7 @@ import type { ColElement, BoxElement, BadgeElement, + IconElement, ListElement, ListItemElement, SpacerElement, @@ -59,7 +60,8 @@ const emptySpacer: SpacerElement = { ...spacer, children: [] }; const invalidSpacer: SpacerElement = { ...spacer, children: ["x"] }; const badge: BadgeElement = { type: "badge", children: ["queued"] }; -const passing: BadgeElement = { ...badge, props: { color: "success" }, children: ["passing"] }; +const check: IconElement = { type: "icon", props: { name: "check", inline: true } }; +const passing: BadgeElement = { ...badge, props: { color: "success" }, children: [check, "passing"] }; // @ts-expect-error Badges accept semantic colors. const invalidBadge: BadgeElement = { ...badge, props: { color: "red" } };