@@ -760,12 +760,23 @@ void testShouldGetLastSessionId() throws Exception {
760760 .createSession (new SessionConfig ().setOnPermissionRequest (PermissionHandler .APPROVE_ALL )).get ();
761761
762762 session .sendAndWait (new MessageOptions ().setPrompt ("Say hello" )).get (60 , TimeUnit .SECONDS );
763+ String sessionId = session .getSessionId ();
764+ session .close ();
763765
764- String lastId = client .getLastSessionId ().get (30 , TimeUnit .SECONDS );
766+ // Poll until getLastSessionId returns the expected value.
767+ // Session state is persisted asynchronously; polling keeps fast
768+ // machines fast and slow CI safe (mirrors Node.js/.NET patterns).
769+ String lastId = null ;
770+ long deadline = System .currentTimeMillis () + 10_000 ;
771+ while (System .currentTimeMillis () < deadline ) {
772+ lastId = client .getLastSessionId ().get (30 , TimeUnit .SECONDS );
773+ if (sessionId .equals (lastId )) {
774+ break ;
775+ }
776+ Thread .sleep (50 );
777+ }
765778 assertNotNull (lastId , "Last session ID should not be null" );
766- assertEquals (session .getSessionId (), lastId , "Last session ID should match the current session ID" );
767-
768- session .close ();
779+ assertEquals (sessionId , lastId , "Last session ID should match the current session ID" );
769780 }
770781 }
771782
@@ -840,11 +851,24 @@ void testShouldGetSessionMetadataById() throws Exception {
840851 var session = client
841852 .createSession (new SessionConfig ().setOnPermissionRequest (PermissionHandler .APPROVE_ALL )).get ();
842853
854+ // Send a message to persist the session to disk
843855 session .sendAndWait (new MessageOptions ().setPrompt ("Say hello" )).get (60 , TimeUnit .SECONDS );
844856
845- var metadata = client .getSessionMetadata (session .getSessionId ()).get (30 , TimeUnit .SECONDS );
846- assertNotNull (metadata , "Metadata should not be null for known session" );
847- assertEquals (session .getSessionId (), metadata .getSessionId (), "Metadata session ID should match" );
857+ // Poll until metadata becomes available; the CLI persists session
858+ // state asynchronously so it may not be queryable immediately
859+ // (mirrors .NET WaitForConditionAsync pattern).
860+ var sessionId = session .getSessionId ();
861+ com .github .copilot .sdk .json .SessionMetadata metadata = null ;
862+ long deadline = System .currentTimeMillis () + 10_000 ;
863+ while (System .currentTimeMillis () < deadline ) {
864+ metadata = client .getSessionMetadata (sessionId ).get (30 , TimeUnit .SECONDS );
865+ if (metadata != null ) {
866+ break ;
867+ }
868+ Thread .sleep (50 );
869+ }
870+ assertNotNull (metadata , "Timed out waiting for getSessionMetadata() to return the persisted session" );
871+ assertEquals (sessionId , metadata .getSessionId (), "Metadata session ID should match" );
848872
849873 // A non-existent session should return null
850874 var notFound = client .getSessionMetadata ("non-existent-session-id" ).get (30 , TimeUnit .SECONDS );
0 commit comments