@@ -384,6 +384,8 @@ async def _run_consumer(self) -> None: # noqa: PLR0915, PLR0912
384384 event ,
385385 )
386386 else :
387+ replace_event_with_task = False
388+
387389 if task_mode is False :
388390 logger .error (
389391 'Received %s in message mode.' ,
@@ -408,6 +410,17 @@ async def _run_consumer(self) -> None: # noqa: PLR0915, PLR0912
408410 # Initial task should already contain the message.
409411 message_to_save = None
410412 else :
413+ if (
414+ isinstance (event , TaskStatusUpdateEvent )
415+ and not self ._task_created .is_set ()
416+ ):
417+ task = (
418+ await self ._task_manager .get_task ()
419+ )
420+ if task is None :
421+ # Backward compat: Agent sent TaskStatusUpdateEvent before the Task.
422+ replace_event_with_task = True
423+
411424 new_task = (
412425 await self ._task_manager .ensure_task_id (
413426 self ._task_id ,
@@ -434,8 +447,6 @@ async def _run_consumer(self) -> None: # noqa: PLR0915, PLR0912
434447 if not isinstance (event , Task ):
435448 await self ._task_manager .process (event )
436449
437- self ._task_created .set ()
438-
439450 # Check for AUTH_REQUIRED or INPUT_REQUIRED or TERMINAL states
440451 new_task = await self ._task_manager .get_task ()
441452 if new_task is None :
@@ -484,6 +495,14 @@ async def _run_consumer(self) -> None: # noqa: PLR0915, PLR0912
484495 new_task .status .state ,
485496 )
486497
498+ if replace_event_with_task :
499+ logger .debug (
500+ 'Replacing TaskStatusUpdateEvent %s with Task %s in consumer loop.' ,
501+ event ,
502+ new_task ,
503+ )
504+ event = new_task
505+
487506 if (
488507 self ._push_sender
489508 and self ._task_id
@@ -496,6 +515,9 @@ async def _run_consumer(self) -> None: # noqa: PLR0915, PLR0912
496515 await self ._push_sender .send_notification (
497516 self ._task_id , event
498517 )
518+
519+ self ._task_created .set ()
520+
499521 finally :
500522 if new_task is not None :
501523 new_task_copy = Task ()
0 commit comments