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