@@ -290,22 +290,45 @@ async def handle_msg_wait(db, arguments: dict[str, Any]) -> list[types.Content]:
290290
291291 logger .info (f"[msg_wait] explicit: agent_id={ explicit_agent_id } , connection: agent_id={ connection_agent_id } , final_agent_id={ agent_id } " )
292292
293- if agent_id and token :
294- try :
295- result = await crud .agent_msg_wait (db , agent_id , token )
296- logger .info (f"[msg_wait] activity recorded: agent_id={ agent_id } , result={ result } " )
297- except Exception as e :
298- logger .warning (f"[msg_wait] Failed to record activity for { agent_id } : { e } " )
299- else :
300- logger .warning (f"[msg_wait] No credentials available: agent_id={ agent_id } , token={ '***' if token else None } " )
293+ # Heartbeat interval: refresh every 20 seconds to stay online (AGENT_HEARTBEAT_TIMEOUT is 30s)
294+ HEARTBEAT_INTERVAL = 20.0
295+
296+ async def _refresh_heartbeat ():
297+ """Refresh heartbeat to keep agent online during long wait."""
298+ if agent_id and token :
299+ try :
300+ await crud .agent_msg_wait (db , agent_id , token )
301+ logger .debug (f"[msg_wait] heartbeat refreshed for agent_id={ agent_id } " )
302+ except Exception as e :
303+ logger .warning (f"[msg_wait] Failed to refresh heartbeat for { agent_id } : { e } " )
301304
302305 async def _poll ():
306+ """Poll for new messages, refreshing heartbeat periodically."""
307+ last_heartbeat = asyncio .get_event_loop ().time ()
303308 while True :
309+ # Check for new messages
304310 msgs = await crud .msg_list (db , thread_id , after_seq = after_seq , include_system_prompt = False )
305311 if msgs :
306312 return msgs
313+
314+ # Refresh heartbeat if interval elapsed
315+ now = asyncio .get_event_loop ().time ()
316+ if now - last_heartbeat >= HEARTBEAT_INTERVAL :
317+ await _refresh_heartbeat ()
318+ last_heartbeat = now
319+
307320 await asyncio .sleep (0.5 )
308321
322+ # Record initial activity
323+ if agent_id and token :
324+ try :
325+ result = await crud .agent_msg_wait (db , agent_id , token )
326+ logger .info (f"[msg_wait] initial activity recorded: agent_id={ agent_id } , result={ result } " )
327+ except Exception as e :
328+ logger .warning (f"[msg_wait] Failed to record activity for { agent_id } : { e } " )
329+ else :
330+ logger .warning (f"[msg_wait] No credentials available: agent_id={ agent_id } , token={ '***' if token else None } " )
331+
309332 try :
310333 msgs = await asyncio .wait_for (_poll (), timeout = timeout_s )
311334 except asyncio .TimeoutError :
0 commit comments