Skip to main content

ag_session/
model.rs

1//! Shared session identity, lifecycle, settings, and aggregate models.
2
3use 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
20/// Returns the default worktree branch name for a session.
21pub 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/// Shared stable identifier for one session.
28///
29/// Session identifiers are cloned heavily across maps, events, and worker
30/// tasks. Wrapping the identifier in `Arc<str>` keeps those clones cheap while
31/// retaining borrowed `&str` lookup support.
32#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
33pub struct SessionId(Arc<str>);
34
35impl SessionId {
36    /// Returns the session identifier as a string slice.
37    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/// High-level lifecycle state for one session.
143#[derive(Clone, Copy, Debug, Eq, PartialEq)]
144pub enum SessionStatus {
145    /// Session has been created but has not started its first agent turn yet.
146    Draft,
147    /// An agent turn or its post-processing workflow is running.
148    InProgress,
149    /// The session is ready for user review and follow-up work.
150    Review,
151    /// The session is generating focused-review output.
152    AgentReview,
153    /// The session is waiting for model clarification responses.
154    Question,
155    /// The session is waiting in the merge queue.
156    Queued,
157    /// The session branch is being rebased.
158    Rebasing,
159    /// The session branch is being merged.
160    Merging,
161    /// A remote merge awaits local target-branch synchronization.
162    Merged,
163    /// The session completed successfully.
164    Done,
165    /// The session was canceled before completion.
166    Canceled,
167}
168
169impl SessionStatus {
170    /// Ordered list of all session statuses.
171    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    /// Returns whether this status permits opening the chat composer.
186    pub fn allows_chat_composer(self) -> bool {
187        self.allows_session_actions()
188            || matches!(self, SessionStatus::InProgress | SessionStatus::Rebasing)
189    }
190
191    /// Returns whether this status permits idle session actions.
192    pub fn allows_session_actions(self) -> bool {
193        self.allows_review_actions()
194            || matches!(self, SessionStatus::Draft | SessionStatus::Question)
195    }
196
197    /// Returns whether this status permits opening the session diff.
198    pub fn allows_diff_view(self) -> bool {
199        self == Self::InProgress
200            || self.allows_review_actions()
201            || self.is_read_only()
202            || self.allows_terminal_continuation()
203    }
204
205    /// Returns whether this status permits starting or queueing session sync.
206    pub fn allows_rebase_action(self) -> bool {
207        self.allows_review_actions() || self == SessionStatus::InProgress
208    }
209
210    /// Returns whether this status keeps review actions enabled.
211    pub fn allows_review_actions(self) -> bool {
212        matches!(self, SessionStatus::Review | SessionStatus::AgentReview)
213    }
214
215    /// Returns whether this status can seed a follow-on continuation session.
216    pub fn allows_terminal_continuation(self) -> bool {
217        matches!(self, SessionStatus::Done | SessionStatus::Canceled)
218    }
219
220    /// Returns whether this lifecycle state permits only local inspection.
221    pub fn is_read_only(self) -> bool {
222        matches!(self, SessionStatus::Merged)
223    }
224
225    /// Returns whether this status is stable enough to start a stacked child.
226    pub fn allows_stacked_child_start(self) -> bool {
227        self.allows_review_actions()
228    }
229
230    /// Returns whether this status represents branch-mutating stack work.
231    pub fn is_stack_branch_mutating(self) -> bool {
232        matches!(
233            self,
234            SessionStatus::InProgress
235                | SessionStatus::Question
236                | SessionStatus::Queued
237                | SessionStatus::Rebasing
238                | SessionStatus::Merging
239                | SessionStatus::Merged
240        )
241    }
242
243    /// Returns whether a transition to `next` is valid.
244    pub fn can_transition_to(self, next: SessionStatus) -> bool {
245        if self == next {
246            return true;
247        }
248
249        if self == SessionStatus::Merged {
250            return next == SessionStatus::Done;
251        }
252
253        matches!(
254            (self, next),
255            (
256                SessionStatus::Draft,
257                SessionStatus::InProgress | SessionStatus::Canceled
258            ) | (
259                SessionStatus::Draft | SessionStatus::InProgress,
260                SessionStatus::Rebasing
261            ) | (
262                SessionStatus::InProgress
263                    | SessionStatus::Queued
264                    | SessionStatus::Rebasing
265                    | SessionStatus::Merging,
266                SessionStatus::Canceled
267            ) | (SessionStatus::Review, SessionStatus::AgentReview)
268                | (SessionStatus::AgentReview, SessionStatus::Review)
269                | (
270                    SessionStatus::Review | SessionStatus::AgentReview,
271                    SessionStatus::Merged | SessionStatus::Done
272                )
273                | (
274                    SessionStatus::Review | SessionStatus::AgentReview | 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::Question => "Question",
305            SessionStatus::Queued => "Queued",
306            SessionStatus::Rebasing => "Rebasing",
307            SessionStatus::Merging => "Merging",
308            SessionStatus::Merged => "Merged",
309            SessionStatus::Done => "Done",
310            SessionStatus::Canceled => "Canceled",
311        };
312
313        formatter.write_str(value)
314    }
315}
316
317impl FromStr for SessionStatus {
318    type Err = String;
319
320    fn from_str(value: &str) -> Result<Self, Self::Err> {
321        match value {
322            "Draft" => Ok(SessionStatus::Draft),
323            "InProgress" | "Committing" => Ok(SessionStatus::InProgress),
324            "Review" => Ok(SessionStatus::Review),
325            "AgentReview" => Ok(SessionStatus::AgentReview),
326            "Question" => Ok(SessionStatus::Question),
327            "Queued" => Ok(SessionStatus::Queued),
328            "Rebasing" => Ok(SessionStatus::Rebasing),
329            "Merging" => Ok(SessionStatus::Merging),
330            "Merged" => Ok(SessionStatus::Merged),
331            "Done" => Ok(SessionStatus::Done),
332            "Canceled" => Ok(SessionStatus::Canceled),
333            _ => Err(format!("Unknown status: {value}")),
334        }
335    }
336}
337
338/// Complete session-scoped execution settings returned by the API.
339#[derive(Clone, Debug, Eq, PartialEq)]
340pub struct SessionSettings {
341    /// Agent provider and model selected for this session.
342    pub agent: AgentSelection,
343    /// Base branch used to create the session.
344    pub base_branch: String,
345    /// Whether the session uses deferred draft materialization.
346    pub is_draft: bool,
347    /// Immediate parent session for a stacked session.
348    pub parent_session_id: Option<SessionId>,
349    /// Provider permission mode used for future turns.
350    pub permission_mode: PermissionMode,
351    /// Owning project identifier.
352    pub project_id: i64,
353    /// Session-scoped reasoning level.
354    pub reasoning_level: ReasoningLevel,
355    /// Session-scoped response style.
356    pub response_style: ResponseStyle,
357    /// Session-scoped response-speed preference.
358    pub speed_mode: SpeedMode,
359}
360
361/// Persisted forge linkage for one session.
362#[derive(Clone, Debug, Eq, PartialEq)]
363pub struct ReviewRequest {
364    /// Unix timestamp of the most recent successful refresh.
365    pub last_refreshed_at: i64,
366    /// Normalized remote summary captured at `last_refreshed_at`.
367    pub summary: ReviewRequestSummary,
368}
369
370/// Complete persisted session aggregate returned by the programmatic API.
371#[derive(Clone, Debug, Eq, PartialEq)]
372pub struct Session {
373    /// Session creation timestamp in Unix seconds.
374    pub created_at: i64,
375    /// Staged draft prompt that has not entered the durable transcript.
376    pub draft_prompt: Option<String>,
377    /// Stable session identifier.
378    pub id: SessionId,
379    /// Ordered durable transcript messages.
380    pub messages: Vec<SessionMessage>,
381    /// Published upstream branch reference, when present.
382    pub published_upstream_ref: Option<String>,
383    /// Structured clarification questions waiting for answers.
384    pub questions: Vec<QuestionItem>,
385    /// Chat messages waiting behind the active turn or queued branch action.
386    pub queued_messages: Vec<String>,
387    /// Persisted review-request linkage, when present.
388    pub review_request: Option<ReviewRequest>,
389    /// Complete session-scoped execution settings.
390    pub settings: SessionSettings,
391    /// Current lifecycle status.
392    pub status: SessionStatus,
393    /// Optional user-visible session title.
394    pub title: Option<String>,
395    /// Last update timestamp in Unix seconds.
396    pub updated_at: i64,
397}
398
399impl Session {
400    /// Returns the shared local environment owned by this session.
401    ///
402    /// Identity exists before workspace preparation and survives cleanup;
403    /// it does not imply that the workspace is available for execution.
404    pub fn env_id(&self) -> EnvId {
405        EnvId::SessionWorktree(self.id.clone())
406    }
407}
408
409/// Converts Unix timestamp seconds to a day key after applying a UTC offset.
410pub fn activity_day_key_with_offset(timestamp_seconds: i64, utc_offset_seconds: i64) -> i64 {
411    timestamp_seconds
412        .saturating_add(utc_offset_seconds)
413        .div_euclid(SECONDS_PER_DAY)
414}
415
416const SESSION_BRANCH_PREFIX: &str = "wt/";
417
418/// Number of seconds in one activity-calendar day.
419const SECONDS_PER_DAY: i64 = 86_400;
420
421#[cfg(test)]
422#[path = "model_test.rs"]
423mod tests;