Skip to main content

subspace_core/
task_state.rs

1//! Pure cloud-agent task-state rules: which states keep a task alive, which
2//! end it, which transitions deserve an alert, and how often a watcher polls.
3//! No requests and no GPUI, so dashboards and background watchers share them.
4
5use std::time::Duration;
6
7/// The documented states a task or session can report.
8/// `idle` counts as finished: the agent stopped without more work to do.
9pub const ACTIVE_STATES: &[&str] = &["queued", "in_progress", "waiting_for_user"];
10pub const FINISHED_STATES: &[&str] = &["completed", "failed", "timed_out", "cancelled", "idle"];
11
12/// How often a watcher asks GitHub about its active tasks.
13pub const POLL_INTERVAL: Duration = Duration::from_secs(30);
14/// The slowest poll a watcher backs off to after errors or rate limits.
15pub const MAX_POLL_INTERVAL: Duration = Duration::from_secs(120);
16
17/// True while the task can still change on its own. `waiting_for_user` stays
18/// active because the user can answer and the task continues.
19pub fn is_active(state: &str) -> bool {
20    ACTIVE_STATES.contains(&state)
21}
22
23/// True for the documented end states. An unknown future state is neither
24/// active nor finished, so a watcher keeps showing it without alerting.
25// qual:api
26pub fn is_finished(state: &str) -> bool {
27    FINISHED_STATES.contains(&state)
28}
29
30// qual:api
31pub fn needs_input(state: &str) -> bool {
32    state == "waiting_for_user"
33}
34
35/// What a monitored task's change is worth telling the user about.
36#[derive(Debug, Clone, Copy, PartialEq, Eq)]
37pub enum AlertKind {
38    NeedsInput,
39    Completed,
40    Failed,
41    TimedOut,
42    Cancelled,
43    /// The agent stopped with nothing left to do.
44    Idle,
45}
46
47/// Every state worth an alert, with the alert it raises and the phrase a
48/// toast or a notification reads.
49const ALERTS: &[(&str, AlertKind, &str)] = &[
50    ("waiting_for_user", AlertKind::NeedsInput, "needs input"),
51    ("completed", AlertKind::Completed, "completed"),
52    ("failed", AlertKind::Failed, "failed"),
53    ("timed_out", AlertKind::TimedOut, "timed out"),
54    ("cancelled", AlertKind::Cancelled, "was cancelled"),
55    ("idle", AlertKind::Idle, "went idle"),
56];
57
58impl AlertKind {
59    /// A short phrase for a toast or a notification body.
60    pub fn label(self) -> &'static str {
61        ALERTS
62            .iter()
63            .find(|(_, kind, _)| *kind == self)
64            .map_or("changed", |(_, _, label)| *label)
65    }
66}
67
68/// The alert a state change earns, or `None` when it earns none. Only a task
69/// that was active can alert, so a list refresh of old finished tasks is
70/// silent, and an unknown state never alerts.
71// qual:api
72pub fn alert_for(previous: &str, current: &str) -> Option<AlertKind> {
73    if previous == current || !is_active(previous) {
74        return None;
75    }
76    ALERTS
77        .iter()
78        .find(|(state, _, _)| *state == current)
79        .map(|(_, kind, _)| *kind)
80}
81
82/// The watcher's poll delay: [`POLL_INTERVAL`] while requests succeed,
83/// doubling up to [`MAX_POLL_INTERVAL`] after an error or a rate limit.
84#[derive(Debug, Clone, Copy, PartialEq, Eq)]
85pub struct PollBackoff {
86    interval: Duration,
87}
88
89impl Default for PollBackoff {
90    fn default() -> Self {
91        Self {
92            interval: POLL_INTERVAL,
93        }
94    }
95}
96
97impl PollBackoff {
98    pub fn new() -> Self {
99        Self::default()
100    }
101
102    pub fn interval(&self) -> Duration {
103        self.interval
104    }
105
106    /// Slows the next poll after a failed request.
107    pub fn failed(&mut self) -> Duration {
108        self.interval = (self.interval * 2).min(MAX_POLL_INTERVAL);
109        self.interval
110    }
111
112    /// Returns to the normal interval after a successful request.
113    pub fn succeeded(&mut self) -> Duration {
114        self.interval = POLL_INTERVAL;
115        self.interval
116    }
117}
118
119#[cfg(test)]
120mod tests {
121    use super::{
122        ACTIVE_STATES, AlertKind, FINISHED_STATES, MAX_POLL_INTERVAL, POLL_INTERVAL, PollBackoff,
123        alert_for, is_active, is_finished, needs_input,
124    };
125
126    #[test]
127    fn active_and_finished_states_are_disjoint_and_cover_the_documented_set() {
128        for state in ACTIVE_STATES {
129            assert!(is_active(state), "{state} is active");
130            assert!(!is_finished(state), "{state} is not finished");
131        }
132        for state in FINISHED_STATES {
133            assert!(is_finished(state), "{state} is finished");
134            assert!(!is_active(state), "{state} is not active");
135        }
136        assert!(!is_active("new_state"));
137        assert!(!is_finished("new_state"));
138        assert!(needs_input("waiting_for_user"));
139        assert!(!needs_input("in_progress"));
140    }
141
142    #[test]
143    fn alerts_fire_only_when_an_active_task_reaches_a_reportable_state() {
144        assert_eq!(
145            alert_for("in_progress", "waiting_for_user"),
146            Some(AlertKind::NeedsInput)
147        );
148        assert_eq!(
149            alert_for("waiting_for_user", "completed"),
150            Some(AlertKind::Completed)
151        );
152        assert_eq!(alert_for("queued", "failed"), Some(AlertKind::Failed));
153        assert_eq!(
154            alert_for("in_progress", "timed_out"),
155            Some(AlertKind::TimedOut)
156        );
157        assert_eq!(
158            alert_for("in_progress", "cancelled"),
159            Some(AlertKind::Cancelled)
160        );
161        assert_eq!(alert_for("in_progress", "idle"), Some(AlertKind::Idle));
162        assert_eq!(alert_for("in_progress", "in_progress"), None);
163        assert_eq!(alert_for("queued", "in_progress"), None);
164        assert_eq!(alert_for("completed", "failed"), None);
165        assert_eq!(alert_for("in_progress", "new_state"), None);
166        assert_eq!(AlertKind::NeedsInput.label(), "needs input");
167        assert_eq!(AlertKind::TimedOut.label(), "timed out");
168    }
169
170    #[test]
171    fn backoff_doubles_to_the_cap_and_a_success_resets_it() {
172        let mut backoff = PollBackoff::new();
173        assert_eq!(backoff.interval(), POLL_INTERVAL);
174        assert_eq!(backoff.failed(), POLL_INTERVAL * 2);
175        assert_eq!(backoff.failed(), MAX_POLL_INTERVAL);
176        assert_eq!(backoff.failed(), MAX_POLL_INTERVAL);
177        assert_eq!(backoff.succeeded(), POLL_INTERVAL);
178        assert_eq!(backoff.interval(), POLL_INTERVAL);
179    }
180}