Skip to content
Closed
Show file tree
Hide file tree
Changes from 2 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
21 changes: 20 additions & 1 deletion gateway/platforms/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -4851,7 +4851,26 @@ def truncate_message(

# Everything remaining fits in one final chunk
if _len(prefix) + _len(remaining) <= max_length - INDICATOR_RESERVE:
chunks.append(prefix + remaining)
final_chunk = prefix + remaining
# Check fence balance: if carry_lang was set, the chunk
# starts with an opening fence. Walk the remaining text
# to see if the code block was closed; if not, close it.
_final_in_code = carry_lang is not None
_final_lang = carry_lang or ""
if _final_in_code:
for _line in remaining.split("\n"):
_stripped = _line.strip()
if _stripped.startswith("```"):
Comment on lines 4852 to +4863
if _final_in_code:
_final_in_code = False
_final_lang = ""
else:
_final_in_code = True
_tag = _stripped[3:].strip()
_final_lang = _tag.split()[0] if _tag else ""
if _final_in_code:
final_chunk += FENCE_CLOSE
chunks.append(final_chunk)
break

# Find a natural split point (prefer newlines, then spaces).
Expand Down
44 changes: 38 additions & 6 deletions gateway/stream_consumer.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,16 +37,38 @@

# Sentinel to signal the stream is complete
_DONE = object()

# Sentinel to signal a tool boundary — finalize current message and start a
# new one so that subsequent text appears below tool progress messages.
_NEW_SEGMENT = object()

# Queue marker for a completed assistant commentary message emitted between
# API/tool iterations (for example: "I'll inspect the repo first.").
_COMMENTARY = object()


def ensure_closed_code_fences(text: str) -> str:
"""Append a closing `` ``` `` fence if the text has an odd number of
triple-backtick markers.

When model output is truncated mid-code-block (e.g. by token limits
or a finish_reason="length"), the resulting message has an unclosed
code fence. On Discord, Slack, and other platforms this causes
everything after the orphaned fence to render as a single code block.

The fix is trivial: count `` ``` `` occurrences. If odd, append a
closing fence on its own line. This is safe because nested
triple-backtick fences (e.g. a literal `` ``` `` inside a code block)
are exceedingly rare in model output and, when they do appear, the
extra closing fence just creates a brief empty code block at the end
of the message — far less harmful than the entire message being one
giant code block.

Returns:
The input text with a closing fence appended if needed, or the
input text unchanged.
"""
if not isinstance(text, str) or not text:
return text
if text.count("```") % 2 == 1:
return text.rstrip("\n") + "\n```"
return text


@dataclass
class StreamConsumerConfig:
"""Runtime config for a single stream consumer instance."""
Expand Down Expand Up @@ -855,6 +877,10 @@ async def _send_fallback_final(self, text: str) -> None:
Retries each chunk once on flood-control failures with a short delay.
"""
final_text = self._clean_for_display(text)
# Ensure balanced code fences before computing continuation,
# so the closing fence reaches the user even when the fallback
# only delivers the tail after mid-stream edits failed.
final_text = ensure_closed_code_fences(final_text)
continuation = self._continuation_text(final_text)
self._fallback_final_send = False
if not continuation.strip():
Expand Down Expand Up @@ -1333,6 +1359,12 @@ async def _send_or_edit(
# Media files are delivered as native attachments after the stream
# finishes (via _deliver_media_from_response in gateway/run.py).
text = self._clean_for_display(text)
# Ensure code fences are balanced before send/edit. Model output
# truncated mid-code-block (e.g. finish_reason="length") leaves an
# orphaned ``` which, on Discord/Slack/Matrix, causes the entire
# remaining output to render as a single code block. This covers
# the streaming edit path (G2) and first-send path alike.
text = ensure_closed_code_fences(text)
# A bare streaming cursor is not meaningful user-visible content and
# can render as a stray tofu/white-box message on some clients.
visible_without_cursor = text
Expand Down
Loading