Skip to content
Open
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
17 changes: 9 additions & 8 deletions src/a2a/client/transports/http_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,12 +84,15 @@ async def _aiter_sse_lines(
chunks costs linear rather than quadratic time.
"""
pieces: list[str] = []
held_cr = False
skip_lf = False
async for chunk in response.aiter_text():
text = '\r' + chunk if held_cr else chunk
# Hold a trailing CR back: the next chunk may start with its LF.
held_cr = text.endswith('\r')
*lines, rest = _SSE_LINE_END.split(text[:-1] if held_cr else text)
if not chunk:
continue
# CR already ends the line. Only swallow its optional following LF,
# so a complete event can be delivered without waiting for more data.
text = chunk.removeprefix('\n') if skip_lf else chunk
skip_lf = text.endswith('\r')
*lines, rest = _SSE_LINE_END.split(text)
if lines:
lines[0] = ''.join(pieces) + lines[0]
pieces = []
Expand All @@ -98,9 +101,7 @@ async def _aiter_sse_lines(
if rest:
pieces.append(rest)
tail = ''.join(pieces)
# A held CR at end of stream still ends a line, even an empty one. That
# blank line is what dispatches the last event, so yield it too.
if held_cr or tail:
if tail:
yield tail


Expand Down
10 changes: 10 additions & 0 deletions tests/client/transports/test_http_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,16 @@ async def _byte_chunks(chunks: list[bytes]) -> AsyncIterator[bytes]:
[('message', 'a
b\nc')],
id='crlf-and-character-split-across-chunks',
),
pytest.param(
[b'data: a\r', b'\n', b'data: b\r', b'\n\r', b'\n'],
[('message', 'a\nb')],
id='split-crlf-is-one-line-ending',
),
pytest.param(
[b'data: a\r', b'data: b\r', b'\r'],
[('message', 'a\nb')],
id='cr-separated-data-lines',
),
pytest.param(
[b'data: a\r'],
[],
Expand Down
46 changes: 46 additions & 0 deletions tests/client/transports/test_jsonrpc_client.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
"""Tests for the JSON-RPC client transport."""

import asyncio
import json

from collections.abc import AsyncGenerator
Expand Down Expand Up @@ -978,3 +979,48 @@ async def test_streaming_malformed_event_raises_a2a_error(
create_send_message_request()
):
pass


@pytest.mark.asyncio
@pytest.mark.parametrize('ending', [b'\n', b'\r\n', b'\r'])
async def test_streaming_message_delivered_before_next_chunk(
ending: bytes,
) -> None:
"""A complete SSE event must not wait for another event or EOF."""
payload = {
'jsonrpc': '2.0',
'id': '1',
'result': {
'message': {
'messageId': 'r1',
'role': 'ROLE_AGENT',
'parts': [{'text': 'hello'}],
},
},
}

class LiveBody(httpx_lib.AsyncByteStream):
async def __aiter__(self) -> AsyncGenerator[bytes, None]:
yield b'data: ' + json.dumps(payload).encode() + ending * 2
# The remote agent leaves its stream open until more work arrives.
await asyncio.Event().wait()

def respond(request: httpx_lib.Request) -> httpx_lib.Response:
assert json.loads(request.content)['method'] == 'SendStreamingMessage'
return httpx_lib.Response(
200,
headers={'Content-Type': 'text/event-stream'},
stream=LiveBody(),
)

async with httpx_lib.AsyncClient(
transport=httpx_lib.MockTransport(respond)
) as client:
transport = JsonRpcTransport(client, AgentCard(), 'http://agent')
stream = transport.send_message_streaming(create_send_message_request())
try:
event = await asyncio.wait_for(anext(stream), timeout=1)
assert event.message.message_id == 'r1'
assert event.message.parts[0].text == 'hello'
finally:
await stream.aclose()
Loading