File tree Expand file tree Collapse file tree 1 file changed +11
-3
lines changed
src/main/java/com/github/copilot/sdk Expand file tree Collapse file tree 1 file changed +11
-3
lines changed Original file line number Diff line number Diff line change @@ -542,9 +542,17 @@ public CompletableFuture<AssistantMessageEvent> sendAndWait(MessageOptions optio
542542 }
543543 }
544544
545- // When inner future completes, run cleanup and propagate to result
545+ // When inner future completes, run cleanup and propagate to result.
546+ // Use whenCompleteAsync so that result.complete(r) is not called
547+ // synchronously on the event-dispatch thread while dispatchEvent() is
548+ // still iterating over handlers. Without async dispatch, a caller that
549+ // registered its own session.on() listener before calling sendAndWait()
550+ // could see its listener invoked *after* result.get() returned, because
551+ // sendAndWait's internal handler would complete the future mid-loop. By
552+ // submitting the completion to timeoutScheduler we allow the current
553+ // dispatch loop to finish calling all other handlers first.
546554 final ScheduledFuture <?> taskToCancel = timeoutTask ;
547- future .whenComplete ((r , ex ) -> {
555+ future .whenCompleteAsync ((r , ex ) -> {
548556 try {
549557 subscription .close ();
550558 } catch (IOException e ) {
@@ -560,7 +568,7 @@ public CompletableFuture<AssistantMessageEvent> sendAndWait(MessageOptions optio
560568 result .complete (r );
561569 }
562570 }
563- });
571+ }, timeoutScheduler );
564572
565573 // When result is cancelled externally, cancel inner future to trigger cleanup
566574 result .whenComplete ((v , ex ) -> {
You can’t perform that action at this time.
0 commit comments