1#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
5#[serde(rename_all = "snake_case")]
6#[non_exhaustive]
7pub enum TaskType {
8 Shell,
10 Agent,
12 Teammate,
14 CronJob,
16 Monitor,
18 Code,
20 Ext,
22 Member,
25 McpTask,
28}
29
30impl TaskType {
31 pub fn as_str(&self) -> &'static str {
32 match self {
33 TaskType::Shell => "shell",
34 TaskType::Agent => "agent",
35 TaskType::Teammate => "teammate",
36 TaskType::CronJob => "cron",
37 TaskType::Monitor => "monitor",
38 TaskType::Code => "code",
39 TaskType::Ext => "ext",
40 TaskType::Member => "member",
41 TaskType::McpTask => "mcp_task",
42 }
43 }
44
45 pub fn id_prefix(&self) -> &'static str {
47 match self {
48 TaskType::Shell => "sh",
49 TaskType::Agent => "ag",
50 TaskType::Teammate => "tm",
51 TaskType::CronJob => "cj",
52 TaskType::Monitor => "mo",
53 TaskType::Code => "cd",
54 TaskType::Ext => "ext",
55 TaskType::Member => "member",
56 TaskType::McpTask => "mcp",
57 }
58 }
59}
60
61#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
63pub struct TaskId(pub String);
64
65impl TaskId {
66 pub fn new(task_type: TaskType) -> Self {
67 let uuid = uuid::Uuid::new_v4();
68 let short = &uuid.to_string()[..8];
69 TaskId(format!("{}-{}", task_type.id_prefix(), short))
70 }
71
72 pub fn as_str(&self) -> &str {
73 &self.0
74 }
75}
76
77impl std::fmt::Display for TaskId {
78 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
79 write!(f, "{}", self.0)
80 }
81}
82
83#[derive(Debug)]
88pub struct RunningTask {
89 pub task_id: String,
90 pub typed_id: Option<TaskId>,
91 pub task_type: TaskType,
92 output: std::sync::Mutex<TaskOutput>,
93 pub events_log: std::sync::Mutex<Vec<String>>,
95 pub status: std::sync::Mutex<RunningStatus>,
96 pub cancel: tokio_util::sync::CancellationToken,
98 pub started_ms: i64,
100 pub ended_ms: std::sync::Mutex<Option<i64>>,
102 pub detail: std::sync::Mutex<serde_json::Value>,
105 pub announced: std::sync::atomic::AtomicBool,
107 pub ended: tokio::sync::Notify,
109 pub inbox: std::sync::OnceLock<std::sync::Arc<dyn TaskInbox>>,
112 pub usage: std::sync::Mutex<Option<crate::interface::model::Usage>>,
115 pub structured_output: std::sync::OnceLock<serde_json::Value>,
117 pub waiting_for: std::sync::Mutex<Vec<String>>,
119 progress_sent: std::sync::Mutex<u64>,
121 events: std::sync::OnceLock<tokio::sync::broadcast::Sender<TaskEvent>>,
123 end_claimed: std::sync::atomic::AtomicBool,
124}
125
126pub trait TaskInbox: Send + Sync + std::fmt::Debug {
128 fn deliver(&self, message: String) -> Result<(), String>;
130}
131
132impl RunningTask {
133 pub fn new(task_id: String, task_type: TaskType) -> Self {
135 Self::with_cancel(
136 task_id,
137 task_type,
138 tokio_util::sync::CancellationToken::new(),
139 )
140 }
141
142 pub fn with_cancel(
144 task_id: String,
145 task_type: TaskType,
146 cancel: tokio_util::sync::CancellationToken,
147 ) -> Self {
148 Self {
149 task_id,
150 typed_id: None,
151 task_type,
152 output: std::sync::Mutex::new(TaskOutput::default()),
153 events_log: std::sync::Mutex::new(Vec::new()),
154 status: std::sync::Mutex::new(RunningStatus::Running),
155 cancel,
156 started_ms: crate::clock::unix_ms(),
157 ended_ms: std::sync::Mutex::new(None),
158 detail: std::sync::Mutex::new(serde_json::Value::Null),
159 announced: std::sync::atomic::AtomicBool::new(false),
160 ended: tokio::sync::Notify::new(),
161 inbox: std::sync::OnceLock::new(),
162 usage: std::sync::Mutex::new(
163 matches!(task_type, TaskType::Agent | TaskType::Teammate)
164 .then(crate::interface::model::Usage::default),
165 ),
166 structured_output: std::sync::OnceLock::new(),
167 waiting_for: std::sync::Mutex::new(Vec::new()),
168 progress_sent: std::sync::Mutex::new(0),
169 events: std::sync::OnceLock::new(),
170 end_claimed: std::sync::atomic::AtomicBool::new(false),
171 }
172 }
173
174 pub(crate) fn claim_end(&self) -> bool {
178 !self
179 .end_claimed
180 .swap(true, std::sync::atomic::Ordering::AcqRel)
181 }
182
183 pub fn report_to(&self, events: tokio::sync::broadcast::Sender<TaskEvent>) {
186 let _ = self.events.set(events);
187 }
188
189 pub fn add_usage(&self, call: crate::interface::model::Usage) {
191 {
192 let mut usage = self.usage.lock().unwrap_or_else(|e| e.into_inner());
193 *usage = Some(usage.unwrap_or_default().plus(call));
194 }
195 self.report_update();
196 }
197
198 pub fn begin_waiting(&self, prompt_id: &str) {
200 self.waiting_for
201 .lock()
202 .unwrap_or_else(|e| e.into_inner())
203 .push(prompt_id.to_string());
204 self.report_update();
205 }
206
207 pub fn end_waiting(&self, prompt_id: &str) {
209 let removed = {
210 let mut waiting = self.waiting_for.lock().unwrap_or_else(|e| e.into_inner());
211 let before = waiting.len();
212 waiting.retain(|id| id != prompt_id);
213 waiting.len() != before
214 };
215 if removed {
216 self.report_update();
217 }
218 }
219
220 pub fn update_detail(&self, change: impl FnOnce(&mut serde_json::Value)) {
222 change(&mut self.detail.lock().unwrap_or_else(|e| e.into_inner()));
223 self.report_update();
224 }
225
226 fn report_update(&self) {
229 let Some(events) = self.events.get() else {
230 return;
231 };
232 if self.announced.load(std::sync::atomic::Ordering::SeqCst) && !self.has_ended() {
233 let _ = events.send(TaskEvent::Updated { task: self.info() });
234 }
235 }
236
237 pub fn streams_output(&self) -> bool {
242 matches!(
243 self.task_type,
244 TaskType::Shell
245 | TaskType::Monitor
246 | TaskType::Code
247 | TaskType::Ext
248 | TaskType::McpTask
249 )
250 }
251
252 pub const PROGRESS_FRAME_BYTES: usize = 8 * 1024;
254
255 pub fn report_progress(&self) {
259 let mut sent = self.progress_sent.lock().unwrap_or_else(|e| e.into_inner());
260 let output = self.output.lock().unwrap_or_else(|e| e.into_inner());
261 if !output.closed {
262 self.send_progress(&output, &mut sent);
263 }
264 }
265
266 pub fn close_output(&self) -> bool {
270 let mut sent = self.progress_sent.lock().unwrap_or_else(|e| e.into_inner());
271 let mut output = self.output.lock().unwrap_or_else(|e| e.into_inner());
272 if output.closed {
273 return false;
274 }
275 output.closed = true;
276 self.send_progress(&output, &mut sent);
277 true
278 }
279
280 pub fn output_closed(&self) -> bool {
281 self.output.lock().unwrap_or_else(|e| e.into_inner()).closed
282 }
283
284 fn send_progress(&self, output: &TaskOutput, sent: &mut u64) {
285 if !self.streams_output()
286 || !self.announced.load(std::sync::atomic::Ordering::SeqCst)
287 || output.total == *sent
288 {
289 return;
290 }
291 let Some(events) = self.events.get() else {
292 return;
293 };
294 let new = output.total - *sent;
295 let shown = (new.min(Self::PROGRESS_FRAME_BYTES as u64) as usize).min(output.kept.len());
296 let cut = ceil_char_boundary(&output.kept, output.kept.len() - shown);
297 let appended = &output.kept[cut..];
298 let from_byte = output.total - appended.len() as u64;
299 let _ = events.send(TaskEvent::Progress {
300 task_id: self.task_id.clone(),
301 skipped_bytes: from_byte - *sent,
302 appended: appended.to_string(),
303 from_byte,
304 next_byte: output.total,
305 });
306 *sent = output.total;
307 }
308
309 pub fn has_ended(&self) -> bool {
310 self.ended_ms
311 .lock()
312 .unwrap_or_else(|e| e.into_inner())
313 .is_some()
314 }
315
316 pub async fn wait_ended(&self) {
318 let notified = self.ended.notified();
319 tokio::pin!(notified);
320 notified.as_mut().enable();
321 if self.has_ended() {
322 return;
323 }
324 notified.await;
325 }
326
327 pub const OUTPUT_KEPT_BYTES: usize = 256 * 1024;
330
331 pub fn append_output(&self, text: &str) {
334 let mut output = self.output.lock().unwrap_or_else(|e| e.into_inner());
335 if output.closed {
336 return;
337 }
338 output.kept.push_str(text);
339 output.total += text.len() as u64;
340 if output.kept.len() > Self::OUTPUT_KEPT_BYTES {
341 let cut = ceil_char_boundary(&output.kept, output.kept.len() - Self::OUTPUT_KEPT_BYTES);
342 output.kept.drain(..cut);
343 }
344 }
345
346 pub fn output_text(&self) -> String {
348 self.output
349 .lock()
350 .unwrap_or_else(|e| e.into_inner())
351 .kept
352 .clone()
353 }
354
355 pub fn output_tail(&self, max_bytes: usize) -> OutputSlice {
357 let output = self.output.lock().unwrap_or_else(|e| e.into_inner());
358 let cut = ceil_char_boundary(&output.kept, output.kept.len().saturating_sub(max_bytes));
359 output.slice(cut, 0)
360 }
361
362 pub fn output_from(&self, from_byte: u64) -> Result<OutputSlice, u64> {
366 let output = self.output.lock().unwrap_or_else(|e| e.into_inner());
367 if from_byte > output.total {
368 return Err(output.total);
369 }
370 let earliest = output.earliest_kept();
371 let at = ceil_char_boundary(&output.kept, (from_byte.max(earliest) - earliest) as usize);
372 let dropped = earliest + at as u64 - from_byte;
373 Ok(output.slice(at, dropped))
374 }
375
376 pub fn info(&self) -> TaskInfo {
378 let status = self
379 .status
380 .lock()
381 .unwrap_or_else(|e| e.into_inner())
382 .clone();
383 let waiting_for = self
384 .waiting_for
385 .lock()
386 .unwrap_or_else(|e| e.into_inner())
387 .clone();
388 let (status, error, waiting_for) = match status {
389 RunningStatus::Running if !waiting_for.is_empty() => {
390 (TaskStatus::Waiting, None, waiting_for)
391 }
392 RunningStatus::Running => (TaskStatus::Running, None, Vec::new()),
393 RunningStatus::Completed => (TaskStatus::Done, None, Vec::new()),
394 RunningStatus::Cancelled => (TaskStatus::Stopped, None, Vec::new()),
395 RunningStatus::Failed(e) => (TaskStatus::Failed, Some(e), Vec::new()),
396 };
397 TaskInfo {
398 task_id: self.task_id.clone(),
399 kind: self.task_type,
400 status,
401 started_ms: self.started_ms,
402 ended_ms: *self.ended_ms.lock().unwrap_or_else(|e| e.into_inner()),
403 detail: self
404 .detail
405 .lock()
406 .unwrap_or_else(|e| e.into_inner())
407 .clone(),
408 error,
409 waiting_for,
410 usage: *self.usage.lock().unwrap_or_else(|e| e.into_inner()),
411 structured_output: self.structured_output.get().cloned(),
412 }
413 }
414}
415
416#[derive(Debug, Clone, PartialEq, serde::Serialize, schemars::JsonSchema)]
418pub struct TaskInfo {
419 pub task_id: String,
420 #[serde(serialize_with = "wire_kind")]
422 #[schemars(with = "String")]
423 pub kind: TaskType,
424 pub status: TaskStatus,
425 pub started_ms: i64,
427 pub ended_ms: Option<i64>,
429 pub detail: serde_json::Value,
430 #[serde(skip_serializing_if = "Option::is_none")]
431 pub error: Option<String>,
432 #[serde(skip_serializing_if = "Vec::is_empty")]
434 pub waiting_for: Vec<String>,
435 #[serde(skip_serializing_if = "Option::is_none")]
436 pub usage: Option<crate::interface::model::Usage>,
437 #[serde(skip_serializing_if = "Option::is_none")]
438 pub structured_output: Option<serde_json::Value>,
439}
440
441fn wire_kind<S: serde::Serializer>(kind: &TaskType, s: S) -> Result<S::Ok, S::Error> {
444 s.serialize_str(kind.as_str())
445}
446
447#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, schemars::JsonSchema)]
448#[serde(rename_all = "snake_case")]
449#[non_exhaustive]
450pub enum TaskStatus {
451 Running,
452 Idle,
454 Waiting,
456 Done,
457 Stopped,
458 Failed,
459}
460
461impl TaskStatus {
462 pub fn as_str(self) -> &'static str {
463 match self {
464 Self::Running => "running",
465 Self::Idle => "idle",
466 Self::Waiting => "waiting",
467 Self::Done => "done",
468 Self::Stopped => "stopped",
469 Self::Failed => "failed",
470 }
471 }
472}
473
474#[derive(Debug, Clone, PartialEq, serde::Serialize)]
477#[serde(tag = "kind")]
478pub enum TaskEvent {
479 #[serde(rename = "task_started")]
480 Started { task: TaskInfo },
481 #[serde(rename = "task_updated")]
482 Updated { task: TaskInfo },
483 #[serde(rename = "task_progress")]
487 Progress {
488 task_id: String,
489 skipped_bytes: u64,
490 appended: String,
491 from_byte: u64,
492 next_byte: u64,
493 },
494 #[serde(rename = "task_finished")]
495 Finished { task: TaskInfo },
496}
497
498#[derive(Debug, Default)]
500struct TaskOutput {
501 kept: String,
505 total: u64,
506 closed: bool,
507}
508
509impl TaskOutput {
510 fn earliest_kept(&self) -> u64 {
511 self.total - self.kept.len() as u64
512 }
513
514 fn slice(&self, at: usize, dropped: u64) -> OutputSlice {
515 OutputSlice {
516 text: self.kept[at..].to_string(),
517 from_byte: self.earliest_kept() + at as u64,
518 next_byte: self.total,
519 dropped,
520 closed: self.closed,
521 }
522 }
523}
524
525#[derive(Debug, Clone, PartialEq, Eq)]
528pub struct OutputSlice {
529 pub text: String,
530 pub from_byte: u64,
531 pub next_byte: u64,
532 pub dropped: u64,
535 pub closed: bool,
537}
538
539fn ceil_char_boundary(text: &str, mut at: usize) -> usize {
540 while !text.is_char_boundary(at) {
541 at += 1;
542 }
543 at
544}
545
546#[cfg(test)]
547mod tests {
548 use super::*;
549
550 #[test]
551 fn an_mcp_task_streams_its_status_lines() {
552 let task = RunningTask::new("mcp-1".into(), TaskType::McpTask);
553 assert!(task.streams_output());
554 assert_eq!(task.info().kind.as_str(), "mcp_task");
555 task.update_detail(|d| *d = serde_json::json!({"mcp_status": "working"}));
556 assert_eq!(task.info().detail["mcp_status"], "working");
557 }
558
559 #[test]
560 fn a_tail_is_cut_on_a_character_boundary() {
561 let task = RunningTask::new("sh-1".into(), TaskType::Shell);
562 task.append_output("ab\u{4e2d}\n");
563 let tail = |max| {
564 let tail = task.output_tail(max);
565 (tail.text, tail.from_byte)
566 };
567 assert_eq!(tail(64), ("ab\u{4e2d}\n".to_string(), 0));
568 assert_eq!(tail(2), ("\n".to_string(), 5));
569 assert_eq!(tail(4), ("\u{4e2d}\n".to_string(), 2));
570 assert_eq!(task.output_tail(2).next_byte, 6);
571 }
572
573 #[test]
574 fn the_oldest_output_goes_past_the_cap() {
575 let task = RunningTask::new("sh-2".into(), TaskType::Shell);
576 task.append_output("head\n");
577 task.append_output(&"x".repeat(RunningTask::OUTPUT_KEPT_BYTES));
578 let whole = task.output_tail(usize::MAX);
579 assert_eq!(whole.text.len(), RunningTask::OUTPUT_KEPT_BYTES);
580 assert!(!whole.text.contains("head"));
581 assert_eq!(whole.from_byte, 5, "what was dropped is reported");
582 }
583
584 #[test]
585 fn reads_from_each_next_byte_join_into_the_whole_output() {
586 let task = RunningTask::new("sh-3".into(), TaskType::Shell);
587 let mut joined = String::new();
588 let mut next = 0;
589 for chunk in ["one\n", "\u{4e2d}two\n", "three\n"] {
590 task.append_output(chunk);
591 let read = task.output_from(next).unwrap();
592 assert_eq!(read.from_byte, next);
593 assert_eq!(read.dropped, 0);
594 joined.push_str(&read.text);
595 next = read.next_byte;
596 }
597 assert_eq!(joined, "one\n\u{4e2d}two\nthree\n");
598 assert_eq!(next, joined.len() as u64);
599 let idle = task.output_from(next).unwrap();
600 assert_eq!((idle.text.as_str(), idle.next_byte), ("", next));
601 }
602
603 #[test]
604 fn a_read_after_more_than_is_kept_says_how_much_was_dropped() {
605 let task = RunningTask::new("sh-4".into(), TaskType::Shell);
606 task.append_output("start\n");
607 let first = task.output_from(0).unwrap();
608 task.append_output(&"x".repeat(RunningTask::OUTPUT_KEPT_BYTES + 100));
609 let second = task.output_from(first.next_byte).unwrap();
610 let earliest_kept = second.next_byte - RunningTask::OUTPUT_KEPT_BYTES as u64;
611 assert_eq!(second.from_byte, earliest_kept);
612 assert_eq!(second.dropped, earliest_kept - first.next_byte);
613 assert_eq!(second.text, task.output_text());
614 assert_eq!(
615 second.from_byte + second.text.len() as u64,
616 second.next_byte
617 );
618 }
619
620 #[test]
621 fn a_read_from_inside_a_character_starts_after_it() {
622 let task = RunningTask::new("sh-5".into(), TaskType::Shell);
623 task.append_output("a\u{4e2d}b");
624 let read = task.output_from(2).unwrap();
625 assert_eq!(read.text, "b");
626 assert_eq!((read.from_byte, read.dropped), (4, 2));
627 }
628
629 #[test]
630 fn a_read_past_the_end_is_refused_with_the_end() {
631 let task = RunningTask::new("sh-6".into(), TaskType::Shell);
632 task.append_output("abc");
633 assert_eq!(task.output_from(4), Err(3));
634 assert!(task.output_from(3).is_ok());
635 }
636
637 #[test]
638 fn a_closed_output_takes_nothing_more() {
639 let task = RunningTask::new("sh-7".into(), TaskType::Shell);
640 task.append_output("done\n");
641 assert!(!task.output_tail(64).closed);
642 assert!(task.close_output());
643 assert!(!task.close_output(), "only once");
644 task.append_output("late\n");
645 let read = task.output_from(0).unwrap();
646 assert_eq!(read.text, "done\n");
647 assert!(read.closed);
648 }
649
650 fn reporting(
651 task_type: TaskType,
652 ) -> (RunningTask, tokio::sync::broadcast::Receiver<TaskEvent>) {
653 let (events, rx) = tokio::sync::broadcast::channel(64);
654 let task = RunningTask::new("t-1".into(), task_type);
655 task.report_to(events);
656 (task, rx)
657 }
658
659 fn drain(rx: &mut tokio::sync::broadcast::Receiver<TaskEvent>) -> Vec<serde_json::Value> {
660 std::iter::from_fn(|| rx.try_recv().ok())
661 .map(|e| serde_json::to_value(e).unwrap())
662 .collect()
663 }
664
665 #[test]
666 fn progress_goes_out_only_between_announcement_and_close() {
667 let (task, mut rx) = reporting(TaskType::Shell);
668 task.append_output("early\n");
669 task.report_progress();
670 assert!(drain(&mut rx).is_empty(), "not announced yet");
671
672 task.announced
673 .store(true, std::sync::atomic::Ordering::SeqCst);
674 task.report_progress();
675 task.append_output("more\n");
676 task.report_progress();
677 task.report_progress();
678 let sent: Vec<_> = drain(&mut rx)
679 .into_iter()
680 .map(|e| e["appended"].as_str().unwrap().to_string())
681 .collect();
682 assert_eq!(
683 sent,
684 ["early\n", "more\n"],
685 "each byte once, nothing when idle"
686 );
687
688 task.append_output("last\n");
689 task.close_output();
690 assert_eq!(drain(&mut rx)[0]["appended"], "last\n");
691 task.report_progress();
692 assert!(drain(&mut rx).is_empty(), "nothing follows the close");
693 }
694
695 #[test]
696 fn progress_frames_carry_offsets_that_account_for_every_byte() {
697 let (task, mut rx) = reporting(TaskType::Shell);
698 task.announced
699 .store(true, std::sync::atomic::Ordering::SeqCst);
700 for chunk in [
701 "a\n".to_string(),
702 "x".repeat(RunningTask::PROGRESS_FRAME_BYTES + 10),
703 "\u{4e2d}\n".to_string(),
704 ] {
705 task.append_output(&chunk);
706 task.report_progress();
707 }
708 let frames = drain(&mut rx);
709 assert_eq!(frames.len(), 3);
710 let mut previous = 0;
711 for frame in &frames {
712 let from = frame["from_byte"].as_u64().unwrap();
713 let next = frame["next_byte"].as_u64().unwrap();
714 assert_eq!(from - previous, frame["skipped_bytes"].as_u64().unwrap());
715 assert_eq!(
716 from + frame["appended"].as_str().unwrap().len() as u64,
717 next
718 );
719 previous = next;
720 }
721 assert_eq!(frames[1]["skipped_bytes"], 10);
722 assert_eq!(previous, task.output_tail(1).next_byte);
723 }
724
725 #[test]
726 fn a_burst_beyond_a_frame_is_sent_as_its_tail() {
727 let (task, mut rx) = reporting(TaskType::Monitor);
728 task.announced
729 .store(true, std::sync::atomic::Ordering::SeqCst);
730 let burst = "x".repeat(RunningTask::PROGRESS_FRAME_BYTES * 3);
731 task.append_output(&burst);
732 task.report_progress();
733 let frame = drain(&mut rx).remove(0);
734 assert_eq!(frame["kind"], "task_progress");
735 assert_eq!(frame["task_id"], "t-1");
736 assert_eq!(
737 frame["appended"].as_str().unwrap().len(),
738 RunningTask::PROGRESS_FRAME_BYTES
739 );
740 assert_eq!(
741 frame["skipped_bytes"],
742 RunningTask::PROGRESS_FRAME_BYTES * 2,
743 "what was left out is counted"
744 );
745 }
746
747 #[test]
748 fn a_sub_agents_answer_is_not_streamed() {
749 let (task, mut rx) = reporting(TaskType::Agent);
750 task.announced
751 .store(true, std::sync::atomic::Ordering::SeqCst);
752 task.append_output("the answer");
753 task.close_output();
754 assert!(drain(&mut rx).is_empty());
755 }
756
757 #[test]
758 fn usage_and_waiting_are_reported_as_snapshots() {
759 let (task, mut rx) = reporting(TaskType::Agent);
760 let call = crate::interface::model::Usage {
761 input_tokens: 10,
762 output_tokens: 2,
763 ..Default::default()
764 };
765 task.add_usage(call);
766 assert!(drain(&mut rx).is_empty(), "not announced yet");
767
768 task.announced
769 .store(true, std::sync::atomic::Ordering::SeqCst);
770 task.add_usage(call);
771 let update = drain(&mut rx).remove(0);
772 assert_eq!(update["kind"], "task_updated");
773 assert_eq!(update["task"]["usage"]["input_tokens"], 20);
774 assert_eq!(update["task"]["status"], "running");
775
776 task.begin_waiting("p-1");
777 task.begin_waiting("p-2");
778 task.end_waiting("p-1");
779 let states: Vec<_> = drain(&mut rx)
780 .into_iter()
781 .map(|e| {
782 (
783 e["task"]["status"].clone(),
784 e["task"]["waiting_for"].clone(),
785 )
786 })
787 .collect();
788 assert_eq!(
789 states,
790 [
791 (serde_json::json!("waiting"), serde_json::json!(["p-1"])),
792 (
793 serde_json::json!("waiting"),
794 serde_json::json!(["p-1", "p-2"])
795 ),
796 (serde_json::json!("waiting"), serde_json::json!(["p-2"])),
797 ]
798 );
799 task.end_waiting("p-2");
800 task.end_waiting("p-2");
801 let back = drain(&mut rx);
802 assert_eq!(back.len(), 1, "an answer already counted changes nothing");
803 assert_eq!(back[0]["task"]["status"], "running");
804 assert!(back[0]["task"].get("waiting_for").is_none());
805
806 *task.ended_ms.lock().unwrap() = Some(1);
807 task.add_usage(call);
808 assert!(
809 drain(&mut rx).is_empty(),
810 "an ended task's final word is task_finished"
811 );
812 }
813}
814
815#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
816#[serde(rename_all = "snake_case")]
817pub enum RunningStatus {
818 Running,
820 Completed,
822 Cancelled,
824 Failed(String),
826}
827
828#[derive(
830 Debug, Clone, serde::Serialize, serde::Deserialize, schemars::JsonSchema, PartialEq, Eq,
831)]
832pub struct TodoItem {
833 pub content: String,
835 pub status: TodoStatus,
837 #[serde(alias = "activeForm")]
840 pub active_form: String,
841}
842
843#[derive(
844 Debug, Clone, Copy, serde::Serialize, serde::Deserialize, schemars::JsonSchema, PartialEq, Eq,
845)]
846#[serde(rename_all = "snake_case")]
847pub enum TodoStatus {
848 Pending,
849 InProgress,
850 Completed,
851}