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::{
12 ForgeKind, ReviewRequestMergeOutcome, ReviewRequestState, ReviewRequestSummary,
13};
14use ag_protocol::QuestionItem;
15use serde::de::{self, Deserializer};
16use serde::ser::Serializer;
17use serde::{Deserialize, Serialize};
18
19use crate::message::SessionMessage;
20use crate::{AgentModel, AgentSelection, EnvId, ReasoningLevel};
21
22pub fn session_branch(session_id: &str) -> String {
24 let prefix_length = session_id.len().min(8);
25
26 format!("{SESSION_BRANCH_PREFIX}{}", &session_id[..prefix_length])
27}
28
29#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
35pub struct SessionId(Arc<str>);
36
37impl SessionId {
38 pub fn as_str(&self) -> &str {
40 self.0.as_ref()
41 }
42}
43
44impl AsRef<str> for SessionId {
45 fn as_ref(&self) -> &str {
46 self.as_str()
47 }
48}
49
50impl AsRef<Path> for SessionId {
51 fn as_ref(&self) -> &Path {
52 Path::new(self.as_str())
53 }
54}
55
56impl Borrow<str> for SessionId {
57 fn borrow(&self) -> &str {
58 self.as_str()
59 }
60}
61
62impl Deref for SessionId {
63 type Target = str;
64
65 fn deref(&self) -> &Self::Target {
66 self.as_str()
67 }
68}
69
70impl fmt::Display for SessionId {
71 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
72 formatter.write_str(self.as_str())
73 }
74}
75
76impl From<&str> for SessionId {
77 fn from(value: &str) -> Self {
78 Self(Arc::<str>::from(value))
79 }
80}
81
82impl From<String> for SessionId {
83 fn from(value: String) -> Self {
84 Self(Arc::<str>::from(value))
85 }
86}
87
88impl From<Arc<str>> for SessionId {
89 fn from(value: Arc<str>) -> Self {
90 Self(value)
91 }
92}
93
94impl From<SessionId> for String {
95 fn from(value: SessionId) -> Self {
96 value.as_str().to_string()
97 }
98}
99
100impl PartialEq<str> for SessionId {
101 fn eq(&self, other: &str) -> bool {
102 self.as_str() == other
103 }
104}
105
106impl PartialEq<&str> for SessionId {
107 fn eq(&self, other: &&str) -> bool {
108 self.as_str() == *other
109 }
110}
111
112impl PartialEq<String> for SessionId {
113 fn eq(&self, other: &String) -> bool {
114 self.as_str() == other
115 }
116}
117
118impl PartialEq<&String> for SessionId {
119 fn eq(&self, other: &&String) -> bool {
120 self.as_str() == other.as_str()
121 }
122}
123
124impl Serialize for SessionId {
125 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
126 where
127 S: Serializer,
128 {
129 serializer.serialize_str(self.as_str())
130 }
131}
132
133impl<'de> Deserialize<'de> for SessionId {
134 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
135 where
136 D: Deserializer<'de>,
137 {
138 String::deserialize(deserializer)
139 .map(Self::from)
140 .map_err(de::Error::custom)
141 }
142}
143
144#[derive(Clone, Copy, Debug, Eq, PartialEq)]
146pub enum SessionStatus {
147 Draft,
149 InProgress,
151 Review,
153 AgentReview,
155 Watching,
158 Question,
160 Queued,
163 Rebasing,
165 Merging,
167 Merged,
169 Done,
171 Canceled,
173}
174
175impl SessionStatus {
176 pub const ALL: [SessionStatus; 12] = [
178 SessionStatus::Draft,
179 SessionStatus::InProgress,
180 SessionStatus::Review,
181 SessionStatus::AgentReview,
182 SessionStatus::Watching,
183 SessionStatus::Question,
184 SessionStatus::Queued,
185 SessionStatus::Rebasing,
186 SessionStatus::Merging,
187 SessionStatus::Merged,
188 SessionStatus::Done,
189 SessionStatus::Canceled,
190 ];
191
192 pub fn allows_chat_composer(self) -> bool {
194 self.allows_session_actions()
195 || matches!(self, SessionStatus::InProgress | SessionStatus::Rebasing)
196 }
197
198 pub fn allows_session_actions(self) -> bool {
200 self.allows_review_actions()
201 || matches!(self, SessionStatus::Draft | SessionStatus::Question)
202 }
203
204 pub fn allows_diff_view(self) -> bool {
206 self == Self::InProgress
207 || self.allows_review_actions()
208 || self.is_read_only()
209 || self.allows_terminal_continuation()
210 }
211
212 pub fn allows_rebase_action(self) -> bool {
214 self.allows_review_actions() || self == SessionStatus::InProgress
215 }
216
217 pub fn allows_review_actions(self) -> bool {
222 matches!(
223 self,
224 SessionStatus::Review | SessionStatus::AgentReview | SessionStatus::Watching
225 )
226 }
227
228 pub fn allows_terminal_continuation(self) -> bool {
230 matches!(self, SessionStatus::Done | SessionStatus::Canceled)
231 }
232
233 pub fn is_read_only(self) -> bool {
235 matches!(self, SessionStatus::Merged)
236 }
237
238 pub fn can_transition_to(self, next: SessionStatus) -> bool {
240 if self == next {
241 return true;
242 }
243
244 if self == SessionStatus::Merged {
245 return next == SessionStatus::Done;
246 }
247
248 matches!(
249 (self, next),
250 (
251 SessionStatus::Draft,
252 SessionStatus::InProgress | SessionStatus::Canceled
253 ) | (
254 SessionStatus::Draft | SessionStatus::InProgress,
255 SessionStatus::Rebasing
256 ) | (
257 SessionStatus::InProgress
258 | SessionStatus::Queued
259 | SessionStatus::Rebasing
260 | SessionStatus::Merging,
261 SessionStatus::Canceled
262 ) | (
263 SessionStatus::Review,
264 SessionStatus::AgentReview | SessionStatus::Watching
265 ) | (
266 SessionStatus::AgentReview | SessionStatus::Watching,
267 SessionStatus::Review
268 ) | (SessionStatus::Watching, SessionStatus::AgentReview)
269 | (
270 SessionStatus::Review | SessionStatus::AgentReview | SessionStatus::Watching,
271 SessionStatus::Merged | SessionStatus::Done
272 )
273 | (
274 SessionStatus::Review
275 | SessionStatus::AgentReview
276 | SessionStatus::Watching
277 | SessionStatus::Question,
278 SessionStatus::InProgress
279 | SessionStatus::Queued
280 | SessionStatus::Rebasing
281 | SessionStatus::Merging
282 | SessionStatus::Canceled
283 )
284 | (
285 SessionStatus::Queued,
286 SessionStatus::Merging
287 | SessionStatus::Review
288 | SessionStatus::AgentReview
289 | SessionStatus::Watching
290 | SessionStatus::Merged
291 )
292 | (
293 SessionStatus::InProgress | SessionStatus::Rebasing,
294 SessionStatus::Review | SessionStatus::AgentReview | SessionStatus::Question
295 )
296 | (
297 SessionStatus::Merging,
298 SessionStatus::Done | SessionStatus::Review | SessionStatus::AgentReview
299 )
300 )
301 }
302}
303
304impl fmt::Display for SessionStatus {
305 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
306 let value = match self {
307 SessionStatus::Draft => "Draft",
308 SessionStatus::InProgress => "InProgress",
309 SessionStatus::Review => "Review",
310 SessionStatus::AgentReview => "AgentReview",
311 SessionStatus::Watching => "Watching",
312 SessionStatus::Question => "Question",
313 SessionStatus::Queued => "Queued",
314 SessionStatus::Rebasing => "Rebasing",
315 SessionStatus::Merging => "Merging",
316 SessionStatus::Merged => "Merged",
317 SessionStatus::Done => "Done",
318 SessionStatus::Canceled => "Canceled",
319 };
320
321 formatter.write_str(value)
322 }
323}
324
325impl FromStr for SessionStatus {
326 type Err = String;
327
328 fn from_str(value: &str) -> Result<Self, Self::Err> {
329 match value {
330 "Draft" => Ok(SessionStatus::Draft),
331 "InProgress" | "Committing" => Ok(SessionStatus::InProgress),
332 "Review" => Ok(SessionStatus::Review),
333 "AgentReview" => Ok(SessionStatus::AgentReview),
334 "Watching" => Ok(SessionStatus::Watching),
335 "Question" => Ok(SessionStatus::Question),
336 "Queued" => Ok(SessionStatus::Queued),
337 "Rebasing" => Ok(SessionStatus::Rebasing),
338 "Merging" => Ok(SessionStatus::Merging),
339 "Merged" => Ok(SessionStatus::Merged),
340 "Done" => Ok(SessionStatus::Done),
341 "Canceled" => Ok(SessionStatus::Canceled),
342 _ => Err(format!("Unknown status: {value}")),
343 }
344 }
345}
346
347#[derive(Clone, Debug, Eq, PartialEq)]
349pub struct SessionSettings {
350 pub agent: AgentSelection,
352 pub base_branch: String,
354 pub is_draft: bool,
356 pub project_id: i64,
358 pub reasoning_level: ReasoningLevel,
360 pub response_style: ResponseStyle,
362 pub speed_mode: SpeedMode,
364}
365
366#[derive(Clone, Debug, Eq, PartialEq)]
368pub struct ReviewRequest {
369 pub last_refreshed_at: i64,
371 pub summary: ReviewRequestSummary,
373}
374
375#[derive(Clone, Debug, Eq, PartialEq)]
377pub struct ReviewRequestMerge {
378 pub outcome: ReviewRequestMergeOutcome,
380 pub review_request: Option<ReviewRequestSummary>,
383}
384
385#[derive(Clone, Debug, Eq, PartialEq)]
387pub struct Session {
388 pub created_at: i64,
390 pub draft_prompt: Option<String>,
392 pub focused_review: Option<SessionFocusedReview>,
396 pub graph: Option<crate::SessionGraphSummary>,
400 pub graph_question_target: Option<String>,
411 pub id: SessionId,
413 pub messages: Vec<SessionMessage>,
415 pub progress: Option<String>,
419 pub published_upstream_ref: Option<String>,
421 pub questions: Vec<QuestionItem>,
424 pub queued_actions: Vec<String>,
428 pub queued_messages: Vec<String>,
430 pub review_request: Option<ReviewRequest>,
432 pub settings: SessionSettings,
434 pub status: SessionStatus,
436 pub title: Option<String>,
438 pub updated_at: i64,
440}
441
442impl Session {
443 pub fn env_id(&self) -> EnvId {
448 EnvId::SessionWorktree(self.id.clone())
449 }
450}
451
452#[derive(Clone, Debug, Eq, PartialEq)]
454pub enum SessionFocusedReview {
455 Ready {
457 text: String,
459 },
460 Failed {
463 message: String,
465 },
466}
467
468#[derive(Clone, Debug, Eq, PartialEq)]
470pub struct SessionSummary {
471 pub id: SessionId,
473 pub status: SessionStatus,
475 pub title: Option<String>,
477 pub updated_at: i64,
479}
480
481#[derive(Clone, Debug, Eq, PartialEq)]
484pub struct SessionListEntry {
485 pub stats: Option<SessionListStats>,
488 pub summary: SessionSummary,
490}
491
492impl From<SessionSummary> for SessionListEntry {
493 fn from(summary: SessionSummary) -> Self {
494 Self {
495 stats: None,
496 summary,
497 }
498 }
499}
500
501#[derive(Clone, Debug, Eq, PartialEq)]
503pub struct SessionListStats {
504 pub added_lines: u64,
506 pub base_ahead_behind: Option<(u32, u32)>,
509 pub deleted_lines: u64,
511 pub has_merge_conflict: bool,
514 pub in_progress_started_at: Option<i64>,
517 pub in_progress_total_seconds: i64,
519 pub is_published: bool,
521 pub model: AgentModel,
523 pub reasoning_level: ReasoningLevel,
525 pub review_request: Option<ReviewRequestSummary>,
527 pub size_label: String,
529 pub upstream_ahead_behind: Option<(u32, u32)>,
533}
534
535pub fn activity_day_key_with_offset(timestamp_seconds: i64, utc_offset_seconds: i64) -> i64 {
537 timestamp_seconds
538 .saturating_add(utc_offset_seconds)
539 .div_euclid(SECONDS_PER_DAY)
540}
541
542const SESSION_BRANCH_PREFIX: &str = "wt/";
543
544const SECONDS_PER_DAY: i64 = 86_400;
546
547#[cfg(test)]
548#[path = "model_test.rs"]
549mod tests;