use std::future::Future;
use std::sync::Arc;
use serde::Deserialize;
use serde_json::Value;
use crate::approval::ApprovalDecisionInput;
use crate::msp::{
ApprovalMode, ApprovalRequestParams, HistoryPreference, SessionConfig, SessionResumeParams,
SessionResumeResult, SessionStartParams, SessionStartResult,
};
use crate::session::{Session, SessionOpening, drop_unreadable_snapshot, resume_history_items};
use super::{FacadeError, FacadeResult, MuseClient, invalid_frame, lock};
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct StartSessionOptions {
pub session_id: Option<String>,
pub workspace_root: Option<String>,
pub workspace_roots: Option<Vec<String>>,
pub model_id: Option<String>,
pub provider_id: Option<String>,
pub approval_mode: Option<ApprovalMode>,
pub config: Option<SessionConfig>,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct ResumeSessionOptions {
pub session_id: String,
pub cursor: Option<String>,
pub exclude_items: Option<bool>,
pub history: Option<HistoryPreference>,
pub config: Option<SessionConfig>,
}
impl MuseClient {
pub async fn start_session(&self, options: StartSessionOptions) -> FacadeResult<Session> {
let command_id = self.shared.mint_command_id()?;
let named = options
.session_id
.clone()
.map(|id| (self.shared.note_open(&id), id));
let params = SessionStartParams {
command_id,
recovery_mode: None,
session_id: options.session_id,
workspace_root: options.workspace_root,
workspace_roots: options.workspace_roots,
model_id: options.model_id,
provider_id: options.provider_id,
approval_mode: options.approval_mode,
config: options.config,
worktree: None,
permission_profile: None,
limits: None,
};
let result = match self
.shared
.command::<_, SessionStartResult>("session/start", ¶ms)
.await
{
Ok(result) => result,
Err(error) => {
if let Some((_, id)) = &named
&& matches!(error, FacadeError::Msp(_))
{
self.shared.forget_open(id);
}
return Err(error);
}
};
let session = Session::from_opening(
Arc::clone(&self.shared),
SessionOpening::Start(Box::new(result)),
&[],
None,
);
let reopened = match named {
Some((reopened, id)) if id == session.session_id() => reopened,
Some((_, id)) => {
self.shared.forget_open(&id);
self.shared.note_open(session.session_id())
}
None => self.shared.note_open(session.session_id()),
};
self.shared.register(&session, reopened);
Ok(session)
}
pub async fn resume_session(&self, options: ResumeSessionOptions) -> FacadeResult<Session> {
self.resume_with(options, |_| {}).await
}
pub async fn resume_session_with_approval_handler<Handler, HandlerFuture>(
&self,
options: ResumeSessionOptions,
handler: Handler,
) -> FacadeResult<Session>
where
Handler: Fn(ApprovalRequestParams) -> HandlerFuture + Send + Sync + 'static,
HandlerFuture: Future<Output = ApprovalDecisionInput> + Send + 'static,
{
self.resume_with(options, |session| session.on_approval(handler))
.await
}
async fn resume_with(
&self,
options: ResumeSessionOptions,
before_handoff: impl FnOnce(&Session),
) -> FacadeResult<Session> {
if lock(&self.shared.discarded_session_ids).contains(&options.session_id) {
return Err(FacadeError::SessionDiscarded(options.session_id));
}
let command_id = self.shared.mint_command_id()?;
let reopened = self.shared.note_open(&options.session_id);
let params = SessionResumeParams {
command_id,
recovery_mode: None,
session_id: options.session_id,
cursor: options.cursor,
exclude_items: options.exclude_items,
history: options.history,
config: options.config,
permission_profile: None,
};
let mut raw = match self
.shared
.command::<_, Value>("session/resume", ¶ms)
.await
{
Ok(raw) => raw,
Err(error) => {
if matches!(error, FacadeError::Msp(_)) {
self.shared.forget_open(¶ms.session_id);
}
return Err(error);
}
};
let dropped_snapshot = drop_unreadable_snapshot(&mut raw);
let result = SessionResumeResult::deserialize(&raw).map_err(invalid_frame)?;
let history = resume_history_items(&raw, &result.history.mode);
let session = Session::from_opening(
Arc::clone(&self.shared),
SessionOpening::Resume(Box::new(result)),
history,
dropped_snapshot,
);
before_handoff(&session);
session.fix_resume_approval_routing();
self.shared.register(&session, reopened);
Ok(session)
}
}