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 review-ready session watches its linked review request and
154    /// resolves failing checks, review comments, and merge conflicts.
155    Watching,
156    /// The session is waiting for model clarification responses.
157    Question,
158    /// The session is waiting in the merge queue.
159    Queued,
160    /// The session branch is being rebased.
161    Rebasing,
162    /// The session branch is being merged.
163    Merging,
164    /// A remote merge awaits local target-branch synchronization.
165    Merged,
166    /// The session completed successfully.
167    Done,
168    /// The session was canceled before completion.
169    Canceled,
170}
171
172impl SessionStatus {
173    /// Ordered list of all session statuses.
174    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    /// Returns whether this status permits opening the chat composer.
190    pub fn allows_chat_composer(self) -> bool {
191        self.allows_session_actions()
192            || matches!(self, SessionStatus::InProgress | SessionStatus::Rebasing)
193    }
194
195    /// Returns whether this status permits idle session actions.
196    pub fn allows_session_actions(self) -> bool {
197        self.allows_review_actions()
198            || matches!(self, SessionStatus::Draft | SessionStatus::Question)
199    }
200
201    /// Returns whether this status permits opening the session diff.
202    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    /// Returns whether this status permits starting or queueing session sync.
210    pub fn allows_rebase_action(self) -> bool {
211        self.allows_review_actions() || self == SessionStatus::InProgress
212    }
213
214    /// Returns whether this status keeps review actions enabled.
215    ///
216    /// `Watching` is a review-ready state: it adds automatic review-request
217    /// follow-up without removing any manual review action.
218    pub fn allows_review_actions(self) -> bool {
219        matches!(
220            self,
221            SessionStatus::Review | SessionStatus::AgentReview | SessionStatus::Watching
222        )
223    }
224
225    /// Returns whether this status can seed a follow-on continuation session.
226    pub fn allows_terminal_continuation(self) -> bool {
227        matches!(self, SessionStatus::Done | SessionStatus::Canceled)
228    }
229
230    /// Returns whether this lifecycle state permits only local inspection.
231    pub fn is_read_only(self) -> bool {
232        matches!(self, SessionStatus::Merged)
233    }
234
235    /// Returns whether this status is stable enough to start a stacked child.
236    pub fn allows_stacked_child_start(self) -> bool {
237        self.allows_review_actions()
238    }
239
240    /// Returns whether this status represents branch-mutating stack work.
241    pub fn is_stack_branch_mutating(self) -> bool {
242        matches!(
243            self,
244            SessionStatus::InProgress
245                | SessionStatus::Question
246                | SessionStatus::Queued
247                | SessionStatus::Rebasing
248                | SessionStatus::Merging
249                | SessionStatus::Merged
250        )
251    }
252
253    /// Returns whether a transition to `next` is valid.
254    pub fn can_transition_to(self, next: SessionStatus) -> bool {
255        if self == next {
256            return true;
257        }
258
259        if self == SessionStatus::Merged {
260            return next == SessionStatus::Done;
261        }
262
263        matches!(
264            (self, next),
265            (
266                SessionStatus::Draft,
267                SessionStatus::InProgress | SessionStatus::Canceled
268            ) | (
269                SessionStatus::Draft | SessionStatus::InProgress,
270                SessionStatus::Rebasing
271            ) | (
272                SessionStatus::InProgress
273                    | SessionStatus::Queued
274                    | SessionStatus::Rebasing
275                    | SessionStatus::Merging,
276                SessionStatus::Canceled
277            ) | (
278                SessionStatus::Review,
279                SessionStatus::AgentReview | SessionStatus::Watching
280            ) | (
281                SessionStatus::AgentReview | SessionStatus::Watching,
282                SessionStatus::Review
283            ) | (SessionStatus::Watching, SessionStatus::AgentReview)
284                | (
285                    SessionStatus::Review | SessionStatus::AgentReview | SessionStatus::Watching,
286                    SessionStatus::Merged | SessionStatus::Done
287                )
288                | (
289                    SessionStatus::Review
290                        | SessionStatus::AgentReview
291                        | SessionStatus::Watching
292                        | SessionStatus::Question,
293                    SessionStatus::InProgress
294                        | SessionStatus::Queued
295                        | SessionStatus::Rebasing
296                        | SessionStatus::Merging
297                        | SessionStatus::Canceled
298                )
299                | (
300                    SessionStatus::Queued,
301                    SessionStatus::Merging | SessionStatus::Review | SessionStatus::AgentReview
302                )
303                | (
304                    SessionStatus::InProgress | SessionStatus::Rebasing,
305                    SessionStatus::Review | SessionStatus::AgentReview | SessionStatus::Question
306                )
307                | (
308                    SessionStatus::Merging,
309                    SessionStatus::Done | SessionStatus::Review | SessionStatus::AgentReview
310                )
311        )
312    }
313}
314
315impl fmt::Display for SessionStatus {
316    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
317        let value = match self {
318            SessionStatus::Draft => "Draft",
319            SessionStatus::InProgress => "InProgress",
320            SessionStatus::Review => "Review",
321            SessionStatus::AgentReview => "AgentReview",
322            SessionStatus::Watching => "Watching",
323            SessionStatus::Question => "Question",
324            SessionStatus::Queued => "Queued",
325            SessionStatus::Rebasing => "Rebasing",
326            SessionStatus::Merging => "Merging",
327            SessionStatus::Merged => "Merged",
328            SessionStatus::Done => "Done",
329            SessionStatus::Canceled => "Canceled",
330        };
331
332        formatter.write_str(value)
333    }
334}
335
336impl FromStr for SessionStatus {
337    type Err = String;
338
339    fn from_str(value: &str) -> Result<Self, Self::Err> {
340        match value {
341            "Draft" => Ok(SessionStatus::Draft),
342            "InProgress" | "Committing" => Ok(SessionStatus::InProgress),
343            "Review" => Ok(SessionStatus::Review),
344            "AgentReview" => Ok(SessionStatus::AgentReview),
345            "Watching" => Ok(SessionStatus::Watching),
346            "Question" => Ok(SessionStatus::Question),
347            "Queued" => Ok(SessionStatus::Queued),
348            "Rebasing" => Ok(SessionStatus::Rebasing),
349            "Merging" => Ok(SessionStatus::Merging),
350            "Merged" => Ok(SessionStatus::Merged),
351            "Done" => Ok(SessionStatus::Done),
352            "Canceled" => Ok(SessionStatus::Canceled),
353            _ => Err(format!("Unknown status: {value}")),
354        }
355    }
356}
357
358/// Complete session-scoped execution settings returned by the API.
359#[derive(Clone, Debug, Eq, PartialEq)]
360pub struct SessionSettings {
361    /// Agent provider and model selected for this session.
362    pub agent: AgentSelection,
363    /// Base branch used to create the session.
364    pub base_branch: String,
365    /// Whether the session uses deferred draft materialization.
366    pub is_draft: bool,
367    /// Immediate parent session for a stacked session.
368    pub parent_session_id: Option<SessionId>,
369    /// Provider permission mode used for future turns.
370    pub permission_mode: PermissionMode,
371    /// Owning project identifier.
372    pub project_id: i64,
373    /// Session-scoped reasoning level.
374    pub reasoning_level: ReasoningLevel,
375    /// Session-scoped response style.
376    pub response_style: ResponseStyle,
377    /// Session-scoped response-speed preference.
378    pub speed_mode: SpeedMode,
379}
380
381/// Persisted forge linkage for one session.
382#[derive(Clone, Debug, Eq, PartialEq)]
383pub struct ReviewRequest {
384    /// Unix timestamp of the most recent successful refresh.
385    pub last_refreshed_at: i64,
386    /// Normalized remote summary captured at `last_refreshed_at`.
387    pub summary: ReviewRequestSummary,
388}
389
390/// Complete persisted session aggregate returned by the programmatic API.
391#[derive(Clone, Debug, Eq, PartialEq)]
392pub struct Session {
393    /// Session creation timestamp in Unix seconds.
394    pub created_at: i64,
395    /// Staged draft prompt that has not entered the durable transcript.
396    pub draft_prompt: Option<String>,
397    /// Stable session identifier.
398    pub id: SessionId,
399    /// Ordered durable transcript messages.
400    pub messages: Vec<SessionMessage>,
401    /// Published upstream branch reference, when present.
402    pub published_upstream_ref: Option<String>,
403    /// Structured clarification questions waiting for answers.
404    pub questions: Vec<QuestionItem>,
405    /// Chat messages waiting behind the active turn or queued branch action.
406    pub queued_messages: Vec<String>,
407    /// Persisted review-request linkage, when present.
408    pub review_request: Option<ReviewRequest>,
409    /// Complete session-scoped execution settings.
410    pub settings: SessionSettings,
411    /// Current lifecycle status.
412    pub status: SessionStatus,
413    /// Optional user-visible session title.
414    pub title: Option<String>,
415    /// Last update timestamp in Unix seconds.
416    pub updated_at: i64,
417}
418
419impl Session {
420    /// Returns the shared local environment owned by this session.
421    ///
422    /// Identity exists before workspace preparation and survives cleanup;
423    /// it does not imply that the workspace is available for execution.
424    pub fn env_id(&self) -> EnvId {
425        EnvId::SessionWorktree(self.id.clone())
426    }
427}
428
429/// Converts Unix timestamp seconds to a day key after applying a UTC offset.
430pub fn activity_day_key_with_offset(timestamp_seconds: i64, utc_offset_seconds: i64) -> i64 {
431    timestamp_seconds
432        .saturating_add(utc_offset_seconds)
433        .div_euclid(SECONDS_PER_DAY)
434}
435
436const SESSION_BRANCH_PREFIX: &str = "wt/";
437
438/// Number of seconds in one activity-calendar day.
439const SECONDS_PER_DAY: i64 = 86_400;
440
441#[cfg(test)]
442#[path = "model_test.rs"]
443mod tests;