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 worktree: None,
88 permission_profile: None,
92 };
93 let result = match self
94 .shared
95 .command::<_, SessionStartResult>("session/start", ¶ms)
96 .await
97 {
98 Ok(result) => result,
99 Err(error) => {
100 if let Some((_, id)) = &named
101 && matches!(error, FacadeError::Msp(_))
102 {
103 self.shared.forget_open(id);
104 }
105 return Err(error);
106 }
107 };
108 let session = Session::from_opening(
109 Arc::clone(&self.shared),
110 SessionOpening::Start(Box::new(result)),
111 &[],
112 None,
113 );
114 let reopened = match named {
117 Some((reopened, id)) if id == session.session_id() => reopened,
118 Some((_, id)) => {
119 self.shared.forget_open(&id);
120 self.shared.note_open(session.session_id())
121 }
122 None => self.shared.note_open(session.session_id()),
123 };
124 self.shared.register(&session, reopened);
125 Ok(session)
126 }
127
128 pub async fn resume_session(&self, options: ResumeSessionOptions) -> FacadeResult<Session> {
132 self.resume_with(options, |_| {}).await
133 }
134
135 pub async fn resume_session_with_approval_handler<Handler, HandlerFuture>(
140 &self,
141 options: ResumeSessionOptions,
142 handler: Handler,
143 ) -> FacadeResult<Session>
144 where
145 Handler: Fn(ApprovalRequestParams) -> HandlerFuture + Send + Sync + 'static,
146 HandlerFuture: Future<Output = ApprovalDecisionInput> + Send + 'static,
147 {
148 self.resume_with(options, |session| session.on_approval(handler))
149 .await
150 }
151
152 async fn resume_with(
153 &self,
154 options: ResumeSessionOptions,
155 before_handoff: impl FnOnce(&Session),
156 ) -> FacadeResult<Session> {
157 if lock(&self.shared.discarded_session_ids).contains(&options.session_id) {
158 return Err(FacadeError::SessionDiscarded(options.session_id));
159 }
160 let command_id = self.shared.mint_command_id()?;
161 let reopened = self.shared.note_open(&options.session_id);
163 let params = SessionResumeParams {
164 command_id,
165 recovery_mode: None,
167 session_id: options.session_id,
168 cursor: options.cursor,
169 exclude_items: options.exclude_items,
170 history: options.history,
171 config: options.config,
172 permission_profile: None,
176 };
177 let mut raw = match self
179 .shared
180 .command::<_, Value>("session/resume", ¶ms)
181 .await
182 {
183 Ok(raw) => raw,
184 Err(error) => {
185 if matches!(error, FacadeError::Msp(_)) {
186 self.shared.forget_open(¶ms.session_id);
187 }
188 return Err(error);
189 }
190 };
191 let dropped_snapshot = drop_unreadable_snapshot(&mut raw);
192 let result = SessionResumeResult::deserialize(&raw).map_err(invalid_frame)?;
193 let session = Session::from_opening(
194 Arc::clone(&self.shared),
195 SessionOpening::Resume(Box::new(result)),
196 resume_history_items(&raw),
197 dropped_snapshot,
198 );
199 before_handoff(&session);
200 session.fix_resume_approval_routing();
201 self.shared.register(&session, reopened);
202 Ok(session)
203 }
204}