diff --git a/codex-rs/mermaid/src/families_tests.rs b/codex-rs/mermaid/src/families_tests.rs index 176c031e3a..057adf1914 100644 --- a/codex-rs/mermaid/src/families_tests.rs +++ b/codex-rs/mermaid/src/families_tests.rs @@ -40,10 +40,12 @@ const STATE: &str = "stateDiagram-v2 Shipped --> Delivered: received Delivered --> [*] Rejected --> Draft: revise - Charging: Retry up to 3 times"; + Charging: Retry up to 3 times + Draft: Order drafted + Draft: Awaiting submission"; const CLASS: &str = "classDiagram - class Order { + class order { +String id +Status status +submit() @@ -62,10 +64,10 @@ const CLASS: &str = "classDiagram +String lastFour +authorize() } - Order \"1\" *-- \"1..*\" LineItem : contains - Order \"1\" --> \"1\" Payment : pays with + order \"1\" *-- \"1..*\" LineItem : contains + order \"1\" --> \"1\" Payment : pays with Payment <|-- CardPayment - CardPayment ..> Order : updates"; + CardPayment ..order : updates"; const ER: &str = "erDiagram CUSTOMER ||--o{ ORDER : places @@ -125,6 +127,32 @@ fn unicode_labels_and_later_declarations() { insta::assert_snapshot!("LR", output); } } + for descriptions in [ + vec!["S: Ready"], + vec!["S: Ready", "S: Working"], + vec![r#"state "Ready" as S"#, "S: Working"], + vec!["S: Ready", r#"state "Working" as S"#], + vec![r#"state "Ready" as S"#, r#"state "Working" as S"#], + ] { + // References before and after descriptions must retain the same state identity. + let mut body = vec!["S --> T"]; + body.extend(&descriptions); + body.push("T --> S"); + let graph = super::state::parse(&body).unwrap(); + let mut expected = super::state::parse(&["S --> T", "T --> S"]).unwrap(); + expected.nodes[0] = super::Node { + id: "S".to_owned(), + label: "Ready".to_owned(), + shape: super::Shape::Rectangle, + declared: true, + members: if descriptions.len() == 1 { + Vec::new() + } else { + vec!["Working".to_owned()] + }, + }; + assert_eq!(graph, expected, "{descriptions:?}"); + } } #[test] @@ -164,6 +192,27 @@ fn class_relationship_endpoints() { assert!(ports[1].contains("(many)")); assert_eq!(output.contains('┆'), dashed); } + for (line, target, target_tip, target_label, dashed) in [ + ("A --orange", "orange", '─', "", false), + ("A ..o_range", "o_range", '─', "", true), + ("A --o B", "B", '◇', "", false), + (r#"A ..o"many" B"#, "B", '◇', "(many)", true), + ] { + let graph = super::relations::parse("classDiagram", &[line]).unwrap(); + let mut expected = super::Graph::default(); + let from = expected.node("A").unwrap(); + let to = expected.node(target).unwrap(); + expected.edges.push(super::Edge { + from, + to, + label: String::new(), + target_label: target_label.to_owned(), + source_tip: '─', + target_tip, + dashed, + }); + assert_eq!(graph, expected, "{line}"); + } } #[test] @@ -210,7 +259,6 @@ fn rejects_incomplete_and_unsupported_families() { "sequenceDiagram; participant A as e\u{301}", "stateDiagram-v2; state Processing {; A-->B; }", "stateDiagram-v2; A --> B: ok; garbage text", - "stateDiagram-v2; state \"First\" as A; state \"Second\" as A", "stateDiagram-v2; accDescr: Order lifecycle; [*] --> Ready", "stateDiagram; ACCDESCR: Order lifecycle; [*] --> Ready", "stateDiagram-v2; A:::highlight; A --> B", @@ -269,6 +317,11 @@ fn family_limits() { format!("classDiagram; class A {{; {} }}", "+field;".repeat(17)), format!("erDiagram; A {{; {} }}", "int id;".repeat(17)), format!("stateDiagram-v2; {}", "A --> B;".repeat(25)), + format!("stateDiagram-v2\n{}", "S: Description\n".repeat(18)), + format!( + "stateDiagram-v2\n{}", + "state \"Description\" as S\n".repeat(18) + ), ] { assert_eq!( render(&source, /*max_width*/ usize::MAX), diff --git a/codex-rs/mermaid/src/parse.rs b/codex-rs/mermaid/src/parse.rs index 76049220f6..e07086f56c 100644 --- a/codex-rs/mermaid/src/parse.rs +++ b/codex-rs/mermaid/src/parse.rs @@ -59,6 +59,13 @@ fn node(rest: &mut &str, graph: &mut Graph) -> Result { ) { return Err(RenderError::Unsupported); } + // Longer shape delimiters must not become punctuation inside a simpler node. + if ["[(", "[[", "[/", "[\\", "{{"] + .iter() + .any(|open| rest.starts_with(open)) + { + return Err(RenderError::Unsupported); + } let declaration = match rest.chars().next() { Some('[') => Some(("[", "]", Shape::Rectangle)), Some('{') => Some(("{", "}", Shape::Decision)), @@ -84,6 +91,10 @@ fn node(rest: &mut &str, graph: &mut Graph) -> Result { } fn flowchart_label(label: &str) -> Result<&str, RenderError> { + // Mermaid Markdown strings require rendering beyond ordinary quoted labels. + if label.starts_with("\"`") { + return Err(RenderError::Unsupported); + } let label = if let Some(quoted) = label.strip_prefix('"') { quoted.strip_suffix('"').ok_or(RenderError::Unsupported)? } else { diff --git a/codex-rs/mermaid/src/relations.rs b/codex-rs/mermaid/src/relations.rs index c13f79e151..9b44861be0 100644 --- a/codex-rs/mermaid/src/relations.rs +++ b/codex-rs/mermaid/src/relations.rs @@ -128,6 +128,12 @@ pub(super) fn parse(header: &str, body: &[&str]) -> Result { let mut target_tip = '─'; for (token, tip) in [("|>", '◁'), (">", '◄'), ("*", '◆'), ("o", '◇')] { if let Some(after) = rest.strip_prefix(token) { + // A longer identifier wins over the single-letter aggregation token. + if token == "o" + && after.starts_with(|ch: char| ch.is_ascii_alphanumeric() || ch == '_') + { + continue; + } target_tip = tip; rest = after; break; diff --git a/codex-rs/mermaid/src/snapshots/codex_mermaid__families_tests__class.snap b/codex-rs/mermaid/src/snapshots/codex_mermaid__families_tests__class.snap index 054ec8f946..2f1688f249 100644 --- a/codex-rs/mermaid/src/snapshots/codex_mermaid__families_tests__class.snap +++ b/codex-rs/mermaid/src/snapshots/codex_mermaid__families_tests__class.snap @@ -1,10 +1,9 @@ --- source: mermaid/src/families_tests.rs -assertion_line: 100 expression: output --- ┌──────────────────┐ -│ Order │ +│ order │ │ ───── │ │ +String id │ │ +Status status │ @@ -12,7 +11,7 @@ expression: output │ +cancel() │ │ ├◆─(1) contains────┐ │ ├──(1) pays with───╪─┐ -│ ├◄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄╪┄╪┄┄┄┐ +│ ├─┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄╪┄╪┄┄┄┐ └──────────────────┘ │ │ ┆ │ │ ┆ │ │ ┆ diff --git a/codex-rs/mermaid/src/snapshots/codex_mermaid__families_tests__state.snap b/codex-rs/mermaid/src/snapshots/codex_mermaid__families_tests__state.snap index 23ccd97f5d..a2d15eb2d0 100644 --- a/codex-rs/mermaid/src/snapshots/codex_mermaid__families_tests__state.snap +++ b/codex-rs/mermaid/src/snapshots/codex_mermaid__families_tests__state.snap @@ -1,6 +1,5 @@ --- source: mermaid/src/families_tests.rs -assertion_line: 100 expression: output --- ┌─────────────────────┐ @@ -20,7 +19,9 @@ expression: output │ │ │ │ │ │ │ │ ┌─────────────────────┐ │ │ │ │ -│ Draft │ │ │ │ │ +│ Order drafted │ │ │ │ │ +│ ───────────── │ │ │ │ │ +│ Awaiting submission │ │ │ │ │ │ ├◄────────────┘ │ │ │ │ ├──submit───────┐ │ │ │ │ ├◄──────────────╪─╪───╪─╪───────┐ diff --git a/codex-rs/mermaid/src/state.rs b/codex-rs/mermaid/src/state.rs index 077fd987be..3210e02c66 100644 --- a/codex-rs/mermaid/src/state.rs +++ b/codex-rs/mermaid/src/state.rs @@ -1,4 +1,5 @@ //! Flat state machines, with distinct initial/final pseudostates and labeled transitions. +//! Aliases and descriptions accumulate in source order: first the title, then body rows. use super::Direction; use super::Edge; @@ -32,11 +33,10 @@ pub(super) fn parse(body: &[&str]) -> Result { .strip_prefix("as ") .ok_or(RenderError::Unsupported)?; let index = graph.node(identifier(&mut rest)?)?; - if !rest.trim().is_empty() || graph.nodes[index].declared { + if !rest.trim().is_empty() { return Err(RenderError::Unsupported); } - graph.nodes[index].label = label.to_owned(); - graph.nodes[index].declared = true; + add_description(&mut graph.nodes[index], label)?; continue; } let from = if let Some(after) = rest.strip_prefix("[*]") { @@ -66,10 +66,7 @@ pub(super) fn parse(body: &[&str]) -> Result { } let description = description.trim(); check_label(description)?; - if graph.nodes[from].members.len() == 16 { - return Err(RenderError::Limit); - } - graph.nodes[from].members.push(description.to_owned()); + add_description(&mut graph.nodes[from], description)?; continue; } rest = rest @@ -107,3 +104,16 @@ pub(super) fn parse(body: &[&str]) -> Result { } Ok(graph) } + +fn add_description(node: &mut super::Node, description: &str) -> Result<(), RenderError> { + if !node.declared { + node.label = description.to_owned(); + node.declared = true; + } else { + if node.members.len() == 16 { + return Err(RenderError::Limit); + } + node.members.push(description.to_owned()); + } + Ok(()) +} diff --git a/codex-rs/mermaid/src/tests.rs b/codex-rs/mermaid/src/tests.rs index a81d8ffef6..6ba9f7e7ee 100644 --- a/codex-rs/mermaid/src/tests.rs +++ b/codex-rs/mermaid/src/tests.rs @@ -45,6 +45,22 @@ A[Review & confirm]"#; super::parse::parse("flowchart TD", "ed.lines().collect::>()).unwrap(), super::parse::parse("flowchart TD", &unquoted.lines().collect::>()).unwrap(), ); + for (quoted, label) in [ + (r#"A["(Database)"]"#, "(Database)"), + (r#"A["/Input/"]"#, "/Input/"), + ] { + let graph = super::parse::parse("flowchart TD", &[quoted]).unwrap(); + assert_eq!( + graph.nodes, + vec![super::Node { + id: "A".to_owned(), + label: label.to_owned(), + shape: super::Shape::Rectangle, + declared: true, + members: Vec::new(), + }] + ); + } } #[test] @@ -110,6 +126,17 @@ fn branches_merges_and_retry_loop() { #[test] fn rejects_partial_or_unsupported_input() { for source in [ + "flowchart TD; P --> Q; A[(Database)]", + "flowchart TD; P --> Q; A[/Input/]", + r"flowchart TD; P --> Q; A[\Output\]", + r"flowchart TD; P --> Q; A[/Trapezoid\]", + r"flowchart TD; P --> Q; A[\Inverse/]", + "flowchart TD; P --> Q; A[[Subroutine]]", + "flowchart TD; P --> Q; A{{Hexagon}}", + r#"flowchart TD; P --> Q; A["`hello **world**`"]"#, + r#"flowchart TD; P --> Q; A{"`Decision`"}"#, + r#"flowchart TD; P --> Q; A(["`Stadium`"])"#, + r#"flowchart TD; P --> Q; A -->|"`Caption`"| B"#, "flowchart TD; subgraph X; A; end", "flowchart TD; A --> B; garbage syntax", "flowchart TD; A -.-> B", diff --git a/codex-rs/tui/src/markdown_render/mermaid_tests.rs b/codex-rs/tui/src/markdown_render/mermaid_tests.rs index 5fe87a8c49..9127ac44ce 100644 --- a/codex-rs/tui/src/markdown_render/mermaid_tests.rs +++ b/codex-rs/tui/src/markdown_render/mermaid_tests.rs @@ -112,6 +112,16 @@ fn mermaid_fallback_notices_preserve_source() { for (name, source, width) in [ ("invalid", "```mermaid\nflowchart LR\nA[unfinished\n```", 80), ("unsupported", "```mermaid\npie\n\"Cats\": 2\n```", 80), + ( + "unsupported shape after supported edges", + "```mermaid\nflowchart TD\nP --> Q\nA[(Database)]\n```", + 80, + ), + ( + "Markdown string after supported edges", + "```mermaid\nflowchart TD\nP --> Q\nA[\"`hello **world**`\"]\n```", + 80, + ), ( "too wide", "```mermaid\nflowchart LR\nA[Request] --> B[Reply]\n```", diff --git a/codex-rs/tui/src/markdown_render/snapshots/codex_tui__markdown_render__mermaid__tests__mermaid_fallback_notices_preserve_source.snap b/codex-rs/tui/src/markdown_render/snapshots/codex_tui__markdown_render__mermaid__tests__mermaid_fallback_notices_preserve_source.snap index e7eaf91720..0a0e436b83 100644 --- a/codex-rs/tui/src/markdown_render/snapshots/codex_tui__markdown_render__mermaid__tests__mermaid_fallback_notices_preserve_source.snap +++ b/codex-rs/tui/src/markdown_render/snapshots/codex_tui__markdown_render__mermaid__tests__mermaid_fallback_notices_preserve_source.snap @@ -16,6 +16,22 @@ pie --- +unsupported shape after supported edges +This Mermaid diagram uses features the terminal renderer doesn't support. +flowchart TD +P --> Q +A[(Database)] + +--- + +Markdown string after supported edges +This Mermaid diagram uses features the terminal renderer doesn't support. +flowchart TD +P --> Q +A["`hello **world**`"] + +--- + too wide This Mermaid