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::{AgentModel, 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 Agentty's merge queue, or its linked pull
159    /// request is waiting in the forge's merge queue.
160    Queued,
161    /// The session branch is being rebased.
162    Rebasing,
163    /// The session branch is being merged.
164    Merging,
165    /// A remote merge awaits local target-branch synchronization.
166    Merged,
167    /// The session completed successfully.
168    Done,
169    /// The session was canceled before completion.
170    Canceled,
171}
172
173impl SessionStatus {
174    /// Ordered list of all session statuses.
175    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    /// Returns whether this status permits opening the chat composer.
191    pub fn allows_chat_composer(self) -> bool {
192        self.allows_session_actions()
193            || matches!(self, SessionStatus::InProgress | SessionStatus::Rebasing)
194    }
195
196    /// Returns whether this status permits idle session actions.
197    pub fn allows_session_actions(self) -> bool {
198        self.allows_review_actions()
199            || matches!(self, SessionStatus::Draft | SessionStatus::Question)
200    }
201
202    /// Returns whether this status permits opening the session diff.
203    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    /// Returns whether this status permits starting or queueing session sync.
211    pub fn allows_rebase_action(self) -> bool {
212        self.allows_review_actions() || self == SessionStatus::InProgress
213    }
214
215    /// Returns whether this status keeps review actions enabled.
216    ///
217    /// `Watching` is a review-ready state: it adds automatic review-request
218    /// follow-up without removing any manual review action.
219    pub fn allows_review_actions(self) -> bool {
220        matches!(
221            self,
222            SessionStatus::Review | SessionStatus::AgentReview | SessionStatus::Watching
223        )
224    }
225
226    /// Returns whether this status can seed a follow-on continuation session.
227    pub fn allows_terminal_continuation(self) -> bool {
228        matches!(self, SessionStatus::Done | SessionStatus::Canceled)
229    }
230
231    /// Returns whether this lifecycle state permits only local inspection.
232    pub fn is_read_only(self) -> bool {
233        matches!(self, SessionStatus::Merged)
234    }
235
236    /// Returns whether a transition to `next` is valid.
237    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/// Complete session-scoped execution settings returned by the API.
346#[derive(Clone, Debug, Eq, PartialEq)]
347pub struct SessionSettings {
348    /// Agent provider and model selected for this session.
349    pub agent: AgentSelection,
350    /// Base branch used to create the session.
351    pub base_branch: String,
352    /// Whether the session uses deferred draft materialization.
353    pub is_draft: bool,
354    /// Owning project identifier.
355    pub project_id: i64,
356    /// Session-scoped reasoning level.
357    pub reasoning_level: ReasoningLevel,
358    /// Session-scoped response style.
359    pub response_style: ResponseStyle,
360    /// Session-scoped response-speed preference.
361    pub speed_mode: SpeedMode,
362}
363
364/// Persisted forge linkage for one session.
365#[derive(Clone, Debug, Eq, PartialEq)]
366pub struct ReviewRequest {
367    /// Unix timestamp of the most recent successful refresh.
368    pub last_refreshed_at: i64,
369    /// Normalized remote summary captured at `last_refreshed_at`.
370    pub summary: ReviewRequestSummary,
371}
372
373/// Complete persisted session aggregate returned by the programmatic API.
374#[derive(Clone, Debug, Eq, PartialEq)]
375pub struct Session {
376    /// Session creation timestamp in Unix seconds.
377    pub created_at: i64,
378    /// Staged draft prompt that has not entered the durable transcript.
379    pub draft_prompt: Option<String>,
380    /// Latest focused review of the session's changes, while the host shows
381    /// it. `None` when there is none to show, including while a review runs:
382    /// `progress` then describes it.
383    pub focused_review: Option<SessionFocusedReview>,
384    /// The session's latest graph proposal and, once approved, its graph's
385    /// progress, as the host summarizes them beside the chat. `None` when
386    /// the session has no proposal.
387    pub graph: Option<crate::SessionGraphSummary>,
388    /// Opaque key of the graph work that asked `questions`, its pending
389    /// graph proposal version or one of its graph node executions, or `None`
390    /// when the session's own turn asked them. Other graph work asking the
391    /// same questions has another key. The key identifies no proposal or
392    /// node; a frontend echoes it in
393    /// [`AnswerQuestionsRequest::graph_question_target`](crate::AnswerQuestionsRequest)
394    /// so its answers reach only the work they were entered for. The host
395    /// reports graph questions only while the turn asks none, and a chat
396    /// message still answers them, so the session's status need not be
397    /// [`SessionStatus::Question`].
398    pub graph_question_target: Option<String>,
399    /// Stable session identifier.
400    pub id: SessionId,
401    /// Ordered durable transcript messages.
402    pub messages: Vec<SessionMessage>,
403    /// Live line describing the session's current work, such as
404    /// `Working... Reading files`, while it works or waits. Further lines
405    /// add detail. `None` when the host shows no such line.
406    pub progress: Option<String>,
407    /// Published upstream branch reference, when present.
408    pub published_upstream_ref: Option<String>,
409    /// Structured clarification questions waiting for answers, which
410    /// [`crate::SessionService::answer_questions`] answers.
411    pub questions: Vec<QuestionItem>,
412    /// Workflow actions waiting behind the active turn, such as a queued
413    /// sync, publish, or settings change, as display labels in the order
414    /// they run. Chat messages wait in `queued_messages`.
415    pub queued_actions: Vec<String>,
416    /// Chat messages waiting behind the active turn or queued branch action.
417    pub queued_messages: Vec<String>,
418    /// Persisted review-request linkage, when present.
419    pub review_request: Option<ReviewRequest>,
420    /// Complete session-scoped execution settings.
421    pub settings: SessionSettings,
422    /// Current lifecycle status.
423    pub status: SessionStatus,
424    /// Optional user-visible session title.
425    pub title: Option<String>,
426    /// Last update timestamp in Unix seconds.
427    pub updated_at: i64,
428}
429
430impl Session {
431    /// Returns the shared local environment owned by this session.
432    ///
433    /// Identity exists before workspace preparation and survives cleanup;
434    /// it does not imply that the workspace is available for execution.
435    pub fn env_id(&self) -> EnvId {
436        EnvId::SessionWorktree(self.id.clone())
437    }
438}
439
440/// Outcome of a session's latest focused review.
441#[derive(Clone, Debug, Eq, PartialEq)]
442pub enum SessionFocusedReview {
443    /// The review finished; `text` is its Markdown.
444    Ready {
445        /// Review findings and suggestions as Markdown.
446        text: String,
447    },
448    /// The review could not be produced; `message` says why, ready to
449    /// display.
450    Failed {
451        /// Plain-text failure description.
452        message: String,
453    },
454}
455
456/// Listing entry for one session, without its transcript or settings.
457#[derive(Clone, Debug, Eq, PartialEq)]
458pub struct SessionSummary {
459    /// Stable session identifier.
460    pub id: SessionId,
461    /// Current lifecycle status.
462    pub status: SessionStatus,
463    /// Optional user-visible session title.
464    pub title: Option<String>,
465    /// Last update timestamp in Unix seconds.
466    pub updated_at: i64,
467}
468
469/// Listing entry for one session, with the figures a dense session list
470/// shows when the host provides them.
471#[derive(Clone, Debug, Eq, PartialEq)]
472pub struct SessionListEntry {
473    /// Diff size, model, timer, and review state, or `None` when the host
474    /// lists only summaries.
475    pub stats: Option<SessionListStats>,
476    /// Identity, status, title, and update time.
477    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/// Figures a dense session list shows beside one session.
490#[derive(Clone, Debug, Eq, PartialEq)]
491pub struct SessionListStats {
492    /// Lines the session's diff adds.
493    pub added_lines: u64,
494    /// Commits the session branch is ahead of and behind its base branch,
495    /// in that order, as of the host's latest check; `None` before one.
496    pub base_ahead_behind: Option<(u32, u32)>,
497    /// Lines the session's diff removes.
498    pub deleted_lines: u64,
499    /// Whether merging the session branch into its base would conflict, as
500    /// of the host's latest check.
501    pub has_merge_conflict: bool,
502    /// Start of the current active-work interval in Unix seconds, while the
503    /// session accumulates `InProgress` time.
504    pub in_progress_started_at: Option<i64>,
505    /// Active-work seconds completed before the current interval.
506    pub in_progress_total_seconds: i64,
507    /// Whether the session branch was published to an upstream branch.
508    pub is_published: bool,
509    /// Model the session runs on.
510    pub model: AgentModel,
511    /// Reasoning level of the session's next turn.
512    pub reasoning_level: ReasoningLevel,
513    /// Linked review request as of the latest forge refresh.
514    pub review_request: Option<ReviewRequestSummary>,
515    /// Host size bucket of the diff, such as `XS` or `XXL`.
516    pub size_label: String,
517    /// Commits the session branch is ahead of and behind the upstream
518    /// branch it tracks, in that order, as of the host's latest fetch;
519    /// `None` when it tracks none or before the host compared them.
520    pub upstream_ahead_behind: Option<(u32, u32)>,
521}
522
523/// Converts Unix timestamp seconds to a day key after applying a UTC offset.
524pub 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
532/// Number of seconds in one activity-calendar day.
533const SECONDS_PER_DAY: i64 = 86_400;
534
535#[cfg(test)]
536#[path = "model_test.rs"]
537mod tests;