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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
use std::io::Write;
use std::sync::mpsc::{Receiver, RecvTimeoutError};
use std::time::{Duration, Instant};
use seher::sdk::{CancelToken, StreamChunk};
/// Result of [`drain_to_stdout`]. `Limit` carries no payload — the caller already
/// has the [`crate::run_mode`] `ResolvedAgent` whose `provider` is what gets
/// added to the exclude list.
pub enum Outcome {
Done(String),
Limit,
Error(String),
Timeout,
Cancelled,
}
/// Drain a `Receiver<StreamChunk>` to stdout, writing each delta as it arrives.
///
/// `timeout_ms` is the total deadline (in ms) from "now" — it does NOT abort the
/// in-flight worker thread; on timeout, the receiver is dropped and the worker
/// is left to finish in the background. Returns `Outcome::Done` with the
/// concatenated text on success.
#[expect(
clippy::needless_pass_by_value,
reason = "takes ownership of the receiver so it is dropped on return, signaling the worker the consumer is gone"
)]
pub fn drain_to_stdout(
rx: Receiver<StreamChunk>,
timeout_ms: Option<u64>,
cancel: &CancelToken,
) -> Outcome {
// Short poll interval used when there is no deadline — lets cancel checks
// fire even while blocked on recv, instead of waiting for the next chunk.
const CANCEL_POLL: Duration = Duration::from_millis(50);
let stdout = std::io::stdout();
let mut out = stdout.lock();
let mut full = String::new();
let deadline = timeout_ms.map(|t| Instant::now() + Duration::from_millis(t));
loop {
if cancel.is_cancelled() {
return Outcome::Cancelled;
}
let chunk = match deadline {
Some(d) => {
let now = Instant::now();
if now >= d {
return Outcome::Timeout;
}
match rx.recv_timeout(d - now) {
Ok(c) => c,
Err(RecvTimeoutError::Timeout) => return Outcome::Timeout,
// The worker is required to send Done/Limit/Error before dropping
// the sender; an unexpected disconnect is a worker panic / early-drop bug.
Err(RecvTimeoutError::Disconnected) => {
return Outcome::Error(
"pi worker disconnected without a terminal chunk".to_string(),
);
}
}
}
// Without a deadline, use a short timeout so that cancel signals
// are detected promptly rather than waiting for the next chunk.
None => loop {
match rx.recv_timeout(CANCEL_POLL) {
Ok(c) => break c,
Err(RecvTimeoutError::Timeout) => {
if cancel.is_cancelled() {
return Outcome::Cancelled;
}
}
Err(RecvTimeoutError::Disconnected) => {
return Outcome::Error(
"pi worker disconnected without a terminal chunk".to_string(),
);
}
}
},
};
match chunk {
StreamChunk::Delta(d) => {
let _ = out.write_all(d.as_bytes());
let _ = out.flush();
full.push_str(&d);
}
// Session id is metadata — keep stdout clean for piping and surface it on
// stderr so a follow-up turn can resume with `--resume <id>`.
StreamChunk::Session(id) => {
eprintln!("session: {id}");
}
StreamChunk::Done(t) => {
let _ = out.write_all(b"\n");
let _ = out.flush();
return Outcome::Done(if t.is_empty() { full } else { t });
}
StreamChunk::Limit(_) => return Outcome::Limit,
StreamChunk::Error(m) => {
// If cancellation is active, the error was most likely caused
// by the runner aborting due to the cancel signal — report it
// as Cancelled rather than a generic error.
if cancel.is_cancelled() {
return Outcome::Cancelled;
}
return Outcome::Error(m);
}
}
}
}
#[cfg(test)]
#[expect(clippy::unwrap_used, reason = "tests may panic on unexpected fixtures")]
mod tests {
use super::*;
use std::sync::mpsc::channel;
fn no_cancel() -> CancelToken {
CancelToken::new()
}
#[test]
fn done_returns_concatenated_deltas() {
let (tx, rx) = channel();
tx.send(StreamChunk::Delta("ab".to_string())).unwrap();
tx.send(StreamChunk::Delta("cd".to_string())).unwrap();
tx.send(StreamChunk::Done(String::new())).unwrap();
drop(tx);
match drain_to_stdout(rx, None, &no_cancel()) {
Outcome::Done(s) => assert_eq!(s, "abcd"),
other => panic!(
"unexpected outcome: {other:?}",
other = OutcomeDebug(&other)
),
}
}
#[test]
fn done_with_explicit_text_overrides_buffered_deltas() {
let (tx, rx) = channel();
tx.send(StreamChunk::Delta("ignored".to_string())).unwrap();
tx.send(StreamChunk::Done("final".to_string())).unwrap();
drop(tx);
match drain_to_stdout(rx, None, &no_cancel()) {
Outcome::Done(s) => assert_eq!(s, "final"),
other => panic!(
"unexpected outcome: {other:?}",
other = OutcomeDebug(&other)
),
}
}
#[test]
fn limit_returns_limit_outcome() {
use seher::sdk::LimitError;
let (tx, rx) = channel();
tx.send(StreamChunk::Delta("partial".to_string())).unwrap();
tx.send(StreamChunk::Limit(LimitError {
provider: "anthropic".to_string(),
reset_at: None,
}))
.unwrap();
drop(tx);
match drain_to_stdout(rx, None, &no_cancel()) {
Outcome::Limit => {}
other => panic!(
"unexpected outcome: {other:?}",
other = OutcomeDebug(&other)
),
}
}
#[test]
fn error_chunk_returns_error_outcome() {
let (tx, rx) = channel();
tx.send(StreamChunk::Error("boom".to_string())).unwrap();
drop(tx);
match drain_to_stdout(rx, None, &no_cancel()) {
Outcome::Error(m) => assert_eq!(m, "boom"),
other => panic!(
"unexpected outcome: {other:?}",
other = OutcomeDebug(&other)
),
}
}
#[test]
fn disconnected_without_terminal_returns_error() {
// tx is dropped before sending Done/Limit/Error — must NOT be reported as success.
let (tx, rx) = channel::<StreamChunk>();
drop(tx);
match drain_to_stdout(rx, None, &no_cancel()) {
Outcome::Error(m) => assert!(m.contains("disconnected"), "got: {m}"),
other => panic!(
"unexpected outcome: {other:?}",
other = OutcomeDebug(&other)
),
}
}
#[test]
fn disconnected_with_timeout_set_returns_error() {
// Same as above but with a timeout configured — the disconnect path
// through recv_timeout must also classify as Error, not Timeout.
let (tx, rx) = channel::<StreamChunk>();
drop(tx);
match drain_to_stdout(rx, Some(10_000), &no_cancel()) {
Outcome::Error(m) => assert!(m.contains("disconnected"), "got: {m}"),
other => panic!(
"unexpected outcome: {other:?}",
other = OutcomeDebug(&other)
),
}
}
#[test]
fn timeout_fires_when_no_chunk_arrives() {
let (tx, rx) = channel::<StreamChunk>();
// Keep tx alive in scope so the channel doesn't disconnect; otherwise
// we'd get the Error branch instead of Timeout.
match drain_to_stdout(rx, Some(50), &no_cancel()) {
Outcome::Timeout => {}
other => panic!(
"unexpected outcome: {other:?}",
other = OutcomeDebug(&other)
),
}
drop(tx);
}
#[test]
fn cancelled_token_returns_cancelled_outcome_before_any_chunk() {
// Given: a token that is already cancelled and a channel with no chunks yet
let (tx, rx) = channel::<StreamChunk>();
let cancel = CancelToken::new();
cancel.cancel();
// When: drain_to_stdout is called with the already-cancelled token
// Then: returns Outcome::Cancelled without blocking
match drain_to_stdout(rx, Some(5_000), &cancel) {
Outcome::Cancelled => {}
other => panic!(
"expected Cancelled, got: {other:?}",
other = OutcomeDebug(&other)
),
}
drop(tx);
}
#[test]
fn cancelled_token_returns_cancelled_even_with_pending_deltas() {
// Given: a cancelled token and a channel that has deltas queued but no Done
let (tx, rx) = channel();
tx.send(StreamChunk::Delta("partial".to_string())).unwrap();
let cancel = CancelToken::new();
cancel.cancel();
// When: drain_to_stdout is called
// Then: returns Cancelled (not Done) because the token was cancelled
match drain_to_stdout(rx, Some(5_000), &cancel) {
Outcome::Cancelled => {}
other => panic!(
"expected Cancelled, got: {other:?}",
other = OutcomeDebug(&other)
),
}
drop(tx);
}
// -----------------------------------------------------------------------
// Helpers
// -----------------------------------------------------------------------
struct OutcomeDebug<'a>(&'a Outcome);
impl std::fmt::Debug for OutcomeDebug<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self.0 {
Outcome::Done(s) => write!(f, "Done({s:?})"),
Outcome::Limit => write!(f, "Limit"),
Outcome::Error(m) => write!(f, "Error({m:?})"),
Outcome::Timeout => write!(f, "Timeout"),
Outcome::Cancelled => write!(f, "Cancelled"),
}
}
}
}