Files
codex/codex-rs/tui/src/ui_tree.rs
T
Joe Savona e251a64500 Reject positional arrays for TUI tree elements and props (#64798)
## Why

Serde's derived decoders could accept positional arrays for values the UI
tree schema defines as objects. For example, row props could be written
as `[1, "red"]`, tying their meaning to the order of Rust fields.

## What changed

Require JSON objects for typed elements and their props while retaining
literal string nodes and child arrays. Pass object fields directly to
the derived decoders so duplicate and unknown fields are still rejected.

## Testing

Add regression cases for positional props, positional elements at the
root and inside children, and duplicate keys. Verify that named row
layout props round-trip through JSON.

GitOrigin-RevId: 81fbd048e8b7b1df6b453d97c9e16e8194a451a6
2026-11-30 19:39:47 +00:00

389 lines
12 KiB
Rust

//! Display elements for the terminal UI and their JSON representation.
//! See `ui_tree/AGENTS.md` for the object deserialization rule.
mod decode;
mod render;
mod theme;
pub(crate) use render::PreparedUiTree;
pub(crate) use render::sanitize_leaf;
use theme::Color;
use theme::TextWeight;
#[cfg(test)]
#[path = "ui_tree_tests.rs"]
mod tests;
use serde::Deserialize;
use serde::Serialize;
const MAX_SAFE_INTEGER: u64 = (1 << 53) - 1;
const MAX_TEXT_BYTES: usize = 16 * 1024;
/// A nullable root. JSON is limited to 64 KiB, 256 non-null nodes, depth 16 (root at 0),
/// and 16 KiB of UTF-8 text across all string leaves.
#[derive(Clone, Debug, PartialEq, Serialize)]
#[cfg_attr(test, derive(ts_rs::TS), ts(export_to = "statusline.d.ts"))]
pub(crate) struct UiTree(pub(crate) Option<UiNode>);
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(
remote = "Self",
tag = "type",
rename_all = "kebab-case",
deny_unknown_fields
)]
#[cfg_attr(
test,
derive(ts_rs::TS),
ts(export_to = "statusline.d.ts", rename = "Element")
)]
pub(crate) enum UiNode {
Text {
#[serde(default, skip_serializing_if = "is_default")]
#[cfg_attr(test, ts(as = "Option<TextProps>", optional))]
props: TextProps,
children: Vec<Option<UiNode>>,
},
Link {
props: LinkProps,
children: Vec<Option<UiNode>>,
},
Row {
props: RowProps,
children: Vec<Option<UiNode>>,
},
/// Each direct child is one item. Use list-item to compose an item from siblings.
List {
#[serde(default, skip_serializing_if = "is_default")]
#[cfg_attr(test, ts(as = "Option<ListProps>", optional))]
props: ListProps,
children: Vec<UiNode>,
},
ListItem {
children: Vec<Option<UiNode>>,
},
/// Empty flex item sharing spare space on its parent's main axis.
Spacer {
#[serde(default, skip_serializing_if = "is_default")]
#[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<BadgeProps>", optional))]
props: BadgeProps,
children: BadgeChildren,
},
Box {
props: BoxProps,
children: Vec<Option<UiNode>>,
},
Col {
props: ColProps,
children: Vec<Option<UiNode>>,
},
Bold {
children: Vec<Option<UiNode>>,
},
Italic {
children: Vec<Option<UiNode>>,
},
Underline {
children: Vec<Option<UiNode>>,
},
/// An inline span with preserved whitespace and its own theme colors.
Code {
children: Vec<Option<UiNode>>,
},
#[serde(untagged)]
String(String),
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[cfg_attr(test, derive(ts_rs::TS), ts(export_to = "statusline.d.ts"))]
#[serde(remote = "Self", deny_unknown_fields)]
pub(crate) struct IconNode {
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(remote = "Self", 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<bool>", 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(remote = "Self", deny_unknown_fields)]
#[cfg_attr(test, derive(ts_rs::TS), ts(export_to = "statusline.d.ts"))]
pub(crate) struct ListProps {
#[serde(
default,
deserialize_with = "decode::token",
skip_serializing_if = "is_default"
)]
#[cfg_attr(test, ts(as = "Option<ListMarker>", optional))]
marker: ListMarker,
}
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
#[cfg_attr(test, derive(ts_rs::TS), ts(export_to = "statusline.d.ts"))]
enum ListMarker {
#[default]
Bullet,
Number,
None,
}
#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
#[serde(remote = "Self", deny_unknown_fields)]
#[cfg_attr(test, derive(ts_rs::TS), ts(export_to = "statusline.d.ts"))]
pub(crate) struct BadgeProps {
#[serde(
default,
deserialize_with = "decode::token",
skip_serializing_if = "is_default"
)]
#[cfg_attr(test, ts(as = "Option<BadgeColor>", optional))]
color: BadgeColor,
}
#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
#[cfg_attr(test, derive(ts_rs::TS), ts(export_to = "statusline.d.ts"))]
enum BadgeColor {
#[default]
Secondary,
Info,
Success,
Warning,
Danger,
}
/// A box defaults to a column when direction is omitted.
/// Horizontal boxes group adjacent strings even without justify. Use separate elements for a gap.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(untagged)]
#[cfg_attr(test, derive(ts_rs::TS), ts(export_to = "statusline.d.ts"))]
pub(crate) enum BoxProps {
Directed(DirectedBox),
DefaultColumn(#[cfg_attr(test, ts(type = "BoxColumnProps & { direction?: never }"))] ColProps),
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(tag = "direction", rename_all = "lowercase")]
#[cfg_attr(test, derive(ts_rs::TS), ts(export_to = "statusline.d.ts"))]
pub(crate) enum DirectedBox {
Row(RowProps),
Col(#[cfg_attr(test, ts(type = "BoxColumnProps"))] ColProps),
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(remote = "Self", deny_unknown_fields)]
#[cfg_attr(test, derive(ts_rs::TS), ts(export_to = "statusline.d.ts"))]
pub(crate) struct ColProps {
/// Blank terminal rows between flex items, as a non-negative JavaScript-safe integer.
/// Adjacent strings form one item. Separate elements each take a slot, even when empty.
#[serde(deserialize_with = "decode::gap")]
#[cfg_attr(test, ts(type = "number"))]
gap: u64,
}
#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
#[serde(remote = "Self", default, deny_unknown_fields)]
#[cfg_attr(test, derive(ts_rs::TS), ts(export_to = "statusline.d.ts", optional_fields = nullable))]
pub(crate) struct TextProps {
#[serde(
deserialize_with = "decode::optional_token",
skip_serializing_if = "Option::is_none"
)]
color: Option<Color>,
#[serde(
deserialize_with = "decode::optional_token",
skip_serializing_if = "Option::is_none"
)]
weight: Option<TextWeight>,
#[serde(skip_serializing_if = "Option::is_none")]
italic: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
underline: Option<bool>,
/// Preserve spaces and tabs across styled children.
#[serde(rename = "preserveWhitespace", skip_serializing_if = "is_default")]
#[cfg_attr(test, ts(as = "Option<bool>", optional))]
preserve_whitespace: bool,
/// Clamp this text block after wrapping. Must be a positive safe integer.
/// If support is unknown for app.cli_version, return a literal string for the entire tree.
#[serde(
rename = "maxLines",
deserialize_with = "decode::max_lines",
skip_serializing_if = "Option::is_none"
)]
#[cfg_attr(test, ts(type = "number", optional))]
max_lines: Option<u64>,
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(remote = "Self", deny_unknown_fields)]
#[cfg_attr(test, derive(ts_rs::TS), ts(export_to = "statusline.d.ts", optional_fields = nullable))]
pub(crate) struct LinkProps {
pub(crate) href: LinkHref,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub(crate) title: Option<String>,
}
/// An absolute HTTP(S) URL without control characters, at most 8 KiB in UTF-8.
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(try_from = "String")]
#[cfg_attr(
test,
derive(ts_rs::TS),
ts(export_to = "statusline.d.ts", type = "string")
)]
pub(crate) struct LinkHref(String);
impl TryFrom<String> for LinkHref {
type Error = &'static str;
fn try_from(value: String) -> Result<Self, Self::Error> {
Self::try_from(value.as_str())
}
}
impl TryFrom<&str> for LinkHref {
type Error = &'static str;
fn try_from(value: &str) -> Result<Self, Self::Error> {
crate::terminal_hyperlinks::web_destination(value)
.filter(|destination| destination == value)
.map(Self)
.ok_or("link href must be an absolute HTTP(S) URL of at most 8 KiB without control characters")
}
}
/// A root row receives the available footer width. A row inside another row takes up to its content width.
/// An explicit `justify` groups adjacent bare strings into one item. Use separate `text` or `row`
/// elements to position fields independently. Rows with a direct spacer also group adjacent strings. Other rows with omitted
/// `justify` keep gaps between authored children.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(remote = "Self", deny_unknown_fields)]
#[cfg_attr(test, derive(ts_rs::TS), ts(export_to = "statusline.d.ts", optional_fields = nullable))]
pub(crate) struct RowProps {
/// Horizontal spacing in terminal columns, expressed as a non-negative JavaScript-safe integer.
#[serde(deserialize_with = "decode::gap")]
#[cfg_attr(test, ts(type = "number"))]
pub(crate) gap: u64,
#[serde(
default,
deserialize_with = "decode::optional_token",
skip_serializing_if = "Option::is_none"
)]
background: Option<Color>,
#[serde(
default,
deserialize_with = "decode::token",
skip_serializing_if = "is_default"
)]
#[cfg_attr(test, ts(as = "Option<RowWrap>", optional))]
wrap: RowWrap,
/// Position each line's items at the `start`, `center`, or `end`.
/// `between` distributes spare columns across the gaps between children.
#[serde(
default,
deserialize_with = "decode::present_token",
skip_serializing_if = "Option::is_none"
)]
#[cfg_attr(test, ts(optional))]
justify: Option<RowJustify>,
}
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
#[cfg_attr(test, derive(ts_rs::TS), ts(export_to = "statusline.d.ts"))]
enum RowWrap {
#[default]
Nowrap,
Wrap,
}
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
#[cfg_attr(test, derive(ts_rs::TS), ts(export_to = "statusline.d.ts"))]
enum RowJustify {
#[default]
Start,
Center,
End,
Between,
}
fn is_default<T: Default + PartialEq>(value: &T) -> bool {
*value == T::default()
}