Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions gateway/run.py
Original file line number Diff line number Diff line change
Expand Up @@ -9161,13 +9161,17 @@ async def _handle_message_with_agent(self, event, source, _quick_key: str, run_g
if _show_reasoning_effective and response and not _intentional_silence:
last_reasoning = agent_result.get("last_reasoning")
if last_reasoning:
from gateway.stream_consumer import escape_code_fences_for_display
# Collapse long reasoning to keep messages readable
lines = last_reasoning.strip().splitlines()
if len(lines) > 15:
display_reasoning = "\n".join(lines[:15])
display_reasoning += f"\n_... ({len(lines) - 15} more lines)_"
else:
display_reasoning = last_reasoning.strip()
# Escape ``` inside reasoning so inner fences don't
# break the outer code block used to render it.
display_reasoning = escape_code_fences_for_display(display_reasoning)
response = f"💭 **Reasoning:**\n```\n{display_reasoning}\n```\n\n{response}"

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Current main now chooses subtext, blockquote, or code after building display_reasoning (gateway/run.py:11807-11818). Apply this transformation only in the fenced code branch; otherwise Discord's default subtext and blockquote output gain visible backslashes despite having no enclosing fence.

# Runtime-metadata footer — only on the FINAL message of the turn.
Expand Down
18 changes: 18 additions & 0 deletions gateway/stream_consumer.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,24 @@
_COMMENTARY = object()


def escape_code_fences_for_display(text: str) -> str:
"""Escape triple-backtick markers so text can be safely wrapped
inside an outer ``` code block without breaking the fence.

When reasoning content contains ``` (e.g. the model quotes code
in its thinking), wrapping it in an outer ``` for display causes
the inner fence to break the outer block. Solution: replace each
`` ``` `` with `` \\`\\`\\` `` before wrapping.

Returns:
The input text with each `` ``` `` replaced by `` \\`\\`\\` ``,
or the input unchanged if no triple-backticks are present.
"""
if not isinstance(text, str) or "```" not in text:
return text
return text.replace("```", "\\`\\`\\`")
Comment on lines +50 to +65

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The function is annotated str -> str, but this branch intentionally returns None and the added test asserts that behavior. Please either annotate the accepted/returned optional type or make the helper strictly string-only and remove the None case.



@dataclass
class StreamConsumerConfig:
"""Runtime config for a single stream consumer instance."""
Expand Down
45 changes: 45 additions & 0 deletions tests/gateway/test_escape_reasoning_fences.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
"""
Tests for escape_code_fences_for_display.

B1: Escape triple-backtick markers inside reasoning text before wrapping
in an outer ``` fence, so inner ``` doesn't break the outer block.
"""

import pytest
from gateway.stream_consumer import escape_code_fences_for_display


class TestEscapeCodeFencesForDisplay:
"""escape_code_fences_for_display prevents inner ``` from breaking
the outer code block used to render reasoning."""

def test_no_fence_passthrough(self):
text = "plain reasoning text"
assert escape_code_fences_for_display(text) == text

def test_single_fence_escaped(self):
text = "model used ```python\nx = 1\n``` in its thinking"
result = escape_code_fences_for_display(text)
assert "```" not in result
assert "\\`\\`\\`" in result

def test_multiple_fences_all_escaped(self):
text = "```\nblock1\n``` and ```python\nblock2\n```"
result = escape_code_fences_for_display(text)
assert result.count("```") == 0
assert result.count("\\`\\`\\`") == 4

def test_empty_string(self):
assert escape_code_fences_for_display("") == ""

def test_none_returns_none(self):
assert escape_code_fences_for_display(None) is None

def test_integration_with_outer_fence(self):
"""Simulates the gateway's reasoning wrapping logic."""
raw = "thinking about:\n```python\nprint('hi')\n```\nok"
escaped = escape_code_fences_for_display(raw)
wrapped = f"💭 **Reasoning:**\n```\n{escaped}\n```\n\nHere's the answer."
# The outer ``` should not be broken by inner ```
assert wrapped.count("```") == 2 # only outer open + close
assert "\\`\\`\\`" in wrapped