use std::{
collections::HashSet,
sync::{Mutex, MutexGuard, PoisonError},
};
use rho_protocol::SessionSetup;
use rho_sdk::{SessionId, UserInput};
use super::{
start::{Entered, StartedTurn},
DaemonTurn, LoadedSession, OpenWith, Sessions, TurnSlot,
};
use crate::app::session_runtime::{Turn, TurnStart};
const RESUME_NOTE: &str = "The rho daemon restarted and interrupted your previous turn. \
Continue where you left off. A tool call the restart interrupted \
may have partly run; check its effects before repeating it.";
const RESUME_NOTICE: &str = "rho daemon restarted mid-turn; continuing the interrupted turn";
#[derive(Default)]
pub(super) struct RestartResumes(Mutex<HashSet<SessionId>>);
impl RestartResumes {
pub(super) fn take(&self, session: &SessionId) -> bool {
self.lock().remove(session)
}
fn lock(&self) -> MutexGuard<'_, HashSet<SessionId>> {
self.0.lock().unwrap_or_else(PoisonError::into_inner)
}
}
impl Sessions {
pub(in crate::app::daemon_host) fn resume_after_restart(&self, sessions: Vec<SessionId>) {
if sessions.is_empty() {
return;
}
tracing::info!(
sessions = sessions.len(),
"the restart interrupted turns; each continues once a client attaches to its session"
);
self.restart_resumes.lock().extend(sessions);
}
pub(super) fn resume_interrupted(
&self,
session: &LoadedSession,
turn: &mut TurnSlot,
) -> Option<StartedTurn> {
if !self.restart_resumes.take(&session.id) {
return None;
}
let skipped = |reason: &str| {
tracing::info!(
session = %session.id,
job = %session.job,
reason,
"not continuing the turn the restart interrupted"
);
};
if session.idle_wake.is_none() {
skipped("the client that reopened the session takes no turns the daemon starts");
return None;
}
let Some(grant) = self.jobs.grant_of(&session.job) else {
skipped("the session's job is not recorded");
return None;
};
let with = OpenWith {
environment: session.environment.current(),
setup: SessionSetup::default(),
grant,
};
match self.start_turn(session, turn, &with, None, None) {
Ok(Entered::Started(started)) => {
tracing::info!(
session = %session.id,
job = %session.job,
turn = %started.id,
"continuing the turn the restart interrupted"
);
Some(started)
}
Ok(Entered::SentAgain { .. } | Entered::BehindWakeWait) => None,
Err(error) => {
tracing::warn!(
session = %session.id,
job = %session.job,
%error,
"could not continue the turn the restart interrupted"
);
None
}
}
}
}
pub(super) fn resume_turn() -> DaemonTurn {
let note = UserInput::text(RESUME_NOTE);
DaemonTurn {
start: TurnStart::Prompt(Turn {
display: note.clone(),
model: note,
calls: Vec::new(),
}),
notice: Some(RESUME_NOTICE.to_owned()),
}
}