From 9c7fed093a52adb104aa9a4efa05e59b4594f371 Mon Sep 17 00:00:00 2001 From: Elon-Jiang <191222665+Elon-Jiang@users.noreply.github.com> Date: Wed, 18 Nov 2026 18:18:44 +0800 Subject: [PATCH] fix(client): dispatch CR-terminated SSE events immediately --- src/a2a/client/transports/http_helpers.py | 17 +++---- tests/client/transports/test_http_helpers.py | 10 ++++ .../client/transports/test_jsonrpc_client.py | 46 +++++++++++++++++++ 3 files changed, 65 insertions(+), 8 deletions(-) diff --git a/src/a2a/client/transports/http_helpers.py b/src/a2a/client/transports/http_helpers.py index 17e882b24..6ca034666 100644 --- a/src/a2a/client/transports/http_helpers.py +++ b/src/a2a/client/transports/http_helpers.py @@ -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 = [] @@ -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 diff --git a/tests/client/transports/test_http_helpers.py b/tests/client/transports/test_http_helpers.py index 84a0ed2e2..90feb8fff 100644 --- a/tests/client/transports/test_http_helpers.py +++ b/tests/client/transports/test_http_helpers.py @@ -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'], [], diff --git a/tests/client/transports/test_jsonrpc_client.py b/tests/client/transports/test_jsonrpc_client.py index 3ae287d23..905ad4ea6 100644 --- a/tests/client/transports/test_jsonrpc_client.py +++ b/tests/client/transports/test_jsonrpc_client.py @@ -1,5 +1,6 @@ """Tests for the JSON-RPC client transport.""" +import asyncio import json from collections.abc import AsyncGenerator @@ -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()