1use std::future::Future;
5use std::sync::Arc;
6
7use serde::Deserialize;
8use serde_json::Value;
9
10use crate::approval::ApprovalDecisionInput;
11use crate::msp::{
12 ApprovalMode, ApprovalRequestParams, HistoryPreference, SessionConfig, SessionResumeParams,
13 SessionResumeResult, SessionStartParams, SessionStartResult,
14};
15use crate::session::{Session, SessionOpening, drop_unreadable_snapshot, resume_history_items};
16
17use super::{FacadeError, FacadeResult, MuseClient, invalid_frame, lock};
18
19#[derive(Clone, Debug, Default, PartialEq, Eq)]
23pub struct StartSessionOptions {
24 pub session_id: Option<String>,
28 pub workspace_root: Option<String>,
30 pub workspace_roots: Option<Vec<String>>,
34 pub model_id: Option<String>,
36 pub provider_id: Option<String>,
38 pub approval_mode: Option<ApprovalMode>,
40 pub config: Option<SessionConfig>,
42}
43
44#[derive(Clone, Debug, Default, PartialEq, Eq)]
46pub struct ResumeSessionOptions {
47 pub session_id: String,
49 pub cursor: Option<String>,
52 pub exclude_items: Option<bool>,
55 pub history: Option<HistoryPreference>,
60 pub config: Option<SessionConfig>,
62}
63
64impl MuseClient {
65 pub async fn start_session(&self, options: StartSessionOptions) -> FacadeResult<Session> {
67 let command_id = self.shared.mint_command_id()?;
68 let named = options
71 .session_id
72 .clone()
73 .map(|id| (self.shared.note_open(&id), id));
74 let params = SessionStartParams {
75 command_id,
76 recovery_mode: None,
78 session_id: options.session_id,
79 workspace_root: options.workspace_root,
80 workspace_roots: options.workspace_roots,
81 model_id: options.model_id,
82 provider_id: options.provider_id,
83 approval_mode: options.approval_mode,
84 config: options.config,
85 spawned_by: None,
87 worktree: None,
90 permission_profile: None,
94 limits: None,
96 previous_session_id: None,
98 };
99 let result = match self
100 .shared
101 .command::<_, SessionStartResult>("session/start", ¶ms)
102 .await
103 {
104 Ok(result) => result,
105 Err(error) => {
106 if let Some((_, id)) = &named
107 && matches!(error, FacadeError::Msp(_))
108 {
109 self.shared.forget_open(id);
110 }
111 return Err(error);
112 }
113 };
114 let session = Session::from_opening(
115 Arc::clone(&self.shared),
116 SessionOpening::Start(Box::new(result)),
117 &[],
118 None,
119 );
120 let reopened = match named {
123 Some((reopened, id)) if id == session.session_id() => reopened,
124 Some((_, id)) => {
125 self.shared.forget_open(&id);
126 self.shared.note_open(session.session_id())
127 }
128 None => self.shared.note_open(session.session_id()),
129 };
130 self.shared.register(&session, reopened);
131 Ok(session)
132 }
133
134 pub async fn resume_session(&self, options: ResumeSessionOptions) -> FacadeResult<Session> {
138 self.resume_with(options, |_| {}).await
139 }
140
141 pub async fn resume_session_with_approval_handler<Handler, HandlerFuture>(
146 &self,
147 options: ResumeSessionOptions,
148 handler: Handler,
149 ) -> FacadeResult<Session>
150 where
151 Handler: Fn(ApprovalRequestParams) -> HandlerFuture + Send + Sync + 'static,
152 HandlerFuture: Future<Output = ApprovalDecisionInput> + Send + 'static,
153 {
154 self.resume_with(options, |session| session.on_approval(handler))
155 .await
156 }
157
158 async fn resume_with(
159 &self,
160 options: ResumeSessionOptions,
161 before_handoff: impl FnOnce(&Session),
162 ) -> FacadeResult<Session> {
163 if lock(&self.shared.discarded_session_ids).contains(&options.session_id) {
164 return Err(FacadeError::SessionDiscarded(options.session_id));
165 }
166 let command_id = self.shared.mint_command_id()?;
167 let reopened = self.shared.note_open(&options.session_id);
169 let params = SessionResumeParams {
170 command_id,
171 recovery_mode: None,
173 session_id: options.session_id,
174 cursor: options.cursor,
175 exclude_items: options.exclude_items,
176 history: options.history,
177 config: options.config,
178 permission_profile: None,
182 model_id: None,
185 };
186 let mut raw = match self
188 .shared
189 .command::<_, Value>("session/resume", ¶ms)
190 .await
191 {
192 Ok(raw) => raw,
193 Err(error) => {
194 if matches!(error, FacadeError::Msp(_)) {
195 self.shared.forget_open(¶ms.session_id);
196 }
197 return Err(error);
198 }
199 };
200 let dropped_snapshot = drop_unreadable_snapshot(&mut raw);
201 let result = SessionResumeResult::deserialize(&raw).map_err(invalid_frame)?;
202 let history = resume_history_items(&raw, &result.history.mode);
203 let session = Session::from_opening(
204 Arc::clone(&self.shared),
205 SessionOpening::Resume(Box::new(result)),
206 history,
207 dropped_snapshot,
208 );
209 before_handoff(&session);
210 session.fix_resume_approval_routing();
211 self.shared.register(&session, reopened);
212 Ok(session)
213 }
214}