77import pytest
88from ag_ui .core import (
99 CustomEvent ,
10+ MessagesSnapshotEvent ,
1011 ReasoningEncryptedValueEvent ,
1112 ReasoningEndEvent ,
1213 ReasoningMessageContentEvent ,
1718 TextMessageEndEvent ,
1819 TextMessageStartEvent ,
1920 ToolCallArgsEvent ,
21+ ToolCallStartEvent ,
2022)
2123from agent_framework import AgentResponseUpdate , Content , Message , ResponseStream
2224from agent_framework .exceptions import AgentInvalidResponseException
@@ -664,6 +666,24 @@ def test_snapshot_preserves_stream_order_around_tool_results():
664666 assert kinds [3 ][1 ]["id" ] != kinds [0 ][1 ]["id" ]
665667
666668
669+ def test_snapshot_reuses_streamed_tool_message_id_after_text ():
670+ """Tool-call snapshots reuse the stream ID used by the reference client merge."""
671+ flow = FlowState ()
672+ _emit_text (Content .from_text ("First, the plan." ), flow )
673+ tool_events = _emit_tool_call (Content .from_function_call (call_id = "call_1" , name = "docs_fetch" , arguments = "{}" ), flow )
674+ tool_start = next (event for event in tool_events if isinstance (event , ToolCallStartEvent ))
675+ _emit_tool_result (Content .from_function_result (call_id = "call_1" , result = "done" ), flow )
676+ _emit_text (Content .from_text ("And the summary." ), flow )
677+
678+ event = _build_messages_snapshot (flow , [])
679+
680+ kinds = _snapshot_kinds (event )
681+ assert [kind for kind , _ in kinds ] == ["text" , "tool_calls" , "result" , "text" ]
682+ assert tool_start .parent_message_id is not None
683+ assert kinds [1 ][1 ]["id" ] == tool_start .parent_message_id
684+ assert kinds [1 ][1 ]["id" ] != kinds [0 ][1 ]["id" ]
685+
686+
667687def test_snapshot_tool_only_message_reuses_stream_message_id ():
668688 """Tool-only turns keep the message id the stream opened with."""
669689 flow = FlowState ()
@@ -677,6 +697,27 @@ def test_snapshot_tool_only_message_reuses_stream_message_id():
677697 assert kinds [0 ][1 ]["id" ] == "tool-only-msg"
678698
679699
700+ def test_snapshot_tool_only_segments_get_unique_ids_across_reasoning ():
701+ """A tool-only opening ID is consumed once across separated tool segments."""
702+ flow = FlowState (message_id = "tool-only-msg" )
703+ first_events = _emit_tool_call (
704+ Content .from_function_call (call_id = "call_1" , name = "first_tool" , arguments = "{}" ), flow
705+ )
706+ _emit_text_reasoning (Content .from_text ("Thinking between calls." ), flow )
707+ second_events = _emit_tool_call (
708+ Content .from_function_call (call_id = "call_2" , name = "second_tool" , arguments = "{}" ), flow
709+ )
710+
711+ snapshot = _build_messages_snapshot (flow , [])
712+ tool_messages = [message for kind , message in _snapshot_kinds (snapshot ) if kind == "tool_calls" ]
713+ first_start = next (event for event in first_events if isinstance (event , ToolCallStartEvent ))
714+ second_start = next (event for event in second_events if isinstance (event , ToolCallStartEvent ))
715+
716+ assert [message ["id" ] for message in tool_messages ] == ["tool-only-msg" , second_start .parent_message_id ]
717+ assert first_start .parent_message_id == "tool-only-msg"
718+ assert second_start .parent_message_id != first_start .parent_message_id
719+
720+
680721def test_snapshot_keeps_reasoning_in_emission_order ():
681722 """Reasoning blocks keep their streamed position instead of always trailing."""
682723 flow = FlowState ()
@@ -706,20 +747,26 @@ def test_snapshot_without_segment_tracking_keeps_legacy_layout():
706747
707748
708749def test_snapshot_includes_text_when_message_preopened_by_tool_only_path ():
709- """Text that arrives after a tool-only preopen still lands in the snapshot."""
750+ """Text after a tool-only preopen gets a unique snapshot message ID ."""
710751 flow = FlowState ()
711752 # The tool-only detection in agent_run.py preopens message_id without
712753 # going through _emit_text, so the first text has no segment yet.
713754 flow .message_id = "preopened"
714755 _emit_tool_call (Content .from_function_call (call_id = "call_1" , name = "docs_fetch" , arguments = "{}" ), flow )
715- _emit_text (Content .from_text ("Let me check the docs." ), flow )
756+ text_events = _emit_text (Content .from_text ("Let me check the docs." ), flow )
716757
717758 event = _build_messages_snapshot (flow , [])
718759
719760 kinds = _snapshot_kinds (event )
720761 assert [kind for kind , _ in kinds ] == ["tool_calls" , "text" ]
721762 assert kinds [1 ][1 ]["content" ] == "Let me check the docs."
722- assert kinds [1 ][1 ]["id" ] == "preopened"
763+ assert kinds [0 ][1 ]["id" ] == "preopened"
764+ assert kinds [1 ][1 ]["id" ] != kinds [0 ][1 ]["id" ]
765+ assert len ({message ["id" ] for _ , message in kinds }) == len (kinds )
766+ assert isinstance (text_events [0 ], TextMessageEndEvent )
767+ assert isinstance (text_events [1 ], TextMessageStartEvent )
768+ assert text_events [0 ].message_id == "preopened"
769+ assert text_events [1 ].message_id == kinds [1 ][1 ]["id" ]
723770
724771
725772def test_snapshot_separates_calls_across_results ():
@@ -943,6 +990,26 @@ def test_emit_approval_request_populates_interrupt_metadata():
943990 }
944991
945992
993+ def test_emit_approval_request_reuses_confirmation_message_id_in_snapshot ():
994+ """Confirmation tool events and snapshots share the same message ID."""
995+ flow = FlowState ()
996+ _emit_text (Content .from_text ("Before approval." ), flow )
997+ text_message_id = flow .message_id
998+ function_call = Content .from_function_call (call_id = "call_123" , name = "write_doc" , arguments = {"content" : "x" })
999+ approval_content = Content .from_function_approval_request (id = "approval_1" , function_call = function_call )
1000+
1001+ events = _emit_approval_request (approval_content , flow )
1002+ confirm_start = next (
1003+ event for event in events if isinstance (event , ToolCallStartEvent ) and event .tool_call_name == "confirm_changes"
1004+ )
1005+ snapshot = _build_messages_snapshot (flow , [])
1006+ kinds = _snapshot_kinds (snapshot )
1007+
1008+ assert [kind for kind , _ in kinds ] == ["text" , "tool_calls" ]
1009+ assert confirm_start .parent_message_id == kinds [1 ][1 ]["id" ]
1010+ assert confirm_start .parent_message_id != text_message_id
1011+
1012+
9461013def test_emit_approval_request_keeps_protocol_fields_when_tool_arguments_use_reserved_names () -> None :
9471014 """Reserved protocol fields remain controls while editedArgs carries colliding tool arguments."""
9481015 flow = FlowState (message_id = "msg-1" )
@@ -1043,6 +1110,14 @@ async def test_predictive_confirmation_run_finished_interrupt_links_tool_call():
10431110 "arguments" : {"content" : "Draft" },
10441111 }
10451112
1113+ confirm_start = next (
1114+ event for event in events if isinstance (event , ToolCallStartEvent ) and event .tool_call_name == "confirm_changes"
1115+ )
1116+ snapshots = [event for event in events if isinstance (event , MessagesSnapshotEvent )]
1117+ assert snapshots
1118+ snapshot_tool_message = next (message for message in snapshots [- 1 ].messages if getattr (message , "tool_calls" , None ))
1119+ assert confirm_start .parent_message_id == snapshot_tool_message .id
1120+
10461121
10471122def test_resume_to_tool_messages_from_interrupts_payload ():
10481123 """Resume payload interrupt responses map to tool messages."""
@@ -1782,6 +1857,8 @@ class TestEmitMcpToolCall:
17821857 def test_produces_start_and_args_events (self ):
17831858 """MCP tool call emits ToolCallStart + ToolCallArgs events."""
17841859 flow = FlowState ()
1860+ _emit_text (Content .from_text ("Before MCP call." ), flow )
1861+ text_message_id = flow .message_id
17851862 content = Content .from_mcp_server_tool_call (
17861863 call_id = "mcp_call_1" ,
17871864 tool_name = "search" ,
@@ -1799,6 +1876,12 @@ def test_produces_start_and_args_events(self):
17991876 assert events [1 ].tool_call_id == "mcp_call_1" # type: ignore[attr-defined] # ty: ignore[unresolved-attribute]
18001877 assert "weather" in events [1 ].delta # type: ignore[attr-defined] # ty: ignore[unresolved-attribute]
18011878
1879+ snapshot = _build_messages_snapshot (flow , [])
1880+ kinds = _snapshot_kinds (snapshot )
1881+ assert [kind for kind , _ in kinds ] == ["text" , "tool_calls" ]
1882+ assert events [0 ].parent_message_id == kinds [1 ][1 ]["id" ] # type: ignore[attr-defined] # ty: ignore[unresolved-attribute]
1883+ assert events [0 ].parent_message_id != text_message_id # type: ignore[attr-defined] # ty: ignore[unresolved-attribute]
1884+
18021885 def test_tracks_in_flow_state (self ):
18031886 """MCP tool call is tracked in flow.pending_tool_calls and tool_calls_by_id."""
18041887 flow = FlowState ()
0 commit comments