Fix duplicate state initialization (#6089)

This commit is contained in:
Engel Nyst
2025-01-07 23:22:43 +01:00
committed by GitHub
parent 9747c9e9f8
commit aabbbb6c6a
3 changed files with 204 additions and 18 deletions

View File

@@ -274,27 +274,25 @@ class AgentSession:
confirmation_mode=confirmation_mode,
headless_mode=False,
status_callback=self._status_callback,
initial_state=self._maybe_restore_state(),
)
# Note: We now attempt to restore the state from session here,
# but if it fails, we fall back to None and still initialize the controller
# with a fresh state. That way, the controller will always load events from the event stream
# even if the state file was corrupt.
return controller
def _maybe_restore_state(self) -> State | None:
"""Helper method to handle state restore logic."""
restored_state = None
# Attempt to restore the state from session.
# Use a heuristic to figure out if we should have a state:
# if we have events in the stream.
try:
restored_state = State.restore_from_session(self.sid, self.file_store)
logger.debug(f'Restored state from session, sid: {self.sid}')
except Exception as e:
if self.event_stream.get_latest_event_id() > 0:
# if we have events, we should have a state
logger.warning(f'State could not be restored: {e}')
# Set the initial state through the controller.
controller.set_initial_state(restored_state, max_iterations, confirmation_mode)
if restored_state:
logger.debug(f'Restored agent state from session, sid: {self.sid}')
else:
logger.debug('New session state created.')
logger.debug('Agent controller initialized.')
return controller
else:
logger.debug('No events found, no state to restore')
return restored_state