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::{AgentModel, 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 Watching,
156 Question,
158 Queued,
161 Rebasing,
163 Merging,
165 Merged,
167 Done,
169 Canceled,
171}
172
173impl SessionStatus {
174 pub const ALL: [SessionStatus; 12] = [
176 SessionStatus::Draft,
177 SessionStatus::InProgress,
178 SessionStatus::Review,
179 SessionStatus::AgentReview,
180 SessionStatus::Watching,
181 SessionStatus::Question,
182 SessionStatus::Queued,
183 SessionStatus::Rebasing,
184 SessionStatus::Merging,
185 SessionStatus::Merged,
186 SessionStatus::Done,
187 SessionStatus::Canceled,
188 ];
189
190 pub fn allows_chat_composer(self) -> bool {
192 self.allows_session_actions()
193 || matches!(self, SessionStatus::InProgress | SessionStatus::Rebasing)
194 }
195
196 pub fn allows_session_actions(self) -> bool {
198 self.allows_review_actions()
199 || matches!(self, SessionStatus::Draft | SessionStatus::Question)
200 }
201
202 pub fn allows_diff_view(self) -> bool {
204 self == Self::InProgress
205 || self.allows_review_actions()
206 || self.is_read_only()
207 || self.allows_terminal_continuation()
208 }
209
210 pub fn allows_rebase_action(self) -> bool {
212 self.allows_review_actions() || self == SessionStatus::InProgress
213 }
214
215 pub fn allows_review_actions(self) -> bool {
220 matches!(
221 self,
222 SessionStatus::Review | SessionStatus::AgentReview | SessionStatus::Watching
223 )
224 }
225
226 pub fn allows_terminal_continuation(self) -> bool {
228 matches!(self, SessionStatus::Done | SessionStatus::Canceled)
229 }
230
231 pub fn is_read_only(self) -> bool {
233 matches!(self, SessionStatus::Merged)
234 }
235
236 pub fn can_transition_to(self, next: SessionStatus) -> bool {
238 if self == next {
239 return true;
240 }
241
242 if self == SessionStatus::Merged {
243 return next == SessionStatus::Done;
244 }
245
246 matches!(
247 (self, next),
248 (
249 SessionStatus::Draft,
250 SessionStatus::InProgress | SessionStatus::Canceled
251 ) | (
252 SessionStatus::Draft | SessionStatus::InProgress,
253 SessionStatus::Rebasing
254 ) | (
255 SessionStatus::InProgress
256 | SessionStatus::Queued
257 | SessionStatus::Rebasing
258 | SessionStatus::Merging,
259 SessionStatus::Canceled
260 ) | (
261 SessionStatus::Review,
262 SessionStatus::AgentReview | SessionStatus::Watching
263 ) | (
264 SessionStatus::AgentReview | SessionStatus::Watching,
265 SessionStatus::Review
266 ) | (SessionStatus::Watching, SessionStatus::AgentReview)
267 | (
268 SessionStatus::Review | SessionStatus::AgentReview | SessionStatus::Watching,
269 SessionStatus::Merged | SessionStatus::Done
270 )
271 | (
272 SessionStatus::Review
273 | SessionStatus::AgentReview
274 | SessionStatus::Watching
275 | SessionStatus::Question,
276 SessionStatus::InProgress
277 | SessionStatus::Queued
278 | SessionStatus::Rebasing
279 | SessionStatus::Merging
280 | SessionStatus::Canceled
281 )
282 | (
283 SessionStatus::Queued,
284 SessionStatus::Merging
285 | SessionStatus::Review
286 | SessionStatus::AgentReview
287 | SessionStatus::Watching
288 | SessionStatus::Merged
289 )
290 | (
291 SessionStatus::InProgress | SessionStatus::Rebasing,
292 SessionStatus::Review | SessionStatus::AgentReview | SessionStatus::Question
293 )
294 | (
295 SessionStatus::Merging,
296 SessionStatus::Done | SessionStatus::Review | SessionStatus::AgentReview
297 )
298 )
299 }
300}
301
302impl fmt::Display for SessionStatus {
303 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
304 let value = match self {
305 SessionStatus::Draft => "Draft",
306 SessionStatus::InProgress => "InProgress",
307 SessionStatus::Review => "Review",
308 SessionStatus::AgentReview => "AgentReview",
309 SessionStatus::Watching => "Watching",
310 SessionStatus::Question => "Question",
311 SessionStatus::Queued => "Queued",
312 SessionStatus::Rebasing => "Rebasing",
313 SessionStatus::Merging => "Merging",
314 SessionStatus::Merged => "Merged",
315 SessionStatus::Done => "Done",
316 SessionStatus::Canceled => "Canceled",
317 };
318
319 formatter.write_str(value)
320 }
321}
322
323impl FromStr for SessionStatus {
324 type Err = String;
325
326 fn from_str(value: &str) -> Result<Self, Self::Err> {
327 match value {
328 "Draft" => Ok(SessionStatus::Draft),
329 "InProgress" | "Committing" => Ok(SessionStatus::InProgress),
330 "Review" => Ok(SessionStatus::Review),
331 "AgentReview" => Ok(SessionStatus::AgentReview),
332 "Watching" => Ok(SessionStatus::Watching),
333 "Question" => Ok(SessionStatus::Question),
334 "Queued" => Ok(SessionStatus::Queued),
335 "Rebasing" => Ok(SessionStatus::Rebasing),
336 "Merging" => Ok(SessionStatus::Merging),
337 "Merged" => Ok(SessionStatus::Merged),
338 "Done" => Ok(SessionStatus::Done),
339 "Canceled" => Ok(SessionStatus::Canceled),
340 _ => Err(format!("Unknown status: {value}")),
341 }
342 }
343}
344
345#[derive(Clone, Debug, Eq, PartialEq)]
347pub struct SessionSettings {
348 pub agent: AgentSelection,
350 pub base_branch: String,
352 pub is_draft: bool,
354 pub project_id: i64,
356 pub reasoning_level: ReasoningLevel,
358 pub response_style: ResponseStyle,
360 pub speed_mode: SpeedMode,
362}
363
364#[derive(Clone, Debug, Eq, PartialEq)]
366pub struct ReviewRequest {
367 pub last_refreshed_at: i64,
369 pub summary: ReviewRequestSummary,
371}
372
373#[derive(Clone, Debug, Eq, PartialEq)]
375pub struct Session {
376 pub created_at: i64,
378 pub draft_prompt: Option<String>,
380 pub focused_review: Option<SessionFocusedReview>,
384 pub graph: Option<crate::SessionGraphSummary>,
388 pub graph_question_target: Option<String>,
399 pub id: SessionId,
401 pub messages: Vec<SessionMessage>,
403 pub progress: Option<String>,
407 pub published_upstream_ref: Option<String>,
409 pub questions: Vec<QuestionItem>,
412 pub queued_actions: Vec<String>,
416 pub queued_messages: Vec<String>,
418 pub review_request: Option<ReviewRequest>,
420 pub settings: SessionSettings,
422 pub status: SessionStatus,
424 pub title: Option<String>,
426 pub updated_at: i64,
428}
429
430impl Session {
431 pub fn env_id(&self) -> EnvId {
436 EnvId::SessionWorktree(self.id.clone())
437 }
438}
439
440#[derive(Clone, Debug, Eq, PartialEq)]
442pub enum SessionFocusedReview {
443 Ready {
445 text: String,
447 },
448 Failed {
451 message: String,
453 },
454}
455
456#[derive(Clone, Debug, Eq, PartialEq)]
458pub struct SessionSummary {
459 pub id: SessionId,
461 pub status: SessionStatus,
463 pub title: Option<String>,
465 pub updated_at: i64,
467}
468
469#[derive(Clone, Debug, Eq, PartialEq)]
472pub struct SessionListEntry {
473 pub stats: Option<SessionListStats>,
476 pub summary: SessionSummary,
478}
479
480impl From<SessionSummary> for SessionListEntry {
481 fn from(summary: SessionSummary) -> Self {
482 Self {
483 stats: None,
484 summary,
485 }
486 }
487}
488
489#[derive(Clone, Debug, Eq, PartialEq)]
491pub struct SessionListStats {
492 pub added_lines: u64,
494 pub base_ahead_behind: Option<(u32, u32)>,
497 pub deleted_lines: u64,
499 pub has_merge_conflict: bool,
502 pub in_progress_started_at: Option<i64>,
505 pub in_progress_total_seconds: i64,
507 pub is_published: bool,
509 pub model: AgentModel,
511 pub reasoning_level: ReasoningLevel,
513 pub review_request: Option<ReviewRequestSummary>,
515 pub size_label: String,
517 pub upstream_ahead_behind: Option<(u32, u32)>,
521}
522
523pub fn activity_day_key_with_offset(timestamp_seconds: i64, utc_offset_seconds: i64) -> i64 {
525 timestamp_seconds
526 .saturating_add(utc_offset_seconds)
527 .div_euclid(SECONDS_PER_DAY)
528}
529
530const SESSION_BRANCH_PREFIX: &str = "wt/";
531
532const SECONDS_PER_DAY: i64 = 86_400;
534
535#[cfg(test)]
536#[path = "model_test.rs"]
537mod tests;