1use std::borrow::Borrow;
4use std::fmt;
5use std::ops::Deref;
6use std::path::Path;
7use std::str::FromStr;
8use std::sync::Arc;
9
10pub use ag_contracts::{PermissionMode, ResponseStyle, SpeedMode};
11pub use ag_forge::{ForgeKind, ReviewRequestState, ReviewRequestSummary};
12use ag_protocol::QuestionItem;
13use serde::de::{self, Deserializer};
14use serde::ser::Serializer;
15use serde::{Deserialize, Serialize};
16
17use crate::message::SessionMessage;
18use crate::{AgentSelection, EnvId, ReasoningLevel};
19
20pub fn session_branch(session_id: &str) -> String {
22 let prefix_length = session_id.len().min(8);
23
24 format!("{SESSION_BRANCH_PREFIX}{}", &session_id[..prefix_length])
25}
26
27#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
33pub struct SessionId(Arc<str>);
34
35impl SessionId {
36 pub fn as_str(&self) -> &str {
38 self.0.as_ref()
39 }
40}
41
42impl AsRef<str> for SessionId {
43 fn as_ref(&self) -> &str {
44 self.as_str()
45 }
46}
47
48impl AsRef<Path> for SessionId {
49 fn as_ref(&self) -> &Path {
50 Path::new(self.as_str())
51 }
52}
53
54impl Borrow<str> for SessionId {
55 fn borrow(&self) -> &str {
56 self.as_str()
57 }
58}
59
60impl Deref for SessionId {
61 type Target = str;
62
63 fn deref(&self) -> &Self::Target {
64 self.as_str()
65 }
66}
67
68impl fmt::Display for SessionId {
69 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
70 formatter.write_str(self.as_str())
71 }
72}
73
74impl From<&str> for SessionId {
75 fn from(value: &str) -> Self {
76 Self(Arc::<str>::from(value))
77 }
78}
79
80impl From<String> for SessionId {
81 fn from(value: String) -> Self {
82 Self(Arc::<str>::from(value))
83 }
84}
85
86impl From<Arc<str>> for SessionId {
87 fn from(value: Arc<str>) -> Self {
88 Self(value)
89 }
90}
91
92impl From<SessionId> for String {
93 fn from(value: SessionId) -> Self {
94 value.as_str().to_string()
95 }
96}
97
98impl PartialEq<str> for SessionId {
99 fn eq(&self, other: &str) -> bool {
100 self.as_str() == other
101 }
102}
103
104impl PartialEq<&str> for SessionId {
105 fn eq(&self, other: &&str) -> bool {
106 self.as_str() == *other
107 }
108}
109
110impl PartialEq<String> for SessionId {
111 fn eq(&self, other: &String) -> bool {
112 self.as_str() == other
113 }
114}
115
116impl PartialEq<&String> for SessionId {
117 fn eq(&self, other: &&String) -> bool {
118 self.as_str() == other.as_str()
119 }
120}
121
122impl Serialize for SessionId {
123 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
124 where
125 S: Serializer,
126 {
127 serializer.serialize_str(self.as_str())
128 }
129}
130
131impl<'de> Deserialize<'de> for SessionId {
132 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
133 where
134 D: Deserializer<'de>,
135 {
136 String::deserialize(deserializer)
137 .map(Self::from)
138 .map_err(de::Error::custom)
139 }
140}
141
142#[derive(Clone, Copy, Debug, Eq, PartialEq)]
144pub enum SessionStatus {
145 Draft,
147 InProgress,
149 Review,
151 AgentReview,
153 Question,
155 Queued,
157 Rebasing,
159 Merging,
161 Merged,
163 Done,
165 Canceled,
167}
168
169impl SessionStatus {
170 pub const ALL: [SessionStatus; 11] = [
172 SessionStatus::Draft,
173 SessionStatus::InProgress,
174 SessionStatus::Review,
175 SessionStatus::AgentReview,
176 SessionStatus::Question,
177 SessionStatus::Queued,
178 SessionStatus::Rebasing,
179 SessionStatus::Merging,
180 SessionStatus::Merged,
181 SessionStatus::Done,
182 SessionStatus::Canceled,
183 ];
184
185 pub fn allows_chat_composer(self) -> bool {
187 self.allows_session_actions()
188 || matches!(self, SessionStatus::InProgress | SessionStatus::Rebasing)
189 }
190
191 pub fn allows_session_actions(self) -> bool {
193 self.allows_review_actions()
194 || matches!(self, SessionStatus::Draft | SessionStatus::Question)
195 }
196
197 pub fn allows_diff_view(self) -> bool {
199 self.allows_review_actions() || self.is_read_only() || self.allows_terminal_continuation()
200 }
201
202 pub fn allows_rebase_action(self) -> bool {
204 self.allows_review_actions() || self == SessionStatus::InProgress
205 }
206
207 pub fn allows_review_actions(self) -> bool {
209 matches!(self, SessionStatus::Review | SessionStatus::AgentReview)
210 }
211
212 pub fn allows_terminal_continuation(self) -> bool {
214 matches!(self, SessionStatus::Done | SessionStatus::Canceled)
215 }
216
217 pub fn is_read_only(self) -> bool {
219 matches!(self, SessionStatus::Merged)
220 }
221
222 pub fn allows_stacked_child_start(self) -> bool {
224 self.allows_review_actions()
225 }
226
227 pub fn is_stack_branch_mutating(self) -> bool {
229 matches!(
230 self,
231 SessionStatus::InProgress
232 | SessionStatus::Question
233 | SessionStatus::Queued
234 | SessionStatus::Rebasing
235 | SessionStatus::Merging
236 | SessionStatus::Merged
237 )
238 }
239
240 pub fn can_transition_to(self, next: SessionStatus) -> bool {
242 if self == next {
243 return true;
244 }
245
246 if self == SessionStatus::Merged {
247 return next == SessionStatus::Done;
248 }
249
250 matches!(
251 (self, next),
252 (
253 SessionStatus::Draft,
254 SessionStatus::InProgress | SessionStatus::Canceled
255 ) | (
256 SessionStatus::Draft | SessionStatus::InProgress,
257 SessionStatus::Rebasing
258 ) | (
259 SessionStatus::InProgress
260 | SessionStatus::Queued
261 | SessionStatus::Rebasing
262 | SessionStatus::Merging,
263 SessionStatus::Canceled
264 ) | (SessionStatus::Review, SessionStatus::AgentReview)
265 | (SessionStatus::AgentReview, SessionStatus::Review)
266 | (
267 SessionStatus::Review | SessionStatus::AgentReview,
268 SessionStatus::Merged | SessionStatus::Done
269 )
270 | (
271 SessionStatus::Review | SessionStatus::AgentReview | SessionStatus::Question,
272 SessionStatus::InProgress
273 | SessionStatus::Queued
274 | SessionStatus::Rebasing
275 | SessionStatus::Merging
276 | SessionStatus::Canceled
277 )
278 | (
279 SessionStatus::Queued,
280 SessionStatus::Merging | SessionStatus::Review | SessionStatus::AgentReview
281 )
282 | (
283 SessionStatus::InProgress | SessionStatus::Rebasing,
284 SessionStatus::Review | SessionStatus::AgentReview | SessionStatus::Question
285 )
286 | (
287 SessionStatus::Merging,
288 SessionStatus::Done | SessionStatus::Review | SessionStatus::AgentReview
289 )
290 )
291 }
292}
293
294impl fmt::Display for SessionStatus {
295 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
296 let value = match self {
297 SessionStatus::Draft => "Draft",
298 SessionStatus::InProgress => "InProgress",
299 SessionStatus::Review => "Review",
300 SessionStatus::AgentReview => "AgentReview",
301 SessionStatus::Question => "Question",
302 SessionStatus::Queued => "Queued",
303 SessionStatus::Rebasing => "Rebasing",
304 SessionStatus::Merging => "Merging",
305 SessionStatus::Merged => "Merged",
306 SessionStatus::Done => "Done",
307 SessionStatus::Canceled => "Canceled",
308 };
309
310 formatter.write_str(value)
311 }
312}
313
314impl FromStr for SessionStatus {
315 type Err = String;
316
317 fn from_str(value: &str) -> Result<Self, Self::Err> {
318 match value {
319 "Draft" => Ok(SessionStatus::Draft),
320 "InProgress" | "Committing" => Ok(SessionStatus::InProgress),
321 "Review" => Ok(SessionStatus::Review),
322 "AgentReview" => Ok(SessionStatus::AgentReview),
323 "Question" => Ok(SessionStatus::Question),
324 "Queued" => Ok(SessionStatus::Queued),
325 "Rebasing" => Ok(SessionStatus::Rebasing),
326 "Merging" => Ok(SessionStatus::Merging),
327 "Merged" => Ok(SessionStatus::Merged),
328 "Done" => Ok(SessionStatus::Done),
329 "Canceled" => Ok(SessionStatus::Canceled),
330 _ => Err(format!("Unknown status: {value}")),
331 }
332 }
333}
334
335#[derive(Clone, Debug, Eq, PartialEq)]
337pub struct SessionSettings {
338 pub agent: AgentSelection,
340 pub base_branch: String,
342 pub is_draft: bool,
344 pub parent_session_id: Option<SessionId>,
346 pub permission_mode: PermissionMode,
348 pub personality_id: Option<String>,
350 pub project_id: i64,
352 pub reasoning_level: ReasoningLevel,
354 pub response_style: ResponseStyle,
356 pub speed_mode: SpeedMode,
358}
359
360#[derive(Clone, Debug, Eq, PartialEq)]
362pub struct ReviewRequest {
363 pub last_refreshed_at: i64,
365 pub summary: ReviewRequestSummary,
367}
368
369#[derive(Clone, Debug, Eq, PartialEq)]
371pub struct Session {
372 pub created_at: i64,
374 pub draft_prompt: Option<String>,
376 pub id: SessionId,
378 pub messages: Vec<SessionMessage>,
380 pub published_upstream_ref: Option<String>,
382 pub questions: Vec<QuestionItem>,
384 pub queued_messages: Vec<String>,
386 pub review_request: Option<ReviewRequest>,
388 pub settings: SessionSettings,
390 pub status: SessionStatus,
392 pub title: Option<String>,
394 pub updated_at: i64,
396}
397
398impl Session {
399 pub fn env_id(&self) -> EnvId {
404 EnvId::SessionWorktree(self.id.clone())
405 }
406}
407
408pub fn activity_day_key_with_offset(timestamp_seconds: i64, utc_offset_seconds: i64) -> i64 {
410 timestamp_seconds
411 .saturating_add(utc_offset_seconds)
412 .div_euclid(SECONDS_PER_DAY)
413}
414
415const SESSION_BRANCH_PREFIX: &str = "wt/";
416
417const SECONDS_PER_DAY: i64 = 86_400;
419
420#[cfg(test)]
421#[path = "model_test.rs"]
422mod tests;