use crate::types::{
SessionCommand, SessionResponse, SessionStateSnapshot, ThinkingState,
};
pub fn spawn_session_actor_with_state(
mut rx: tokio::sync::mpsc::Receiver<SessionCommand>,
initial_state: ThinkingState,
) {
tokio::spawn(async move {
let mut state = initial_state;
while let Some(cmd) = rx.recv().await {
match cmd {
SessionCommand::AddThought {
thought,
respond_to,
} => {
state.thought_history.push(thought.clone());
if let (Some(_), Some(branch_id)) =
(thought.branch_from_thought, &thought.branch_id)
{
state
.branches
.entry(branch_id.clone())
.or_default()
.push(thought.clone());
}
let response = SessionResponse {
thought_number: thought.thought_number,
total_thoughts: thought.total_thoughts,
next_thought_needed: thought.next_thought_needed,
branches: state.branches.keys().cloned().collect(),
thought_history_length: state.thought_history.len(),
};
let _ = respond_to.send(response);
if !thought.next_thought_needed {
log::debug!(
"Session completed (final thought {}), terminating actor",
thought.thought_number
);
break;
}
}
SessionCommand::GetState { respond_to } => {
let snapshot = SessionStateSnapshot {
thought_history: state.thought_history.clone(),
branches: state.branches.clone(),
};
let _ = respond_to.send(snapshot);
}
SessionCommand::Clear { respond_to } => {
state.thought_history.clear();
state.branches.clear();
let _ = respond_to.send(());
log::debug!("Session cleared, terminating actor");
break;
}
}
}
log::debug!("Session actor task terminated, state cleaned up");
});
}
pub fn spawn_session_actor(
rx: tokio::sync::mpsc::Receiver<SessionCommand>,
) {
spawn_session_actor_with_state(rx, ThinkingState::default());
}