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,
160 Rebasing,
162 Merging,
164 Merged,
166 Done,
168 Canceled,
170}
171
172impl SessionStatus {
173 pub const ALL: [SessionStatus; 12] = [
175 SessionStatus::Draft,
176 SessionStatus::InProgress,
177 SessionStatus::Review,
178 SessionStatus::AgentReview,
179 SessionStatus::Watching,
180 SessionStatus::Question,
181 SessionStatus::Queued,
182 SessionStatus::Rebasing,
183 SessionStatus::Merging,
184 SessionStatus::Merged,
185 SessionStatus::Done,
186 SessionStatus::Canceled,
187 ];
188
189 pub fn allows_chat_composer(self) -> bool {
191 self.allows_session_actions()
192 || matches!(self, SessionStatus::InProgress | SessionStatus::Rebasing)
193 }
194
195 pub fn allows_session_actions(self) -> bool {
197 self.allows_review_actions()
198 || matches!(self, SessionStatus::Draft | SessionStatus::Question)
199 }
200
201 pub fn allows_diff_view(self) -> bool {
203 self == Self::InProgress
204 || self.allows_review_actions()
205 || self.is_read_only()
206 || self.allows_terminal_continuation()
207 }
208
209 pub fn allows_rebase_action(self) -> bool {
211 self.allows_review_actions() || self == SessionStatus::InProgress
212 }
213
214 pub fn allows_review_actions(self) -> bool {
219 matches!(
220 self,
221 SessionStatus::Review | SessionStatus::AgentReview | SessionStatus::Watching
222 )
223 }
224
225 pub fn allows_terminal_continuation(self) -> bool {
227 matches!(self, SessionStatus::Done | SessionStatus::Canceled)
228 }
229
230 pub fn is_read_only(self) -> bool {
232 matches!(self, SessionStatus::Merged)
233 }
234
235 pub fn can_transition_to(self, next: SessionStatus) -> bool {
237 if self == next {
238 return true;
239 }
240
241 if self == SessionStatus::Merged {
242 return next == SessionStatus::Done;
243 }
244
245 matches!(
246 (self, next),
247 (
248 SessionStatus::Draft,
249 SessionStatus::InProgress | SessionStatus::Canceled
250 ) | (
251 SessionStatus::Draft | SessionStatus::InProgress,
252 SessionStatus::Rebasing
253 ) | (
254 SessionStatus::InProgress
255 | SessionStatus::Queued
256 | SessionStatus::Rebasing
257 | SessionStatus::Merging,
258 SessionStatus::Canceled
259 ) | (
260 SessionStatus::Review,
261 SessionStatus::AgentReview | SessionStatus::Watching
262 ) | (
263 SessionStatus::AgentReview | SessionStatus::Watching,
264 SessionStatus::Review
265 ) | (SessionStatus::Watching, SessionStatus::AgentReview)
266 | (
267 SessionStatus::Review | SessionStatus::AgentReview | SessionStatus::Watching,
268 SessionStatus::Merged | SessionStatus::Done
269 )
270 | (
271 SessionStatus::Review
272 | SessionStatus::AgentReview
273 | SessionStatus::Watching
274 | SessionStatus::Question,
275 SessionStatus::InProgress
276 | SessionStatus::Queued
277 | SessionStatus::Rebasing
278 | SessionStatus::Merging
279 | SessionStatus::Canceled
280 )
281 | (
282 SessionStatus::Queued,
283 SessionStatus::Merging | SessionStatus::Review | SessionStatus::AgentReview
284 )
285 | (
286 SessionStatus::InProgress | SessionStatus::Rebasing,
287 SessionStatus::Review | SessionStatus::AgentReview | SessionStatus::Question
288 )
289 | (
290 SessionStatus::Merging,
291 SessionStatus::Done | SessionStatus::Review | SessionStatus::AgentReview
292 )
293 )
294 }
295}
296
297impl fmt::Display for SessionStatus {
298 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
299 let value = match self {
300 SessionStatus::Draft => "Draft",
301 SessionStatus::InProgress => "InProgress",
302 SessionStatus::Review => "Review",
303 SessionStatus::AgentReview => "AgentReview",
304 SessionStatus::Watching => "Watching",
305 SessionStatus::Question => "Question",
306 SessionStatus::Queued => "Queued",
307 SessionStatus::Rebasing => "Rebasing",
308 SessionStatus::Merging => "Merging",
309 SessionStatus::Merged => "Merged",
310 SessionStatus::Done => "Done",
311 SessionStatus::Canceled => "Canceled",
312 };
313
314 formatter.write_str(value)
315 }
316}
317
318impl FromStr for SessionStatus {
319 type Err = String;
320
321 fn from_str(value: &str) -> Result<Self, Self::Err> {
322 match value {
323 "Draft" => Ok(SessionStatus::Draft),
324 "InProgress" | "Committing" => Ok(SessionStatus::InProgress),
325 "Review" => Ok(SessionStatus::Review),
326 "AgentReview" => Ok(SessionStatus::AgentReview),
327 "Watching" => Ok(SessionStatus::Watching),
328 "Question" => Ok(SessionStatus::Question),
329 "Queued" => Ok(SessionStatus::Queued),
330 "Rebasing" => Ok(SessionStatus::Rebasing),
331 "Merging" => Ok(SessionStatus::Merging),
332 "Merged" => Ok(SessionStatus::Merged),
333 "Done" => Ok(SessionStatus::Done),
334 "Canceled" => Ok(SessionStatus::Canceled),
335 _ => Err(format!("Unknown status: {value}")),
336 }
337 }
338}
339
340#[derive(Clone, Debug, Eq, PartialEq)]
342pub struct SessionSettings {
343 pub agent: AgentSelection,
345 pub base_branch: String,
347 pub is_draft: bool,
349 pub project_id: i64,
351 pub reasoning_level: ReasoningLevel,
353 pub response_style: ResponseStyle,
355 pub speed_mode: SpeedMode,
357}
358
359#[derive(Clone, Debug, Eq, PartialEq)]
361pub struct ReviewRequest {
362 pub last_refreshed_at: i64,
364 pub summary: ReviewRequestSummary,
366}
367
368#[derive(Clone, Debug, Eq, PartialEq)]
370pub struct Session {
371 pub created_at: i64,
373 pub draft_prompt: Option<String>,
375 pub id: SessionId,
377 pub messages: Vec<SessionMessage>,
379 pub published_upstream_ref: Option<String>,
381 pub questions: Vec<QuestionItem>,
383 pub queued_messages: Vec<String>,
385 pub review_request: Option<ReviewRequest>,
387 pub settings: SessionSettings,
389 pub status: SessionStatus,
391 pub title: Option<String>,
393 pub updated_at: i64,
395}
396
397impl Session {
398 pub fn env_id(&self) -> EnvId {
403 EnvId::SessionWorktree(self.id.clone())
404 }
405}
406
407#[derive(Clone, Debug, Eq, PartialEq)]
409pub struct SessionSummary {
410 pub id: SessionId,
412 pub status: SessionStatus,
414 pub title: Option<String>,
416 pub updated_at: i64,
418}
419
420#[derive(Clone, Debug, Eq, PartialEq)]
423pub struct SessionListEntry {
424 pub stats: Option<SessionListStats>,
427 pub summary: SessionSummary,
429}
430
431impl From<SessionSummary> for SessionListEntry {
432 fn from(summary: SessionSummary) -> Self {
433 Self {
434 stats: None,
435 summary,
436 }
437 }
438}
439
440#[derive(Clone, Debug, Eq, PartialEq)]
442pub struct SessionListStats {
443 pub added_lines: u64,
445 pub deleted_lines: u64,
447 pub has_merge_conflict: bool,
450 pub in_progress_started_at: Option<i64>,
453 pub in_progress_total_seconds: i64,
455 pub model: AgentModel,
457 pub reasoning_level: ReasoningLevel,
459 pub review_request: Option<ReviewRequestSummary>,
461 pub size_label: String,
463}
464
465pub fn activity_day_key_with_offset(timestamp_seconds: i64, utc_offset_seconds: i64) -> i64 {
467 timestamp_seconds
468 .saturating_add(utc_offset_seconds)
469 .div_euclid(SECONDS_PER_DAY)
470}
471
472const SESSION_BRANCH_PREFIX: &str = "wt/";
473
474const SECONDS_PER_DAY: i64 = 86_400;
476
477#[cfg(test)]
478#[path = "model_test.rs"]
479mod tests;