1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
//! Session status tracking for monitoring agent activity.
//!
//! Tracks per-session status (idle, busy, retry) and publishes changes
//! via the event bus. The TUI uses this to display retry countdowns
//! and activity indicators.
use std::collections::HashMap;
use std::sync::Mutex;
use serde::{Deserialize, Serialize};
use crate::event_bus::{EventBus, RuntimeEvent, now_ms};
/// The current status of a session.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type")]
pub enum SessionStatus {
/// Session is idle, waiting for user input.
#[default]
#[serde(rename = "idle")]
Idle,
/// Session is actively processing a request.
#[serde(rename = "busy")]
Busy,
/// Session is waiting to retry after an error.
#[serde(rename = "retry")]
Retry {
/// Which retry attempt this is (1-based).
attempt: u32,
/// Human-readable reason for the retry (e.g. "Rate Limited").
message: String,
/// Unix timestamp in milliseconds when the next retry will occur.
next_retry_ms: u64,
},
}
impl std::fmt::Display for SessionStatus {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Idle => write!(f, "idle"),
Self::Busy => write!(f, "busy"),
Self::Retry {
attempt, message, ..
} => write!(f, "retry (attempt {attempt}: {message})"),
}
}
}
/// Tracks the status of all active sessions.
///
/// Thread-safe via interior `Mutex`. Status changes are published
/// to an optional [`EventBus`].
pub struct SessionStatusTracker {
state: Mutex<HashMap<String, SessionStatus>>,
event_bus: Option<EventBus>,
}
impl SessionStatusTracker {
/// Create a new tracker without event publishing.
pub fn new() -> Self {
Self {
state: Mutex::new(HashMap::new()),
event_bus: None,
}
}
/// Create a new tracker that publishes status changes to the event bus.
pub fn with_event_bus(event_bus: EventBus) -> Self {
Self {
state: Mutex::new(HashMap::new()),
event_bus: Some(event_bus),
}
}
/// Get the current status of a session.
///
/// Returns `SessionStatus::Idle` if the session has no tracked status.
pub fn get(&self, session_id: &str) -> SessionStatus {
self.state
.lock()
.expect("SessionStatusTracker lock poisoned")
.get(session_id)
.cloned()
.unwrap_or_default()
}
/// Set the status of a session.
///
/// Setting `Idle` removes the session from tracking (it's the default).
/// Publishes a `SessionStatusChanged` event if an event bus is configured.
pub fn set(&self, session_id: impl Into<String>, status: SessionStatus) {
let session_id = session_id.into();
let mut state = self
.state
.lock()
.expect("SessionStatusTracker lock poisoned");
match &status {
SessionStatus::Idle => {
state.remove(&session_id);
}
_ => {
state.insert(session_id.clone(), status.clone());
}
}
// Publish event
if let Some(bus) = &self.event_bus {
bus.publish(RuntimeEvent::SessionStatusChanged {
session_id,
status,
timestamp_ms: now_ms(),
});
}
}
/// Mark a session as busy.
pub fn set_busy(&self, session_id: impl Into<String>) {
self.set(session_id, SessionStatus::Busy);
}
/// Mark a session as idle.
pub fn set_idle(&self, session_id: impl Into<String>) {
self.set(session_id, SessionStatus::Idle);
}
/// Mark a session as retrying.
pub fn set_retry(
&self,
session_id: impl Into<String>,
attempt: u32,
message: impl Into<String>,
next_retry_ms: u64,
) {
self.set(
session_id,
SessionStatus::Retry {
attempt,
message: message.into(),
next_retry_ms,
},
);
}
/// Get all tracked sessions and their statuses.
pub fn list(&self) -> HashMap<String, SessionStatus> {
self.state
.lock()
.expect("SessionStatusTracker lock poisoned")
.clone()
}
/// Get the number of tracked (non-idle) sessions.
pub fn active_count(&self) -> usize {
self.state
.lock()
.expect("SessionStatusTracker lock poisoned")
.len()
}
/// Check if any session is currently retrying.
pub fn has_retrying(&self) -> bool {
self.state
.lock()
.expect("SessionStatusTracker lock poisoned")
.values()
.any(|s| matches!(s, SessionStatus::Retry { .. }))
}
}
impl Default for SessionStatusTracker {
fn default() -> Self {
Self::new()
}
}
impl std::fmt::Debug for SessionStatusTracker {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let count = self.active_count();
f.debug_struct("SessionStatusTracker")
.field("active_sessions", &count)
.finish()
}
}
#[cfg(test)]
#[path = "session_status_tests.rs"]
mod tests;