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
//! Cooperative cancellation for a run.
//!
//! A [`Cancel`] is a cloneable flag plus a wakeup. The caller (a CLI signal handler, the
//! dashboard) sets it; the agent checks it at its own boundaries — before each provider
//! request, before each tool call, and between iterations — and returns
//! [`Error::Cancelled`](crate::Error::Cancelled) when it sees the flag.
//!
//! It is cooperative on purpose: the run stops at the next check point rather than being
//! aborted mid-write, so a cancelled run never leaves half-written records behind. What
//! has already been written (the user message, any completed tool results) stays in the
//! session, and the next run repairs an unanswered tool call.
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use tokio::sync::Notify;
#[derive(Clone, Debug, Default)]
pub struct Cancel {
inner: Arc<Inner>,
}
#[derive(Debug, Default)]
struct Inner {
flag: AtomicBool,
notify: Notify,
}
impl Cancel {
pub fn new() -> Self {
Self::default()
}
/// Request cancellation. Calling it more than once, or after the run finished, is
/// harmless.
pub fn cancel(&self) {
self.inner.flag.store(true, Ordering::SeqCst);
self.inner.notify.notify_waiters();
}
pub fn is_cancelled(&self) -> bool {
self.inner.flag.load(Ordering::SeqCst)
}
/// Resolves as soon as [`cancel`](Self::cancel) has been called; immediately if it
/// already was, and never if it is not.
pub async fn cancelled(&self) {
// Registered before the check: a `cancel` between the two cannot be missed.
let notified = self.inner.notify.notified();
if self.is_cancelled() {
return;
}
notified.await;
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::time::Duration;
#[test]
fn starts_uncancelled_and_latches() {
let c = Cancel::new();
assert!(!c.is_cancelled());
c.cancel();
assert!(c.is_cancelled());
c.cancel();
assert!(c.is_cancelled());
}
#[test]
fn clones_share_one_flag() {
let a = Cancel::new();
let b = a.clone();
b.cancel();
assert!(a.is_cancelled());
}
#[tokio::test]
async fn cancelled_wakes_a_waiter() {
let c = Cancel::new();
let woken = {
let c = c.clone();
tokio::spawn(async move { c.cancelled().await })
};
tokio::time::sleep(Duration::from_millis(20)).await;
assert!(!woken.is_finished());
c.cancel();
tokio::time::timeout(Duration::from_secs(1), woken)
.await
.expect("waiter should wake")
.unwrap();
}
#[tokio::test]
async fn cancelled_returns_at_once_when_already_set() {
let c = Cancel::new();
c.cancel();
tokio::time::timeout(Duration::from_millis(200), c.cancelled())
.await
.expect("an already-cancelled token must not wait");
}
}