Skip to main content

base/context/
task.rs

1//! 后台任务 + todo 条目类型。
2
3/// Task type enum — categorises all background/async task kinds.
4#[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 command executed as a background process.
9    Shell,
10    /// Sub-agent spawned by AgentTool.
11    Agent,
12    /// In-process teammate (team/swarm mode).
13    Teammate,
14    /// Cron/scheduled job.
15    CronJob,
16    /// MCP monitor task.
17    Monitor,
18    /// A program the model wrote (`RunCode`).
19    Code,
20    /// A plugin command run through `RunExt`.
21    Ext,
22    /// A persistent team member, alive between the messages it is handed;
23    /// each message it runs is a `Teammate` task of its own.
24    Member,
25    /// One MCP tool call that the server turned into a task; lasts as long
26    /// as that call.
27    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    /// Prefix used in task IDs for quick type recognition.
46    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/// Strongly-typed task identifier.
62#[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/// 一件属于会话、在会话里继续跑的工作:子 Agent、团队成员、执行中的 Shell……
84/// 输出(`append_output`)/ events_log / status 由跑它的那段代码追加;TaskOutput
85/// 工具与宿主的 `session.taskOutput` 读快照,或按字节偏移接着读;
86/// TaskStop 与宿主的 `session.stopTask` 触发 cancel token。
87#[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    /// 工具调用与结果的可读日志(每行一条)
94    pub events_log: std::sync::Mutex<Vec<String>>,
95    pub status: std::sync::Mutex<RunningStatus>,
96    /// What the work runs under: cancelling it stops the work.
97    pub cancel: tokio_util::sync::CancellationToken,
98    /// Unix millis.
99    pub started_ms: i64,
100    /// Unix millis; `None` while it runs.
101    pub ended_ms: std::sync::Mutex<Option<i64>>,
102    /// What a viewer needs to tell this task from another: the command, the
103    /// sub-agent's type, the tool call it belongs to.
104    pub detail: std::sync::Mutex<serde_json::Value>,
105    /// Whether its start was announced; a task that never was ends silently.
106    pub announced: std::sync::atomic::AtomicBool,
107    /// Woken once `ended_ms` is set — see [`RunningTask::wait_ended`].
108    pub ended: tokio::sync::Notify,
109    /// Where messages for the work go while it runs; set by work that can
110    /// take them (a sub-agent), absent for the rest.
111    pub inbox: std::sync::OnceLock<std::sync::Arc<dyn TaskInbox>>,
112    /// What the work's own model calls have cost so far; `None` for work that
113    /// makes none (a shell command).
114    pub usage: std::sync::Mutex<Option<crate::interface::model::Usage>>,
115    /// What a sub-agent with an output schema handed in.
116    pub structured_output: std::sync::OnceLock<serde_json::Value>,
117    /// The questions the work is waiting on the host to answer, by prompt id.
118    pub waiting_for: std::sync::Mutex<Vec<String>>,
119    /// How much of the output has gone out as `task_progress`, in bytes.
120    progress_sent: std::sync::Mutex<u64>,
121    /// The session's task event channel, once the task is registered.
122    events: std::sync::OnceLock<tokio::sync::broadcast::Sender<TaskEvent>>,
123    end_claimed: std::sync::atomic::AtomicBool,
124}
125
126/// Delivers a message to a running task's work.
127pub trait TaskInbox: Send + Sync + std::fmt::Debug {
128    /// `Err` says why the work cannot take it now.
129    fn deliver(&self, message: String) -> Result<(), String>;
130}
131
132impl RunningTask {
133    /// Create a new running task with defaults.
134    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    /// A running task whose work runs under `cancel`.
143    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    /// Whether the caller is the one to end this task and tell its parent
175    /// how: `true` to the first of its lease and whoever stops it with a
176    /// notice, `false` to the other.
177    pub(crate) fn claim_end(&self) -> bool {
178        !self
179            .end_claimed
180            .swap(true, std::sync::atomic::Ordering::AcqRel)
181    }
182
183    /// Where this task's `task_*` events go; set once, by the session that
184    /// registers it.
185    pub fn report_to(&self, events: tokio::sync::broadcast::Sender<TaskEvent>) {
186        let _ = self.events.set(events);
187    }
188
189    /// Count one more model call of this task's work.
190    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    /// The work is waiting on the host's answer to `prompt_id`.
199    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    /// The question `prompt_id` was answered, or given up on.
208    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    /// Change what `detail` holds, then report `task_updated`.
221    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    /// `task_updated`, for a task whose start was announced and which has
227    /// not ended: what changed is in the snapshot.
228    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    /// Whether what the work prints is streamed as it runs (`task_progress`):
238    /// a shell command's, a monitor's, a program's and an MCP task's status
239    /// lines. A sub-agent's output is its final answer, reported when it
240    /// finishes.
241    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    /// The most of the new output one `task_progress` carries.
253    pub const PROGRESS_FRAME_BYTES: usize = 8 * 1024;
254
255    /// Send what the work printed since the last `task_progress`, if anything.
256    /// Nothing goes out once the output is [closed](Self::close_output), so
257    /// none can follow `task_finished`.
258    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    /// End the output: what the work printed since the last `task_progress`
267    /// goes out as the last one, and nothing is added after. `false` if it
268    /// was already closed.
269    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    /// Resolves once the task has ended (at once if it already has).
317    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    /// The most of a streamed output (a shell command's, a monitor's) a task
328    /// keeps; beyond it the oldest goes.
329    pub const OUTPUT_KEPT_BYTES: usize = 256 * 1024;
330
331    /// Add to the output as the work produces it, keeping its last
332    /// [`Self::OUTPUT_KEPT_BYTES`]. Nothing is added once it is closed.
333    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    /// All of the output still kept.
347    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    /// The last `max_bytes` of the output.
356    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    /// The output from byte `from_byte` of everything ever appended to its
363    /// end, as much of it as is still kept. `Err` carries the end when
364    /// `from_byte` is past it.
365    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    /// This task as hosts see it (`session.tasks`, `task_*` events).
377    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/// A task as `session.tasks` lists it and the `task_*` events carry it.
417#[derive(Debug, Clone, PartialEq, serde::Serialize, schemars::JsonSchema)]
418pub struct TaskInfo {
419    pub task_id: String,
420    /// `agent`, `teammate`, `member`, `shell`, `monitor`, `cron`, `code` or `mcp_task`.
421    #[serde(serialize_with = "wire_kind")]
422    #[schemars(with = "String")]
423    pub kind: TaskType,
424    pub status: TaskStatus,
425    /// Unix millis.
426    pub started_ms: i64,
427    /// Unix millis; `null` while it runs.
428    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    /// The prompt ids the work waits on; empty unless `status` is `waiting`.
433    #[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
441/// On the wire a task's kind goes by [`TaskType::as_str`], not its serde
442/// name: `cron`, not `cron_job`.
443fn 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    /// Alive with nothing to do: a persistent team member between messages.
453    Idle,
454    /// Running, and waiting on the host to answer a question.
455    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/// What a session's tasks report as they run
475/// (`SessionState::subscribe_tasks` in `session-state`).
476#[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    /// What a streamed task printed since the last one: bytes
484    /// `from_byte..next_byte` of everything it ever printed, after
485    /// `skipped_bytes` that did not fit in one frame.
486    #[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/// A task's output, as the offsets of everything ever appended count it.
499#[derive(Debug, Default)]
500struct TaskOutput {
501    /// The tail of it, at most [`RunningTask::OUTPUT_KEPT_BYTES`]. Every
502    /// append is whole text and the head is cut on a character boundary, so
503    /// every offset handed out is one too.
504    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/// A stretch of a task's output: bytes `from_byte..next_byte` of everything
526/// the work ever printed.
527#[derive(Debug, Clone, PartialEq, Eq)]
528pub struct OutputSlice {
529    pub text: String,
530    pub from_byte: u64,
531    pub next_byte: u64,
532    /// Of what was asked for, the bytes no longer kept: the asked-for start
533    /// plus these is `from_byte`.
534    pub dropped: u64,
535    /// The work's output has ended; `next_byte` will not grow.
536    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    /// 还在跑
819    Running,
820    /// 完成(自然结束)
821    Completed,
822    /// TaskStop 触发取消
823    Cancelled,
824    /// 内部错误(API / 工具)
825    Failed(String),
826}
827
828/// 一条 todo —— 模型用 TodoWrite 一次性替换整个列表。
829#[derive(
830    Debug, Clone, serde::Serialize, serde::Deserialize, schemars::JsonSchema, PartialEq, Eq,
831)]
832pub struct TodoItem {
833    /// 给用户看的简短描述
834    pub content: String,
835    /// 状态
836    pub status: TodoStatus,
837    /// 现在时态描述(spinner 用),如 "Writing tests"。必填。
838    // Models trained on camelCase tool schemas send `activeForm`.
839    #[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}