@@ -240,12 +240,24 @@ void testInvokesBuiltInTools_eventOrderDuringToolExecution() throws Exception {
240240 ctx .configureForTest ("tools" , "invokes_built_in_tools" );
241241
242242 var eventTypes = new ArrayList <String >();
243+ // Use a separate completion signal so we know when THIS handler has seen
244+ // session.idle, rather than relying on sendAndWait's internal subscription.
245+ // sendAndWait also listens for session.idle internally. Because eventHandlers
246+ // is a ConcurrentHashMap Set (non-deterministic iteration order), the
247+ // sendAndWait handler can fire BEFORE this listener and unblock the test
248+ // thread before session.idle has been added to eventTypes — a race condition.
249+ var idleReceived = new java .util .concurrent .CompletableFuture <Void >();
243250
244251 try (CopilotClient client = ctx .createClient ()) {
245252 CopilotSession session = client
246253 .createSession (new SessionConfig ().setOnPermissionRequest (PermissionHandler .APPROVE_ALL )).get ();
247254
248- session .on (event -> eventTypes .add (event .getType ()));
255+ session .on (event -> {
256+ eventTypes .add (event .getType ());
257+ if (event instanceof SessionIdleEvent ) {
258+ idleReceived .complete (null );
259+ }
260+ });
249261
250262 // Create the README.md file expected by the snapshot - must have ONLY one line
251263 // to match the snapshot's expected tool response: "1. # ELIZA, the only chatbot
@@ -257,6 +269,11 @@ void testInvokesBuiltInTools_eventOrderDuringToolExecution() throws Exception {
257269 session .sendAndWait (new MessageOptions ().setPrompt ("What's the first line of README.md in this directory?" ))
258270 .get (60 , TimeUnit .SECONDS );
259271
272+ // Wait for this listener to also receive session.idle. sendAndWait can return
273+ // slightly before our listener sees the event due to concurrent dispatch
274+ // ordering.
275+ idleReceived .get (5 , TimeUnit .SECONDS );
276+
260277 // Verify expected event types are present
261278 assertTrue (eventTypes .contains ("user.message" ), "Should have user.message" );
262279 assertTrue (eventTypes .contains ("assistant.turn_start" ), "Should have assistant.turn_start" );
0 commit comments