@@ -194,6 +194,60 @@ impl ConversationState {
194194 debug ! ( ?msg, "last message in history is from the user, dropping" ) ;
195195 self . history . pop_back ( ) ;
196196 }
197+
198+ // If the last message from the assistant contains tool uses, we need to ensure that the
199+ // next user message contains tool results.
200+ match ( self . history . iter ( ) . last ( ) , & mut self . next_message ) {
201+ (
202+ Some ( ChatMessage :: AssistantResponseMessage ( AssistantResponseMessage {
203+ tool_uses : Some ( tool_uses) ,
204+ ..
205+ } ) ) ,
206+ Some ( msg) ,
207+ ) if !tool_uses. is_empty ( ) => match msg. user_input_message_context . as_mut ( ) {
208+ Some ( ctx) => {
209+ if ctx. tool_results . as_ref ( ) . is_none_or ( |r| r. is_empty ( ) ) {
210+ ctx. tool_results = Some (
211+ tool_uses
212+ . iter ( )
213+ . map ( |tool_use| ToolResult {
214+ tool_use_id : tool_use. tool_use_id . clone ( ) ,
215+ content : vec ! [ ToolResultContentBlock :: Text (
216+ "Tool use was cancelled by the user" . to_string( ) ,
217+ ) ] ,
218+ status : fig_api_client:: model:: ToolResultStatus :: Error ,
219+ } )
220+ . collect :: < Vec < _ > > ( ) ,
221+ ) ;
222+ }
223+ } ,
224+ None => {
225+ let tool_results = tool_uses
226+ . iter ( )
227+ . map ( |tool_use| ToolResult {
228+ tool_use_id : tool_use. tool_use_id . clone ( ) ,
229+ content : vec ! [ ToolResultContentBlock :: Text (
230+ "Tool use was cancelled by the user" . to_string( ) ,
231+ ) ] ,
232+ status : fig_api_client:: model:: ToolResultStatus :: Error ,
233+ } )
234+ . collect :: < Vec < _ > > ( ) ;
235+ let user_input_message_context = UserInputMessageContext {
236+ shell_state : None ,
237+ env_state : Some ( build_env_state ( ) ) ,
238+ tool_results : Some ( tool_results) ,
239+ tools : if self . tools . is_empty ( ) {
240+ None
241+ } else {
242+ Some ( self . tools . clone ( ) )
243+ } ,
244+ ..Default :: default ( )
245+ } ;
246+ msg. user_input_message_context = Some ( user_input_message_context) ;
247+ } ,
248+ } ,
249+ _ => { } ,
250+ }
197251 }
198252
199253 pub fn add_tool_results ( & mut self , tool_results : Vec < ToolResult > ) {
0 commit comments