1use std::borrow::Borrow;
4use std::fmt;
5use std::ops::Deref;
6use std::path::Path;
7use std::str::FromStr;
8use std::sync::Arc;
9
10use ag_agent::{AgentSelection, ReasoningLevel};
11pub use ag_agent::{PermissionMode, ResponseStyle, SpeedMode};
12pub use ag_forge::{ForgeKind, ReviewRequestState, ReviewRequestSummary};
13use ag_protocol::QuestionItem;
14use serde::de::{self, Deserializer};
15use serde::ser::Serializer;
16use serde::{Deserialize, Serialize};
17
18use crate::SessionMessage;
19
20const SESSION_BRANCH_PREFIX: &str = "wt/";
21
22pub fn session_branch(session_id: &str) -> String {
24 let len = session_id.len().min(8);
25
26 format!("{SESSION_BRANCH_PREFIX}{}", &session_id[..len])
27}
28
29const SECONDS_PER_DAY: i64 = 86_400;
31
32#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
38pub struct SessionId(Arc<str>);
39
40impl SessionId {
41 pub fn as_str(&self) -> &str {
43 self.0.as_ref()
44 }
45}
46
47impl AsRef<str> for SessionId {
48 fn as_ref(&self) -> &str {
49 self.as_str()
50 }
51}
52
53impl AsRef<Path> for SessionId {
54 fn as_ref(&self) -> &Path {
55 Path::new(self.as_str())
56 }
57}
58
59impl Borrow<str> for SessionId {
60 fn borrow(&self) -> &str {
61 self.as_str()
62 }
63}
64
65impl Deref for SessionId {
66 type Target = str;
67
68 fn deref(&self) -> &Self::Target {
69 self.as_str()
70 }
71}
72
73impl fmt::Display for SessionId {
74 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
75 formatter.write_str(self.as_str())
76 }
77}
78
79impl From<&str> for SessionId {
80 fn from(value: &str) -> Self {
81 Self(Arc::<str>::from(value))
82 }
83}
84
85impl From<String> for SessionId {
86 fn from(value: String) -> Self {
87 Self(Arc::<str>::from(value))
88 }
89}
90
91impl From<Arc<str>> for SessionId {
92 fn from(value: Arc<str>) -> Self {
93 Self(value)
94 }
95}
96
97impl From<SessionId> for String {
98 fn from(value: SessionId) -> Self {
99 value.as_str().to_string()
100 }
101}
102
103impl PartialEq<str> for SessionId {
104 fn eq(&self, other: &str) -> bool {
105 self.as_str() == other
106 }
107}
108
109impl PartialEq<&str> for SessionId {
110 fn eq(&self, other: &&str) -> bool {
111 self.as_str() == *other
112 }
113}
114
115impl PartialEq<String> for SessionId {
116 fn eq(&self, other: &String) -> bool {
117 self.as_str() == other
118 }
119}
120
121impl PartialEq<&String> for SessionId {
122 fn eq(&self, other: &&String) -> bool {
123 self.as_str() == other.as_str()
124 }
125}
126
127impl Serialize for SessionId {
128 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
129 where
130 S: Serializer,
131 {
132 serializer.serialize_str(self.as_str())
133 }
134}
135
136impl<'de> Deserialize<'de> for SessionId {
137 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
138 where
139 D: Deserializer<'de>,
140 {
141 String::deserialize(deserializer)
142 .map(Self::from)
143 .map_err(de::Error::custom)
144 }
145}
146
147#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
155pub enum SessionRole {
156 #[default]
158 Worker,
159 OrchestrationWorker,
162 OrchestrationResearcher,
165 Orchestrator,
167}
168
169impl SessionRole {
170 pub fn owns_branch_changes(self) -> bool {
176 matches!(self, SessionRole::Worker | SessionRole::OrchestrationWorker)
177 }
178
179 pub fn tracks_worktree_changes(self) -> bool {
184 !matches!(self, SessionRole::Orchestrator)
185 }
186
187 pub fn accepts_user_turns(self) -> bool {
190 !self.is_managed()
191 }
192
193 pub fn is_managed(self) -> bool {
195 matches!(
196 self,
197 SessionRole::OrchestrationWorker | SessionRole::OrchestrationResearcher
198 )
199 }
200}
201
202impl fmt::Display for SessionRole {
203 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
204 let value = match self {
205 SessionRole::Worker => "Worker",
206 SessionRole::OrchestrationWorker => "OrchestrationWorker",
207 SessionRole::OrchestrationResearcher => "OrchestrationResearcher",
208 SessionRole::Orchestrator => "Orchestrator",
209 };
210
211 formatter.write_str(value)
212 }
213}
214
215impl FromStr for SessionRole {
216 type Err = String;
217
218 fn from_str(value: &str) -> Result<Self, Self::Err> {
219 match value {
220 "Worker" => Ok(SessionRole::Worker),
221 "OrchestrationWorker" => Ok(SessionRole::OrchestrationWorker),
222 "OrchestrationResearcher" => Ok(SessionRole::OrchestrationResearcher),
223 "Orchestrator" => Ok(SessionRole::Orchestrator),
224 _ => Err(format!("Unknown role: {value}")),
225 }
226 }
227}
228
229#[derive(Clone, Copy, Debug, Eq, PartialEq)]
231pub enum SessionStatus {
232 Draft,
234 InProgress,
236 Review,
238 AgentReview,
240 Question,
242 Queued,
244 Rebasing,
246 Merging,
248 Merged,
250 Done,
252 Canceled,
254}
255
256impl SessionStatus {
257 pub const ALL: [SessionStatus; 11] = [
259 SessionStatus::Draft,
260 SessionStatus::InProgress,
261 SessionStatus::Review,
262 SessionStatus::AgentReview,
263 SessionStatus::Question,
264 SessionStatus::Queued,
265 SessionStatus::Rebasing,
266 SessionStatus::Merging,
267 SessionStatus::Merged,
268 SessionStatus::Done,
269 SessionStatus::Canceled,
270 ];
271
272 pub fn allows_chat_composer(self) -> bool {
274 self.allows_session_actions()
275 || matches!(self, SessionStatus::InProgress | SessionStatus::Rebasing)
276 }
277
278 pub fn allows_session_actions(self) -> bool {
280 self.allows_review_actions()
281 || matches!(self, SessionStatus::Draft | SessionStatus::Question)
282 }
283
284 pub fn allows_diff_view(self) -> bool {
286 self.allows_review_actions() || self.is_read_only()
287 }
288
289 pub fn allows_rebase_action(self) -> bool {
291 self.allows_review_actions() || self == SessionStatus::InProgress
292 }
293
294 pub fn allows_review_actions(self) -> bool {
296 matches!(self, SessionStatus::Review | SessionStatus::AgentReview)
297 }
298
299 pub fn allows_terminal_continuation(self) -> bool {
301 matches!(self, SessionStatus::Done | SessionStatus::Canceled)
302 }
303
304 pub fn is_read_only(self) -> bool {
306 matches!(self, SessionStatus::Merged)
307 }
308
309 pub fn allows_stacked_child_start(self) -> bool {
311 self.allows_review_actions()
312 }
313
314 pub fn is_stack_branch_mutating(self) -> bool {
316 matches!(
317 self,
318 SessionStatus::InProgress
319 | SessionStatus::Question
320 | SessionStatus::Queued
321 | SessionStatus::Rebasing
322 | SessionStatus::Merging
323 | SessionStatus::Merged
324 )
325 }
326
327 pub fn can_transition_to(self, next: SessionStatus) -> bool {
329 if self == next {
330 return true;
331 }
332 if self == SessionStatus::Merged {
333 return next == SessionStatus::Done;
334 }
335
336 matches!(
337 (self, next),
338 (
339 SessionStatus::Draft,
340 SessionStatus::InProgress | SessionStatus::Canceled
341 ) | (
342 SessionStatus::Draft | SessionStatus::InProgress,
343 SessionStatus::Rebasing
344 ) | (
345 SessionStatus::InProgress
346 | SessionStatus::Queued
347 | SessionStatus::Rebasing
348 | SessionStatus::Merging,
349 SessionStatus::Canceled
350 ) | (SessionStatus::Review, SessionStatus::AgentReview)
351 | (SessionStatus::AgentReview, SessionStatus::Review)
352 | (
353 SessionStatus::Review | SessionStatus::AgentReview,
354 SessionStatus::Merged | SessionStatus::Done
355 )
356 | (
357 SessionStatus::Review | SessionStatus::AgentReview | SessionStatus::Question,
358 SessionStatus::InProgress
359 | SessionStatus::Queued
360 | SessionStatus::Rebasing
361 | SessionStatus::Merging
362 | SessionStatus::Canceled
363 )
364 | (
365 SessionStatus::Queued,
366 SessionStatus::Merging | SessionStatus::Review | SessionStatus::AgentReview
367 )
368 | (
369 SessionStatus::InProgress | SessionStatus::Rebasing,
370 SessionStatus::Review | SessionStatus::AgentReview | SessionStatus::Question
371 )
372 | (
373 SessionStatus::Merging,
374 SessionStatus::Done | SessionStatus::Review | SessionStatus::AgentReview
375 )
376 )
377 }
378}
379
380impl fmt::Display for SessionStatus {
381 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
382 let value = match self {
383 SessionStatus::Draft => "Draft",
384 SessionStatus::InProgress => "InProgress",
385 SessionStatus::Review => "Review",
386 SessionStatus::AgentReview => "AgentReview",
387 SessionStatus::Question => "Question",
388 SessionStatus::Queued => "Queued",
389 SessionStatus::Rebasing => "Rebasing",
390 SessionStatus::Merging => "Merging",
391 SessionStatus::Merged => "Merged",
392 SessionStatus::Done => "Done",
393 SessionStatus::Canceled => "Canceled",
394 };
395
396 formatter.write_str(value)
397 }
398}
399
400impl FromStr for SessionStatus {
401 type Err = String;
402
403 fn from_str(value: &str) -> Result<Self, Self::Err> {
404 match value {
405 "Draft" => Ok(SessionStatus::Draft),
406 "InProgress" | "Committing" => Ok(SessionStatus::InProgress),
407 "Review" => Ok(SessionStatus::Review),
408 "AgentReview" => Ok(SessionStatus::AgentReview),
409 "Question" => Ok(SessionStatus::Question),
410 "Queued" => Ok(SessionStatus::Queued),
411 "Rebasing" => Ok(SessionStatus::Rebasing),
412 "Merging" => Ok(SessionStatus::Merging),
413 "Merged" => Ok(SessionStatus::Merged),
414 "Done" => Ok(SessionStatus::Done),
415 "Canceled" => Ok(SessionStatus::Canceled),
416 _ => Err(format!("Unknown status: {value}")),
417 }
418 }
419}
420
421#[derive(Clone, Debug, Eq, PartialEq)]
423pub struct SessionSettings {
424 pub agent: AgentSelection,
426 pub base_branch: String,
428 pub is_draft: bool,
430 pub parent_session_id: Option<SessionId>,
432 pub permission_mode: PermissionMode,
434 pub personality_id: Option<String>,
436 pub project_id: i64,
438 pub reasoning_level: ReasoningLevel,
440 pub response_style: ResponseStyle,
442 pub role: SessionRole,
444 pub speed_mode: SpeedMode,
446}
447
448#[derive(Clone, Debug, Eq, PartialEq)]
450pub struct ReviewRequest {
451 pub last_refreshed_at: i64,
453 pub summary: ReviewRequestSummary,
455}
456
457#[derive(Clone, Debug, Eq, PartialEq)]
459pub struct Session {
460 pub created_at: i64,
462 pub draft_prompt: Option<String>,
464 pub id: SessionId,
466 pub messages: Vec<SessionMessage>,
468 pub published_upstream_ref: Option<String>,
470 pub questions: Vec<QuestionItem>,
472 pub queued_messages: Vec<String>,
474 pub review_request: Option<ReviewRequest>,
476 pub settings: SessionSettings,
478 pub status: SessionStatus,
480 pub title: Option<String>,
482 pub updated_at: i64,
484}
485
486pub fn activity_day_key_with_offset(timestamp_seconds: i64, utc_offset_seconds: i64) -> i64 {
488 timestamp_seconds
489 .saturating_add(utc_offset_seconds)
490 .div_euclid(SECONDS_PER_DAY)
491}
492
493#[cfg(test)]
494mod tests {
495 use super::*;
496
497 #[test]
498 fn test_session_branch_uses_first_8_chars() {
499 let session_id = "a1b2c3d4-e5f6-7890-abcd-ef1234567890";
501
502 let branch = session_branch(session_id);
504
505 assert_eq!(branch, "wt/a1b2c3d4");
507 }
508
509 #[test]
510 fn session_id_round_trips_json() {
511 let session_id = SessionId::from("session-1");
513
514 let serialized = serde_json::to_string(&session_id).expect("id should serialize");
516 let deserialized =
517 serde_json::from_str::<SessionId>(&serialized).expect("id should deserialize");
518
519 assert_eq!(deserialized, session_id);
521 assert_eq!(deserialized.as_str(), "session-1");
522 assert_eq!(AsRef::<Path>::as_ref(&deserialized), Path::new("session-1"));
523 }
524
525 #[test]
526 fn session_id_supports_owned_conversions_and_comparisons() {
527 let source = Arc::<str>::from("session-1");
529 let expected = "session-1".to_string();
530
531 let session_id = SessionId::from(source);
533 let owned = String::from(session_id.clone());
534
535 assert_eq!(session_id, expected);
537 assert_eq!(session_id, &expected);
538 assert_eq!(owned, expected);
539 }
540
541 #[test]
542 fn session_status_round_trips_persisted_values() {
543 let statuses = SessionStatus::ALL;
545
546 let round_tripped = statuses.map(|status| {
548 status
549 .to_string()
550 .parse::<SessionStatus>()
551 .expect("status should parse")
552 });
553
554 assert_eq!(round_tripped, statuses);
556 assert_eq!(
557 "Committing"
558 .parse::<SessionStatus>()
559 .expect("legacy status should parse"),
560 SessionStatus::InProgress
561 );
562 assert!("Unknown".parse::<SessionStatus>().is_err());
563 }
564
565 #[test]
566 fn session_role_round_trips_persisted_values() {
567 let roles = [
569 SessionRole::Worker,
570 SessionRole::OrchestrationWorker,
571 SessionRole::OrchestrationResearcher,
572 SessionRole::Orchestrator,
573 ];
574
575 let round_tripped = roles.map(|role| {
577 role.to_string()
578 .parse::<SessionRole>()
579 .expect("role should parse")
580 });
581
582 assert_eq!(round_tripped, roles);
584 assert_eq!(SessionRole::default(), SessionRole::Worker);
585 assert!("Unknown".parse::<SessionRole>().is_err());
586 }
587
588 #[test]
589 fn branch_ownership_and_tracking_follow_session_role() {
590 assert!(SessionRole::Worker.owns_branch_changes());
592 assert!(SessionRole::OrchestrationWorker.owns_branch_changes());
593 assert!(!SessionRole::OrchestrationResearcher.owns_branch_changes());
594 assert!(!SessionRole::Orchestrator.owns_branch_changes());
595 assert!(SessionRole::Worker.tracks_worktree_changes());
596 assert!(SessionRole::OrchestrationResearcher.tracks_worktree_changes());
597 assert!(!SessionRole::Orchestrator.tracks_worktree_changes());
598 assert!(SessionRole::Worker.accepts_user_turns());
599 assert!(!SessionRole::OrchestrationWorker.accepts_user_turns());
600 assert!(!SessionRole::OrchestrationResearcher.accepts_user_turns());
601 assert!(SessionRole::OrchestrationWorker.is_managed());
602 assert!(SessionRole::OrchestrationResearcher.is_managed());
603 }
604
605 #[test]
606 fn merged_status_only_transitions_to_done() {
607 let status = SessionStatus::Merged;
609
610 assert!(status.can_transition_to(SessionStatus::Merged));
612 assert!(status.can_transition_to(SessionStatus::Done));
613 assert!(!status.can_transition_to(SessionStatus::Review));
614 }
615
616 #[test]
617 fn active_branch_work_statuses_can_transition_to_canceled() {
618 let statuses = [
620 SessionStatus::Question,
621 SessionStatus::Queued,
622 SessionStatus::Rebasing,
623 SessionStatus::Merging,
624 ];
625
626 let cancellation_transitions =
628 statuses.map(|status| status.can_transition_to(SessionStatus::Canceled));
629
630 assert_eq!(cancellation_transitions, [true; 4]);
632 }
633
634 #[test]
635 fn terminal_continuation_is_available_for_done_and_canceled_sessions() {
636 let statuses = SessionStatus::ALL;
638
639 let continuation_statuses = statuses
641 .into_iter()
642 .filter(|status| status.allows_terminal_continuation())
643 .collect::<Vec<_>>();
644
645 assert_eq!(
647 continuation_statuses,
648 vec![SessionStatus::Done, SessionStatus::Canceled]
649 );
650 }
651
652 #[test]
653 fn activity_day_key_applies_offsets() {
654 assert_eq!(activity_day_key_with_offset(86_399, 1), 1);
656 assert_eq!(activity_day_key_with_offset(0, -1), -1);
657 }
658}