Skip to content

armgit / codex

Public Imported from GitHub
0

Lightweight coding agent that runs in your terminal

Rust

Support line breaks in Mermaid flowchart node labels (#54419)

Eric Traut9fcb1f5ed49c
diff --git a/codex-rs/mermaid/README.md b/codex-rs/mermaid/README.md
index b46db7067b..46f9a04d8d 100644
--- a/codex-rs/mermaid/README.md
+++ b/codex-rs/mermaid/README.md
@@ -27,12 +27,12 @@ return types. ER attribute types and names use the identifier grammar above.
Flowchart node and edge labels may be enclosed in double quotes. Literal
ampersands are supported in labels, as is printable punctuation after parsing.
Quotes protect flowchart label delimiters such as brackets, pipes, and
-semicolons. HTML and entity escapes remain unsupported and return an error
-before statement splitting.
+semicolons. Flowchart node labels support `<br>`, `<br/>`, and `<br />` as
+line breaks. Other HTML and entity escapes remain unsupported.
These are explicit subsets, not complete Mermaid compatibility. Compound states,
flowchart subgraphs, other shapes, sequence activation and parallel fragments,
-styling, front matter, directives, HTML, escapes, combining/zero-width characters,
+styling, front matter, directives, other HTML, escapes, combining/zero-width characters,
and ligatures with non-additive widths return errors. Callers should retain source
on any error; the library never returns a partial diagram.
@@ -61,8 +61,8 @@ named participants. States use separate `● initial` and `◎ final` nodes.
All inputs are limited to 16 KiB. Graphs allow 16 nodes, 24 edges (after expanding
`&` groups), and 16 members per node. Each `&` group allows at most 24 node references. Sequences allow 8 participants, 64 events (including fragment boundaries),
-and 4 fragment levels. Source labels and identifiers are limited to 40 display
-cells/ASCII bytes respectively. Rendered canvases are capped at 65,536 cells,
+and 4 fragment levels. Labels are limited to 40 display cells per line; identifiers
+are limited to 40 ASCII bytes. Rendered canvases are capped at 65,536 cells,
independent of the caller's maximum width. The library performs no I/O.
From `codex-rs`, preview a file, optionally specifying the available width:
diff --git a/codex-rs/mermaid/src/draw.rs b/codex-rs/mermaid/src/draw.rs
index eb79905ca0..3d42d0a0fb 100644
--- a/codex-rs/mermaid/src/draw.rs
+++ b/codex-rs/mermaid/src/draw.rs
@@ -19,11 +19,14 @@ pub(super) fn render(graph: &Graph, max_width: usize) -> Result<Vec<Vec<Span>>,
.nodes
.iter()
.map(|node| {
- let mut lines = vec![if node.shape == Shape::Decision {
- format!("◇ {}", node.label)
- } else {
- node.label.clone()
- }];
+ let mut lines = node
+ .label
+ .split('\n')
+ .map(str::to_owned)
+ .collect::<Vec<_>>();
+ if node.shape == Shape::Decision {
+ lines[0].insert_str(0, "◇ ");
+ }
if !node.members.is_empty() {
lines.push("─".repeat(node.label.width()));
lines.extend(node.members.iter().cloned());
diff --git a/codex-rs/mermaid/src/parse.rs b/codex-rs/mermaid/src/parse.rs
index 141ac37e80..c31b66f799 100644
--- a/codex-rs/mermaid/src/parse.rs
+++ b/codex-rs/mermaid/src/parse.rs
@@ -50,6 +50,7 @@ pub(super) fn parse(header: &str, body: &[&str]) -> Result<Graph, RenderError> {
if let Some(after) = rest.strip_prefix('|') {
let (text, remaining) = delimited_label(after, "|")?;
label = flowchart_label(text)?.to_owned();
+ check_label(&label)?;
rest = remaining;
}
(source, target, dashed)
@@ -71,6 +72,7 @@ pub(super) fn parse(header: &str, body: &[&str]) -> Result<Graph, RenderError> {
.strip_prefix('>')
.ok_or(RenderError::Unsupported)?;
label = flowchart_label(text.trim())?.to_owned();
+ check_label(&label)?;
('─', '◄', dashed)
};
let to = nodes(&mut rest, &mut graph)?;
@@ -137,13 +139,22 @@ fn node(rest: &mut &str, graph: &mut Graph) -> Result<usize, RenderError> {
let index = graph.node(id)?;
if let Some((open, close, shape)) = declaration {
let (label, remaining) = delimited_label(&rest[open.len()..], close)?;
- let label = flowchart_label(label)?;
+ let label = flowchart_label(label)?
+ .replace("<br>", "\n")
+ .replace("<br/>", "\n")
+ .replace("<br />", "\n");
+ if label.trim().is_empty() {
+ return Err(RenderError::Unsupported);
+ }
+ for line in label.split('\n').filter(|line| !line.is_empty()) {
+ check_label(line)?;
+ }
*rest = remaining;
let node = &mut graph.nodes[index];
if node.declared && (node.label != label || node.shape != shape) {
return Err(RenderError::Unsupported);
}
- node.label = label.to_owned();
+ node.label = label;
node.shape = shape;
node.declared = true;
}
@@ -166,7 +177,6 @@ fn flowchart_label(label: &str) -> Result<&str, RenderError> {
if label.contains('"') {
return Err(RenderError::Unsupported);
}
- check_label(label)?;
Ok(label)
}
diff --git a/codex-rs/mermaid/src/snapshots/codex_mermaid__tests__stadiums_with_other_shapes_in_every_direction.snap b/codex-rs/mermaid/src/snapshots/codex_mermaid__tests__stadiums_with_other_shapes_in_every_direction.snap
index fb79a2f76e..74729a4493 100644
--- a/codex-rs/mermaid/src/snapshots/codex_mermaid__tests__stadiums_with_other_shapes_in_every_direction.snap
+++ b/codex-rs/mermaid/src/snapshots/codex_mermaid__tests__stadiums_with_other_shapes_in_every_direction.snap
@@ -1,11 +1,12 @@
---
source: mermaid/src/tests.rs
-assertion_line: 35
+assertion_line: 36
expression: "cases.join(\"\\n\\n\")"
---
TD
╭─────────╮
│ 请求 │
+│ Ready │
│ ├──go───┐
│ ├──go───╪─┐
│ ├◄──────╪─╪───┐
@@ -16,6 +17,7 @@ TD
│ │ │ │ ┆
┌─────────┐ │ │ │ │ ┆
│ Work │ │ │ │ │ ┆
+│ next │ │ │ │ │ ┆
│ ├◄──────┘ │ │ │ ┆
│ ├─┄no┄┄┄┄┄╪┄┐ │ │ ┆
│ ├─────────╪─╪─╪─┘ ┆
@@ -26,6 +28,7 @@ TD
│ ┆ │ ┆
┌─────────┐ │ ┆ │ ┆
│ ◇ Done? │ │ ┆ │ ┆
+│ Retry? │ │ ┆ │ ┆
│ ├◄────────┘ ┆ │ ┆
│ ├◄┄┄┄┄┄┄┄┄┄┄┘ │ ┆
│ ├◄────────────┘ ┆
@@ -35,6 +38,7 @@ TD
BT
┌─────────┐
│ ◇ Done? │
+│ Retry? │
│ ├◄────────┐
│ ├◄┄┄┄┄┄┄┄┄╪┄┐
│ ├◄────────╪─╪─┐
@@ -44,6 +48,7 @@ BT
│ ┆ │ ┆
┌─────────┐ │ ┆ │ ┆
│ Work │ │ ┆ │ ┆
+│ next │ │ ┆ │ ┆
│ ├◄──────┐ │ ┆ │ ┆
│ ├─┄no┄┄┄╪┄╪┄┘ │ ┆
│ ├───────╪─╪───╪─┐ ┆
@@ -54,6 +59,7 @@ BT
│ │ │ │ ┆
╭─────────╮ │ │ │ │ ┆
│ 请求 │ │ │ │ │ ┆
+│ Ready │ │ │ │ │ ┆
│ ├──go───┘ │ │ │ ┆
│ ├──go─────┘ │ │ ┆
│ ├◄────────────┘ │ ┆
@@ -64,6 +70,7 @@ BT
LR
╭────────────────────╮ ┌────────────────────┐ ┌────────────────┐
│ 请求 │ │ Work │ │ ◇ Done? │
+│ Ready │ │ next │ │ Retry? │
╰┬───┬───┬───┬───┬───╯ └┬───┬───┬───┬───┬───┘ └┬───┬───┬───┬───┘
│ │ ▲ │ ▲ ▲ │ │ │ ▲ ▲ ▲ ▲ │
│go │go │ │ ┆ │ ┆no │ ┆ ┆ │ ┆ │ ┆
@@ -86,6 +93,7 @@ LR
RL
┌────────────────┐ ┌────────────────────┐ ╭────────────────────╮
│ ◇ Done? │ │ Work │ │ 请求 │
+│ Retry? │ │ next │ │ Ready │
└┬───┬───┬───┬───┘ └┬───┬───┬───┬───┬───┘ ╰┬───┬───┬───┬───┬───╯
▲ ▲ ▲ │ ▲ │ │ │ ▲ │ │ ▲ │ ▲
│ ┆ │ ┆ │ ┆no │ ┆ ┆ │go │go │ │ ┆
diff --git a/codex-rs/mermaid/src/tests.rs b/codex-rs/mermaid/src/tests.rs
index 12478d4622..cabc9ae3c8 100644
--- a/codex-rs/mermaid/src/tests.rs
+++ b/codex-rs/mermaid/src/tests.rs
@@ -25,7 +25,7 @@ fn stadiums_with_other_shapes_in_every_direction() {
let mut cases = Vec::new();
for direction in ["TD", "BT", "LR", "RL"] {
let source = format!(
- "flowchart {direction}; A([请求]) -- go --> B[Work] & C{{Done?}}; B -. no .-> C; C <--> A; B --- A; C -.- B; A <-.-> B"
+ "flowchart {direction}; A([\"请求<br>Ready\"]) -- go --> B[Work<br/>next] & C{{\"Done?<br />Retry?\"}}; B -. no .-> C; C <--> A; B --- A; C -.- B; A <-.-> B"
);
let output = render(&source, /*max_width*/ 100).unwrap();
let width = output.lines().map(UnicodeWidthStr::width).max().unwrap();
@@ -182,6 +182,8 @@ fn quoted_flowchart_labels_reject_malformed_and_unsafe_text() {
"\"\"",
"\"<b>HTML</b>\"",
"\"before <b\"",
+ "\"one<br/><b>two</b>\"",
+ "\"one<br class='x'>two\"",
"\"\u{1b}\"",
] {
for source in [
@@ -260,6 +262,9 @@ fn rejects_partial_or_unsupported_input() {
"flowchart TD; A -->|unclosed B",
"flowchart TD; A[لا]",
"flowchart TD; A -->|yes┐| B",
+ "flowchart TD; A -->|one<br/>two| B",
+ "flowchart TD; A -- one<br>two --> B",
+ "flowchart TD; A[<br/><br />]",
] {
assert_eq!(
render(source, /*max_width*/ 100),
@@ -281,6 +286,7 @@ fn source_graph_and_width_limits() {
format!("graph; {} --> B", ["A"; 25].join(" & ")),
format!("graph TD; A[\"{}\"]", "[]".repeat(21)),
format!("graph TD; A([{}])", "x".repeat(41)),
+ format!("graph TD; A[\"ok<br />{}\"]", "界".repeat(21)),
format!(
"graph TD; {}",
(0..17).map(|n| format!("N{n};")).collect::<String>()
@@ -289,13 +295,15 @@ fn source_graph_and_width_limits() {
] {
assert_eq!(render(&source, /*max_width*/ 200), Err(RenderError::Limit));
}
- let output = render("graph TD; A --> B", /*max_width*/ 100).unwrap();
- let width = output.lines().map(UnicodeWidthStr::width).max().unwrap();
- assert_eq!(render("graph TD; A --> B", width), Ok(output));
- assert_eq!(
- render("graph TD; A --> B", width - 1),
- Err(RenderError::TooWide)
+ let source = format!(
+ "graph LR; A[\"{}<br/>{}\"] --> B[Done]",
+ "界".repeat(20),
+ "x".repeat(40)
);
+ let output = render(&source, /*max_width*/ 100).unwrap();
+ let width = output.lines().map(UnicodeWidthStr::width).max().unwrap();
+ assert_eq!(render(&source, width), Ok(output));
+ assert_eq!(render(&source, width - 1), Err(RenderError::TooWide));
assert_eq!(
render("graph TD; A", /*max_width*/ 0),
Err(RenderError::TooWide)
diff --git a/codex-rs/tui/src/streaming/mermaid_tests.rs b/codex-rs/tui/src/streaming/mermaid_tests.rs
index 8ff2613043..35a10075d6 100644
--- a/codex-rs/tui/src/streaming/mermaid_tests.rs
+++ b/codex-rs/tui/src/streaming/mermaid_tests.rs
@@ -12,7 +12,7 @@ fn mermaid_stream_closes_resizes_and_preserves_raw_source() {
let mut stages = Vec::new();
for chunk in [
"Before.\n\n```mermaid\n",
- "flowchart LR\nA[Request] --> B[Reply]\n",
+ "flowchart LR\nA[\"Codex reply<br/>completed\"] --> B[\"Rendered in Ghostty\"]\n",
"```\n",
"\nAfter.\n",
] {
@@ -142,7 +142,7 @@ fn mermaid_holdback_tracks_nested_blocks_after_normalized_markdown() {
fn mermaid_controller_keeps_diagram_mutable_and_returns_original_source() {
let mut controller =
StreamController::new(Some(80), &std::env::temp_dir(), HistoryRenderMode::Rich);
- let source = "```mermaid\nflowchart LR\nA[Request] --> B[Reply]\n```\n";
+ let source = "```mermaid\nflowchart LR\nA[Request<br />completed] --> B[Reply]\n```\n";
for chunk in source.split_inclusive('\n') {
controller.push(chunk);
assert!(
@@ -161,7 +161,7 @@ fn mermaid_controller_keeps_diagram_mutable_and_returns_original_source() {
controller
.current_tail_lines()
.iter()
- .any(|line| line.line.to_string().contains("A[Request]"))
+ .any(|line| line.line.to_string().contains("A[Request<br />completed]"))
);
controller.set_width(Some(80));
assert_eq!(controller.current_tail_lines(), diagram);
@@ -169,7 +169,7 @@ fn mermaid_controller_keeps_diagram_mutable_and_returns_original_source() {
crate::markdown::extract_copy_targets(source),
vec![crate::markdown::CopyTarget::Code {
language: Some("mermaid".to_owned()),
- content: std::sync::Arc::from("flowchart LR\nA[Request] --> B[Reply]\n"),
+ content: std::sync::Arc::from("flowchart LR\nA[Request<br />completed] --> B[Reply]\n"),
}],
);
let mut full_source = source.to_owned();
@@ -199,7 +199,7 @@ fn mermaid_controller_keeps_diagram_mutable_and_returns_original_source() {
controller
.current_tail_lines()
.iter()
- .any(|line| line.line.to_string().contains("A[Request]"))
+ .any(|line| line.line.to_string().contains("A[Request<br />completed]"))
);
controller.set_width(Some(80));
assert_eq!(controller.current_tail_lines(), second_diagram);
diff --git a/codex-rs/tui/src/streaming/snapshots/codex_tui__streaming__mermaid_tests__mermaid_stream_closes_resizes_and_preserves_raw_source.snap b/codex-rs/tui/src/streaming/snapshots/codex_tui__streaming__mermaid_tests__mermaid_stream_closes_resizes_and_preserves_raw_source.snap
index d19f7ec28e..87bcf39b11 100644
--- a/codex-rs/tui/src/streaming/snapshots/codex_tui__streaming__mermaid_tests__mermaid_stream_closes_resizes_and_preserves_raw_source.snap
+++ b/codex-rs/tui/src/streaming/snapshots/codex_tui__streaming__mermaid_tests__mermaid_stream_closes_resizes_and_preserves_raw_source.snap
@@ -1,5 +1,6 @@
---
source: tui/src/streaming/mermaid_tests.rs
+assertion_line: 78
expression: "stages.join(\"\\n\\n---\\n\\n\")"
---
Before.
@@ -10,33 +11,35 @@ Before.
Before.
flowchart LR
-A[Request] --> B[Reply]
+A["Codex reply<br/>completed"] --> B["Rendered in Ghostty"]
---
Before.
-┌─────────┐ ┌───────┐
-│ Request │ │ Reply │
-└┬────────┘ └┬──────┘
- │ ▲
- │ │
- │ │
- │ │
- └────────────┘
+┌─────────────┐ ┌─────────────────────┐
+│ Codex reply │ │ Rendered in Ghostty │
+│ completed │ │ │
+└┬────────────┘ └┬────────────────────┘
+ │ ▲
+ │ │
+ │ │
+ │ │
+ └────────────────┘
---
Before.
-┌─────────┐ ┌───────┐
-│ Request │ │ Reply │
-└┬────────┘ └┬──────┘
- │ ▲
- │ │
- │ │
- │ │
- └────────────┘
+┌─────────────┐ ┌─────────────────────┐
+│ Codex reply │ │ Rendered in Ghostty │
+│ completed │ │ │
+└┬────────────┘ └┬────────────────────┘
+ │ ▲
+ │ │
+ │ │
+ │ │
+ └────────────────┘
After.
@@ -53,7 +56,7 @@ current
terminal
width.
flowchart LR
-A[Request] --> B[Reply]
+A["Codex reply<br/>completed"] --> B["Rendered in Ghostty"]
After.
@@ -63,7 +66,7 @@ Before.
```mermaid
flowchart LR
-A[Request] --> B[Reply]
+A["Codex reply<br/>completed"] --> B["Rendered in Ghostty"]
```
After.
@@ -72,13 +75,14 @@ After.
Before.
-┌─────────┐ ┌───────┐
-│ Request │ │ Reply │
-└┬────────┘ └┬──────┘
- │ ▲
- │ │
- │ │
- │ │
- └────────────┘
+┌─────────────┐ ┌─────────────────────┐
+│ Codex reply │ │ Rendered in Ghostty │
+│ completed │ │ │
+└┬────────────┘ └┬────────────────────┘
+ │ ▲
+ │ │
+ │ │
+ │ │
+ └────────────────┘
After.