fix: remove orphaned SSE event headers when suppressing text deltas

When the cleanup filter suppresses a text delta (buffering inside a
tag), the preceding 'event: content_block_delta' header was left in
the output, producing malformed SSE that caused opencode to retry
rapidly and freeze. Now removes the event header alongside the data
line.
This commit is contained in:
Joey Yakimowich-Payne 2026-03-13 21:39:48 -06:00
commit f5c2c91057

View file

@ -136,12 +136,17 @@ class SSECleanupFilter:
"""Process a raw SSE chunk (may contain multiple lines). """Process a raw SSE chunk (may contain multiple lines).
Returns the (possibly rewritten) chunk to forward downstream. Returns the (possibly rewritten) chunk to forward downstream.
When a text delta is suppressed (buffering inside a tag), the
preceding ``event:`` header line is also removed to avoid
producing malformed SSE (event header with no data).
""" """
lines = raw_chunk.split(b"\n") lines = raw_chunk.split(b"\n")
out_lines: list[bytes] = [] out_lines: list[bytes] = []
for line in lines: for line in lines:
if not line.startswith(b"data: "): if not line.startswith(b"data: "):
# Buffer event: lines — only emit them if the next data: line
# is kept. Non-event lines (empty lines, comments) pass through.
out_lines.append(line) out_lines.append(line)
continue continue
@ -173,15 +178,18 @@ class SSECleanupFilter:
# Feed text into buffer and get cleaned output # Feed text into buffer and get cleaned output
cleaned = self._feed(text) cleaned = self._feed(text)
if cleaned is None: if cleaned is None or not cleaned:
# Entire chunk is being buffered (inside a tag) — suppress # Suppressed — also remove the preceding "event:" line
# to avoid malformed SSE (event header with no data)
if out_lines and out_lines[-1].startswith(b"event:"):
out_lines.pop()
# Also remove trailing empty line if present
if out_lines and out_lines[-1] == b"":
out_lines.pop()
continue continue
elif cleaned == text: elif cleaned == text:
# No change — pass through original bytes # No change — pass through original bytes
out_lines.append(line) out_lines.append(line)
elif not cleaned:
# Text was entirely a cleanup tag — suppress this event
continue
else: else:
# Rewrite the delta with cleaned text # Rewrite the delta with cleaned text
delta["text"] = cleaned delta["text"] = cleaned