Skip to content

The agent engineering platform.

test(core): URL-encode bgColor parameter in mermaid.ink API calls (#34466)

Harikrishna KP294dda8df27f
diff --git a/libs/core/langchain_core/runnables/graph_mermaid.py b/libs/core/langchain_core/runnables/graph_mermaid.py
index 1a1d7aa667..ddef49b866 100644
--- a/libs/core/langchain_core/runnables/graph_mermaid.py
+++ b/libs/core/langchain_core/runnables/graph_mermaid.py
@@ -435,7 +435,7 @@ def _render_mermaid_using_api(
if background_color is not None and not _HEX_COLOR_PATTERN.match(background_color):
background_color = f"!{background_color}"
- # URL-encode the background color to handle special characters like '!'
+ # URL-encode the background_color to handle special characters like '!'
encoded_bg_color = urllib.parse.quote(str(background_color), safe="")
image_url = (
f"{base_url}/img/{mermaid_syntax_encoded}"
diff --git a/libs/core/tests/unit_tests/runnables/test_graph.py b/libs/core/tests/unit_tests/runnables/test_graph.py
index 44774c716c..c39dc5e088 100644
--- a/libs/core/tests/unit_tests/runnables/test_graph.py
+++ b/libs/core/tests/unit_tests/runnables/test_graph.py
@@ -655,6 +655,48 @@ def test_graph_draw_mermaid_png_base_url() -> None:
assert url.startswith(custom_url)
+def test_mermaid_bgcolor_url_encoding() -> None:
+ """Test that background_color with special chars is properly URL-encoded.
+
+ Regression test for issue #34444: Named colors like 'white' get prefixed
+ with '!' which must be URL-encoded to avoid HTTP 400 errors from mermaid.ink.
+ """
+ mock_response = MagicMock()
+ mock_response.status_code = 200
+ mock_response.content = b"fake image data"
+
+ with patch("requests.get", return_value=mock_response) as mock_get:
+ _render_mermaid_using_api(
+ "graph TD;\n A --> B;",
+ background_color="white",
+ )
+
+ assert mock_get.called
+ url = mock_get.call_args[0][0]
+ # The '!' character should be URL-encoded as '%21'
+ assert "%21white" in url or "!white" not in url
+ # Verify the URL doesn't contain unencoded '!'
+ assert "bgColor=!white" not in url
+
+
+def test_mermaid_bgcolor_hex_not_encoded() -> None:
+ """Test that hex color codes are not prefixed with '!' and work correctly."""
+ mock_response = MagicMock()
+ mock_response.status_code = 200
+ mock_response.content = b"fake image data"
+
+ with patch("requests.get", return_value=mock_response) as mock_get:
+ _render_mermaid_using_api(
+ "graph TD;\n A --> B;",
+ background_color="#ffffff",
+ )
+
+ assert mock_get.called
+ url = mock_get.call_args[0][0]
+ # Hex colors should be URL-encoded but not prefixed with '!'
+ assert "%23ffffff" in url # '#' encoded as '%23'
+
+
def test_graph_mermaid_special_chars(snapshot: SnapshotAssertion) -> None:
graph = Graph(
nodes={