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::{AgentSelection, 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, Default, Eq, PartialEq)]
150pub enum SessionRole {
151 #[default]
153 Worker,
154 OrchestrationWorker,
157 OrchestrationResearcher,
160 Orchestrator,
162}
163
164impl SessionRole {
165 pub fn owns_branch_changes(self) -> bool {
171 matches!(self, SessionRole::Worker | SessionRole::OrchestrationWorker)
172 }
173
174 pub fn tracks_worktree_changes(self) -> bool {
179 !matches!(self, SessionRole::Orchestrator)
180 }
181
182 pub fn accepts_user_turns(self) -> bool {
185 !self.is_managed()
186 }
187
188 pub fn is_managed(self) -> bool {
190 matches!(
191 self,
192 SessionRole::OrchestrationWorker | SessionRole::OrchestrationResearcher
193 )
194 }
195}
196
197impl fmt::Display for SessionRole {
198 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
199 let value = match self {
200 SessionRole::Worker => "Worker",
201 SessionRole::OrchestrationWorker => "OrchestrationWorker",
202 SessionRole::OrchestrationResearcher => "OrchestrationResearcher",
203 SessionRole::Orchestrator => "Orchestrator",
204 };
205
206 formatter.write_str(value)
207 }
208}
209
210impl FromStr for SessionRole {
211 type Err = String;
212
213 fn from_str(value: &str) -> Result<Self, Self::Err> {
214 match value {
215 "Worker" => Ok(SessionRole::Worker),
216 "OrchestrationWorker" => Ok(SessionRole::OrchestrationWorker),
217 "OrchestrationResearcher" => Ok(SessionRole::OrchestrationResearcher),
218 "Orchestrator" => Ok(SessionRole::Orchestrator),
219 _ => Err(format!("Unknown role: {value}")),
220 }
221 }
222}
223
224#[derive(Clone, Copy, Debug, Eq, PartialEq)]
226pub enum SessionStatus {
227 Draft,
229 InProgress,
231 Review,
233 AgentReview,
235 Question,
237 Queued,
239 Rebasing,
241 Merging,
243 Merged,
245 Done,
247 Canceled,
249}
250
251impl SessionStatus {
252 pub const ALL: [SessionStatus; 11] = [
254 SessionStatus::Draft,
255 SessionStatus::InProgress,
256 SessionStatus::Review,
257 SessionStatus::AgentReview,
258 SessionStatus::Question,
259 SessionStatus::Queued,
260 SessionStatus::Rebasing,
261 SessionStatus::Merging,
262 SessionStatus::Merged,
263 SessionStatus::Done,
264 SessionStatus::Canceled,
265 ];
266
267 pub fn allows_chat_composer(self) -> bool {
269 self.allows_session_actions()
270 || matches!(self, SessionStatus::InProgress | SessionStatus::Rebasing)
271 }
272
273 pub fn allows_session_actions(self) -> bool {
275 self.allows_review_actions()
276 || matches!(self, SessionStatus::Draft | SessionStatus::Question)
277 }
278
279 pub fn allows_diff_view(self) -> bool {
281 self.allows_review_actions() || self.is_read_only()
282 }
283
284 pub fn allows_rebase_action(self) -> bool {
286 self.allows_review_actions() || self == SessionStatus::InProgress
287 }
288
289 pub fn allows_review_actions(self) -> bool {
291 matches!(self, SessionStatus::Review | SessionStatus::AgentReview)
292 }
293
294 pub fn allows_terminal_continuation(self) -> bool {
296 matches!(self, SessionStatus::Done | SessionStatus::Canceled)
297 }
298
299 pub fn is_read_only(self) -> bool {
301 matches!(self, SessionStatus::Merged)
302 }
303
304 pub fn allows_stacked_child_start(self) -> bool {
306 self.allows_review_actions()
307 }
308
309 pub fn is_stack_branch_mutating(self) -> bool {
311 matches!(
312 self,
313 SessionStatus::InProgress
314 | SessionStatus::Question
315 | SessionStatus::Queued
316 | SessionStatus::Rebasing
317 | SessionStatus::Merging
318 | SessionStatus::Merged
319 )
320 }
321
322 pub fn can_transition_to(self, next: SessionStatus) -> bool {
324 if self == next {
325 return true;
326 }
327
328 if self == SessionStatus::Merged {
329 return next == SessionStatus::Done;
330 }
331
332 matches!(
333 (self, next),
334 (
335 SessionStatus::Draft,
336 SessionStatus::InProgress | SessionStatus::Canceled
337 ) | (
338 SessionStatus::Draft | SessionStatus::InProgress,
339 SessionStatus::Rebasing
340 ) | (
341 SessionStatus::InProgress
342 | SessionStatus::Queued
343 | SessionStatus::Rebasing
344 | SessionStatus::Merging,
345 SessionStatus::Canceled
346 ) | (SessionStatus::Review, SessionStatus::AgentReview)
347 | (SessionStatus::AgentReview, SessionStatus::Review)
348 | (
349 SessionStatus::Review | SessionStatus::AgentReview,
350 SessionStatus::Merged | SessionStatus::Done
351 )
352 | (
353 SessionStatus::Review | SessionStatus::AgentReview | SessionStatus::Question,
354 SessionStatus::InProgress
355 | SessionStatus::Queued
356 | SessionStatus::Rebasing
357 | SessionStatus::Merging
358 | SessionStatus::Canceled
359 )
360 | (
361 SessionStatus::Queued,
362 SessionStatus::Merging | SessionStatus::Review | SessionStatus::AgentReview
363 )
364 | (
365 SessionStatus::InProgress | SessionStatus::Rebasing,
366 SessionStatus::Review | SessionStatus::AgentReview | SessionStatus::Question
367 )
368 | (
369 SessionStatus::Merging,
370 SessionStatus::Done | SessionStatus::Review | SessionStatus::AgentReview
371 )
372 )
373 }
374}
375
376impl fmt::Display for SessionStatus {
377 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
378 let value = match self {
379 SessionStatus::Draft => "Draft",
380 SessionStatus::InProgress => "InProgress",
381 SessionStatus::Review => "Review",
382 SessionStatus::AgentReview => "AgentReview",
383 SessionStatus::Question => "Question",
384 SessionStatus::Queued => "Queued",
385 SessionStatus::Rebasing => "Rebasing",
386 SessionStatus::Merging => "Merging",
387 SessionStatus::Merged => "Merged",
388 SessionStatus::Done => "Done",
389 SessionStatus::Canceled => "Canceled",
390 };
391
392 formatter.write_str(value)
393 }
394}
395
396impl FromStr for SessionStatus {
397 type Err = String;
398
399 fn from_str(value: &str) -> Result<Self, Self::Err> {
400 match value {
401 "Draft" => Ok(SessionStatus::Draft),
402 "InProgress" | "Committing" => Ok(SessionStatus::InProgress),
403 "Review" => Ok(SessionStatus::Review),
404 "AgentReview" => Ok(SessionStatus::AgentReview),
405 "Question" => Ok(SessionStatus::Question),
406 "Queued" => Ok(SessionStatus::Queued),
407 "Rebasing" => Ok(SessionStatus::Rebasing),
408 "Merging" => Ok(SessionStatus::Merging),
409 "Merged" => Ok(SessionStatus::Merged),
410 "Done" => Ok(SessionStatus::Done),
411 "Canceled" => Ok(SessionStatus::Canceled),
412 _ => Err(format!("Unknown status: {value}")),
413 }
414 }
415}
416
417#[derive(Clone, Debug, Eq, PartialEq)]
419pub struct SessionSettings {
420 pub agent: AgentSelection,
422 pub base_branch: String,
424 pub is_draft: bool,
426 pub parent_session_id: Option<SessionId>,
428 pub permission_mode: PermissionMode,
430 pub personality_id: Option<String>,
432 pub project_id: i64,
434 pub reasoning_level: ReasoningLevel,
436 pub response_style: ResponseStyle,
438 pub role: SessionRole,
440 pub speed_mode: SpeedMode,
442}
443
444#[derive(Clone, Debug, Eq, PartialEq)]
446pub struct ReviewRequest {
447 pub last_refreshed_at: i64,
449 pub summary: ReviewRequestSummary,
451}
452
453#[derive(Clone, Debug, Eq, PartialEq)]
455pub struct Session {
456 pub created_at: i64,
458 pub draft_prompt: Option<String>,
460 pub id: SessionId,
462 pub messages: Vec<SessionMessage>,
464 pub published_upstream_ref: Option<String>,
466 pub questions: Vec<QuestionItem>,
468 pub queued_messages: Vec<String>,
470 pub review_request: Option<ReviewRequest>,
472 pub settings: SessionSettings,
474 pub status: SessionStatus,
476 pub title: Option<String>,
478 pub updated_at: i64,
480}
481
482pub fn activity_day_key_with_offset(timestamp_seconds: i64, utc_offset_seconds: i64) -> i64 {
484 timestamp_seconds
485 .saturating_add(utc_offset_seconds)
486 .div_euclid(SECONDS_PER_DAY)
487}
488
489const SESSION_BRANCH_PREFIX: &str = "wt/";
490
491const SECONDS_PER_DAY: i64 = 86_400;
493
494#[cfg(test)]
495#[path = "model_test.rs"]
496mod tests;