返回 CodeWhale
tests.rs
根目录 / crates / tui / src / tui / agent_roster / tests.rs
1 use super::*;
2
3 use codewhale_agent_contract::role::FleetRole;
4 use codewhale_agent_contract::worker_profile::WorkerRuntimeProfile;
5 use codewhale_engine::agent_roster::{RosterState, build_agent_roster};
6 use codewhale_engine::tools::subagent::{
7 AgentRunUsage, AgentWorkerEvent, AgentWorkerRecord, AgentWorkerSpec, AgentWorkerStatus,
8 AgentWorkerToolProfile,
9 };
10
11 fn usage_none() -> AgentRunUsage {
12 AgentRunUsage {
13 status: "unavailable".to_string(),
14 input_tokens: None,
15 output_tokens: None,
16 total_tokens: None,
17 cost_microusd: None,
18 note: "no route audit for this worker".to_string(),
19 }
20 }
21
22 fn usage_of(input: u64, output: u64) -> AgentRunUsage {
23 AgentRunUsage {
24 status: "reported".to_string(),
25 input_tokens: Some(input),
26 output_tokens: Some(output),
27 total_tokens: Some(input + output),
28 cost_microusd: Some(1_234),
29 ..usage_none()
30 }
31 }
32
33 /// Minimal record; each test overrides only the fields it is about.
34 fn record(worker_id: &str, created_at_ms: u64) -> AgentWorkerRecord {
35 let spec = AgentWorkerSpec {
36 worker_id: worker_id.to_string(),
37 run_id: format!("run-{worker_id}"),
38 parent_run_id: None,
39 workflow_run_id: None,
40 session_name: Some(worker_id.to_string()),
41 objective: "do the thing".to_string(),
42 role: None,
43 agent_type: FleetRole::Scout,
44 model: "deepseek-v4-pro".to_string(),
45 workspace: std::path::PathBuf::from("/tmp/ws"),
46 git_branch: None,
47 context_mode: "fresh".to_string(),
48 fork_context: false,
49 tool_profile: AgentWorkerToolProfile::Inherited,
50 runtime_profile: WorkerRuntimeProfile::for_role(FleetRole::Scout),
51 max_steps: 20,
52 spawn_depth: 1,
53 max_spawn_depth: 3,
54 child_route: None,
55 launch_manifest: None,
56 };
57 let mut rec = AgentWorkerRecord::new(spec, created_at_ms);
58 rec.status = AgentWorkerStatus::Running;
59 rec.started_at_ms = Some(created_at_ms);
60 rec.usage = usage_none();
61 rec
62 }
63
64 // === The truth rule: absent is not zero ===
65
66 #[test]
67 fn a_worker_without_a_usage_receipt_reports_no_tokens_not_zero() {
68 let rows = build_agent_roster(&[record("scout", 1_000)], 5_000);
69 let row = &rows[0];
70 assert_eq!(
71 row.input_tokens, None,
72 "a missing route audit must stay missing"
73 );
74 assert_eq!(row.output_tokens, None);
75 assert_eq!(row.cost_microusd, None);
76
77 let text = render_agent_roster(&rows, "main");
78 assert!(
79 text.contains('—'),
80 "an absent receipt renders as an em dash, never as 0:\n{text}"
81 );
82 assert!(
83 !text.contains("↓ 0") && !text.contains("↑ 0"),
84 "no receipt must never be shown as a zero token count:\n{text}"
85 );
86 }
87
88 #[test]
89 fn reported_usage_is_passed_through_untouched() {
90 let mut rec = record("builder", 1_000);
91 rec.usage = usage_of(96_300, 4_120);
92 let rows = build_agent_roster(&[rec], 5_000);
93 assert_eq!(rows[0].input_tokens, Some(96_300));
94 assert_eq!(rows[0].output_tokens, Some(4_120));
95
96 let text = render_agent_roster(&rows, "main");
97 assert!(text.contains("↓ 96.3k"), "{text}");
98 assert!(text.contains("↑ 4.1k"), "{text}");
99 }
100
101 #[test]
102 fn totals_are_absent_when_nothing_reported_and_never_summed_from_zeros() {
103 let rows = build_agent_roster(&[record("a", 1), record("b", 2)], 10);
104 assert_eq!(
105 roster_totals(&rows),
106 (None, None),
107 "summing absent receipts into 0 restates the same lie per-row rendering forbids"
108 );
109 assert!(!all_rows_have_usage(&rows));
110
111 let mut reported = record("c", 3);
112 reported.usage = usage_of(10, 20);
113 let mixed = build_agent_roster(&[record("a", 1), reported], 10);
114 assert_eq!(
115 roster_totals(&mixed),
116 (Some(10), Some(20)),
117 "a partial total reports only what was actually reported"
118 );
119 assert!(
120 !all_rows_have_usage(&mixed),
121 "callers must be able to label a partial total as partial"
122 );
123 }
124
125 // === Time: elapsed while live, frozen when finished ===
126
127 #[test]
128 fn a_finished_agent_keeps_the_duration_it_finished_with() {
129 let mut rec = record("done-worker", 1_000);
130 rec.status = AgentWorkerStatus::Completed;
131 rec.completed_at_ms = Some(4_500);
132
133 let early = build_agent_roster(&[rec.clone()], 5_000);
134 let much_later = build_agent_roster(&[rec], 900_000);
135 assert_eq!(early[0].millis, Some(3_500));
136 assert_eq!(
137 much_later[0].millis,
138 Some(3_500),
139 "a finished row must not keep ticking as the session goes on"
140 );
141 }
142
143 #[test]
144 fn a_live_agent_reports_elapsed_against_the_supplied_instant() {
145 let rows = build_agent_roster(&[record("live", 1_000)], 210_000);
146 assert_eq!(rows[0].millis, Some(209_000));
147 let text = render_agent_roster(&rows, "main");
148 assert!(text.contains("3m 29s"), "{text}");
149 }
150
151 #[test]
152 fn a_worker_that_never_started_has_no_duration_rather_than_zero() {
153 let mut rec = record("queued", 1_000);
154 rec.status = AgentWorkerStatus::Queued;
155 rec.started_at_ms = None;
156 let rows = build_agent_roster(&[rec], 9_000);
157 assert_eq!(
158 rows[0].millis, None,
159 "reporting 0s would imply the worker had started"
160 );
161 }
162
163 // === Activity line ===
164
165 #[test]
166 fn activity_prefers_the_newest_tool_event_and_stays_one_line() {
167 let mut rec = record("worker", 1_000);
168 rec.events.push_back(AgentWorkerEvent {
169 seq: 1,
170 worker_id: "worker".to_string(),
171 status: AgentWorkerStatus::Running,
172 timestamp_ms: 1_100,
173 message: Some("starting".to_string()),
174 step: Some(1),
175 tool_name: Some("Grep".to_string()),
176 });
177 rec.events.push_back(AgentWorkerEvent {
178 seq: 2,
179 worker_id: "worker".to_string(),
180 status: AgentWorkerStatus::RunningTool,
181 timestamp_ms: 1_200,
182 message: None,
183 step: Some(4),
184 tool_name: Some("Bash".to_string()),
185 });
186 let rows = build_agent_roster(&[rec], 2_000);
187 assert_eq!(rows[0].activity.as_deref(), Some("step 4 · Bash"));
188 }
189
190 #[test]
191 fn a_multiline_message_is_flattened_and_bounded_to_one_row() {
192 let mut rec = record("chatty", 1_000);
193 rec.latest_message = Some(format!("line one\nline two\n{}", "x".repeat(300)));
194 let rows = build_agent_roster(&[rec], 2_000);
195 let activity = rows[0].activity.clone().expect("activity");
196 assert!(!activity.contains('\n'), "a rail row is one row");
197 assert!(activity.chars().count() <= 72, "{}", activity.len());
198 assert!(activity.ends_with('…'), "truncation is visible: {activity}");
199 }
200
201 #[test]
202 fn a_worker_with_no_events_reports_no_activity() {
203 let rows = build_agent_roster(&[record("silent", 1_000)], 2_000);
204 assert_eq!(rows[0].activity, None);
205 assert!(render_agent_roster(&rows, "main").contains('—'));
206 }
207
208 // === Ordering and workflow aggregation ===
209
210 #[test]
211 fn rows_are_ordered_oldest_first_so_the_rail_reads_as_history() {
212 let rows = build_agent_roster(
213 &[
214 record("third", 3_000),
215 record("first", 1_000),
216 record("second", 2_000),
217 ],
218 9_000,
219 );
220 let names: Vec<&str> = rows.iter().map(|row| row.display_name.as_str()).collect();
221 assert_eq!(names, vec!["first", "second", "third"]);
222 }
223
224 #[test]
225 fn a_workflow_parent_aggregates_its_children_as_n_of_m_done() {
226 let parent = record("workflow", 1_000);
227 let parent_run = parent.spec.run_id.clone();
228 let mut children = Vec::new();
229 for index in 0..6 {
230 let mut child = record(&format!("child-{index}"), 2_000 + index as u64);
231 child.parent_run_id = Some(parent_run.clone());
232 child.spec.parent_run_id = Some(parent_run.clone());
233 if index < 5 {
234 child.status = AgentWorkerStatus::Completed;
235 child.completed_at_ms = Some(3_000);
236 }
237 children.push(child);
238 }
239 let mut records = vec![parent];
240 records.extend(children);
241 let rows = build_agent_roster(&records, 9_000);
242
243 let text = render_agent_roster(&rows, "main");
244 assert!(
245 text.contains("5/6 agents done"),
246 "a workflow collapses to one progress line:\n{text}"
247 );
248 // Children are listed under the parent, indented, and exactly once.
249 assert_eq!(
250 text.matches("child-0").count(),
251 1,
252 "a child must not also appear at the top level:\n{text}"
253 );
254 assert!(text.contains(" ○ child-0"), "{text}");
255 }
256
257 #[test]
258 fn a_grandchild_is_rendered_under_its_parent_not_dropped() {
259 let mut parent = record("workflow", 1_000);
260 parent.status = AgentWorkerStatus::Running;
261 let parent_run = parent.spec.run_id.clone();
262 let mut child = record("builder", 2_000);
263 child.parent_run_id = Some(parent_run.clone());
264 child.spec.parent_run_id = Some(parent_run);
265 child.status = AgentWorkerStatus::Running;
266 let child_run = child.spec.run_id.clone();
267 let mut grandchild = record("scout", 3_000);
268 grandchild.parent_run_id = Some(child_run);
269 grandchild.spec.parent_run_id = Some(child.spec.run_id.clone());
270 grandchild.status = AgentWorkerStatus::Running;
271
272 let rows = build_agent_roster(&[parent, child, grandchild], 9_000);
273 let text = render_agent_roster(&rows, "main");
274 assert!(
275 text.contains("scout"),
276 "a third-level agent must appear in /agents list:\n{text}"
277 );
278 assert_eq!(text.matches("scout").count(), 1, "{text}");
279 assert!(
280 text.contains(" "),
281 "a grandchild should be indented under its parent:\n{text}"
282 );
283 }
284
285 #[test]
286 fn an_orphaned_child_still_appears_when_its_parent_is_not_in_the_roster() {
287 // The parent's record can age out of the ledger before the child's does.
288 let mut child = record("orphan", 2_000);
289 child.parent_run_id = Some("run-that-aged-out".to_string());
290 let rows = build_agent_roster(&[child], 9_000);
291 let text = render_agent_roster(&rows, "main");
292 assert!(
293 text.contains("orphan"),
294 "a child whose parent is gone must not vanish from the roster:\n{text}"
295 );
296 }
297
298 // === Rendering basics ===
299
300 #[test]
301 fn an_empty_roster_says_so_instead_of_rendering_an_empty_frame() {
302 let text = render_agent_roster(&[], "main");
303 assert!(text.contains("● main"));
304 assert!(text.contains("No agents have run in this session yet"));
305 }
306
307 #[test]
308 fn every_state_has_a_distinct_single_width_glyph() {
309 let states = [
310 RosterState::Running,
311 RosterState::Waiting,
312 RosterState::Done,
313 RosterState::Failed,
314 RosterState::Cancelled,
315 ];
316 let glyphs: Vec<&str> = states.iter().map(|state| state.glyph()).collect();
317 let unique: std::collections::HashSet<&&str> = glyphs.iter().collect();
318 assert_eq!(unique.len(), glyphs.len(), "glyphs must be distinguishable");
319 for glyph in glyphs {
320 assert_eq!(glyph.chars().count(), 1, "{glyph} must occupy one cell");
321 }
322 }
323
324 #[test]
325 fn interrupted_and_cancelled_both_read_as_cancelled_not_failed() {
326 for status in [AgentWorkerStatus::Cancelled, AgentWorkerStatus::Interrupted] {
327 let mut rec = record("stopped", 1_000);
328 rec.status = status;
329 rec.completed_at_ms = Some(2_000);
330 let rows = build_agent_roster(&[rec], 9_000);
331 assert_eq!(
332 rows[0].state,
333 RosterState::Cancelled,
334 "{status:?} is a stop, not a failure — a red ✗ would misreport it"
335 );
336 }
337 }
338
339 #[test]
340 fn formatters_never_round_a_real_count_down_to_nothing() {
341 assert_eq!(format_tokens(0), "0");
342 assert_eq!(format_tokens(1), "1");
343 assert_eq!(format_tokens(999), "999");
344 assert_eq!(format_tokens(1_000), "1.0k");
345 assert_eq!(format_tokens(96_300), "96.3k");
346 assert_eq!(format_tokens(1_200_000), "1.2M");
347
348 assert_eq!(format_duration(450), "450ms");
349 assert_eq!(format_duration(12_000), "12s");
350 assert_eq!(format_duration(209_000), "3m 29s");
351 assert_eq!(format_duration(3_600_000 + 120_000), "1h 2m");
352 }
353
354 #[test]
355 fn a_partial_totals_line_says_it_is_partial() {
356 let mut reported = record("builder", 2_000);
357 reported.usage = usage_of(96_300, 4_120);
358 let rows = build_agent_roster(&[record("scout", 1_000), reported], 9_000);
359 let text = render_agent_roster(&rows, "main");
360 assert!(
361 text.contains("receipts from 1 of 2 agents"),
362 "a bare total silently implies it covers every agent listed:\n{text}"
363 );
364
365 let mut both = record("second", 3_000);
366 both.usage = usage_of(1_000, 500);
367 let mut first = record("first", 1_000);
368 first.usage = usage_of(2_000, 500);
369 let full = build_agent_roster(&[first, both], 9_000);
370 let full_text = render_agent_roster(&full, "main");
371 assert!(full_text.contains("↓ 3.0k"), "{full_text}");
372 assert!(
373 !full_text.contains("receipts from"),
374 "a complete total needs no caveat:\n{full_text}"
375 );
376 }
377
378 #[test]
379 fn a_roster_with_no_receipts_at_all_says_so_rather_than_showing_zeros() {
380 let rows = build_agent_roster(&[record("a", 1_000), record("b", 2_000)], 9_000);
381 let text = render_agent_roster(&rows, "main");
382 assert!(
383 text.contains("2 agents · no usage receipts recorded"),
384 "{text}"
385 );
386 assert!(!text.contains("↓ 0"), "{text}");
387 }
388
389 /// Renders the whole thing once so the shape is reviewable in one place.
390 #[test]
391 fn rendered_roster_shape() {
392 let parent = record("refactor-workflow", 1_000);
393 let parent_run = parent.spec.run_id.clone();
394 let mut scout = record("scout", 2_000);
395 scout.parent_run_id = Some(parent_run.clone());
396 scout.status = AgentWorkerStatus::Completed;
397 scout.completed_at_ms = Some(120_000);
398 scout.usage = usage_of(96_300, 4_120);
399 let mut builder = record("builder", 3_000);
400 builder.parent_run_id = Some(parent_run);
401 builder.events.push_back(AgentWorkerEvent {
402 seq: 1,
403 worker_id: "builder".to_string(),
404 status: AgentWorkerStatus::RunningTool,
405 timestamp_ms: 4_000,
406 message: None,
407 step: Some(7),
408 tool_name: Some("apply_patch".to_string()),
409 });
410 builder.usage = usage_of(210_400, 18_900);
411
412 let rows = build_agent_roster(&[parent, scout, builder], 212_000);
413 let text = render_agent_roster(&rows, "main");
414 assert!(text.contains("1/2 agents done"), "{text}");
415 assert!(text.contains("step 7 · apply_patch"), "{text}");
416 assert!(text.contains("↓ 306.7k"), "{text}");
417 }
418
419 // === #5906: a parked husk is not an agent waiting for input ===
420
421 /// A child parked at the parent's turn end settles as `WaitingForUser` like a
422 /// child that really asked a question. Only `parked_at_turn_end` separates
423 /// them, and the rail has to read it or it prints the same row for both.
424 #[test]
425 fn a_parked_record_is_its_own_roster_state_not_waiting() {
426 let mut parked = record("parked_child", 1_000);
427 parked.status = AgentWorkerStatus::WaitingForUser;
428 parked.parked_at_turn_end = true;
429
430 let mut asked = record("asking_child", 2_000);
431 asked.status = AgentWorkerStatus::WaitingForUser;
432
433 let rows = build_agent_roster(&[parked, asked], 5_000);
434 let parked_row = rows
435 .iter()
436 .find(|row| row.worker_id == "parked_child")
437 .expect("parked row");
438 let asked_row = rows
439 .iter()
440 .find(|row| row.worker_id == "asking_child")
441 .expect("asking row");
442
443 assert_eq!(parked_row.state, RosterState::Parked);
444 assert_eq!(
445 asked_row.state,
446 RosterState::Waiting,
447 "a child that genuinely asked must keep the answerable state"
448 );
449 assert_ne!(parked_row.state.glyph(), asked_row.state.glyph());
450 assert!(
451 !parked_row.state.is_terminal(),
452 "parked work is unfinished, not settled-done"
453 );
454 }
455
456 /// The rail is otherwise oldest-first, but a parked husk is exactly the row an
457 /// operator must not have to scan past to find live work.
458 #[test]
459 fn parked_husks_sort_below_live_and_waiting_agents() {
460 let mut parked = record("aaa_parked", 1_000);
461 parked.status = AgentWorkerStatus::WaitingForUser;
462 parked.parked_at_turn_end = true;
463
464 let running = record("bbb_running", 2_000);
465
466 let mut waiting = record("ccc_waiting", 3_000);
467 waiting.status = AgentWorkerStatus::WaitingForUser;
468
469 let rows = build_agent_roster(&[parked, running, waiting], 9_000);
470 let order: Vec<&str> = rows.iter().map(|row| row.worker_id.as_str()).collect();
471 assert_eq!(
472 order,
473 vec!["bbb_running", "ccc_waiting", "aaa_parked"],
474 "the parked husk sinks below live and answerable rows despite being oldest"
475 );
476 }
477
478 /// Re-dispatch clears the flag on the record (#5921); the rail must follow it
479 /// back rather than latching a row as parked forever.
480 #[test]
481 fn a_re_dispatched_record_stops_reading_as_parked() {
482 let mut rec = record("resumed", 1_000);
483 rec.status = AgentWorkerStatus::WaitingForUser;
484 rec.parked_at_turn_end = true;
485 assert_eq!(
486 build_agent_roster(&[rec.clone()], 5_000)[0].state,
487 RosterState::Parked
488 );
489
490 rec.parked_at_turn_end = false;
491 rec.status = AgentWorkerStatus::RunningTool;
492 assert_eq!(
493 build_agent_roster(&[rec], 5_000)[0].state,
494 RosterState::Running
495 );
496 }
497
498 #[test]
499 fn result_headline_skips_scaffolding_and_returns_the_first_sentence() {
500 use codewhale_engine::agent_roster::result_headline;
501 // #6565: the first line of a report is usually a heading or a rule, and
502 // showing it hid the answer.
503 let report = "\n## Summary\n\n---\n```text\nThe docs audit found 3 stale links. Two are in README.md.\n```\n<codewhale:subagent.done>{\"event\":\"subagent.completed\"}</codewhale:subagent.done>";
504 assert_eq!(
505 result_headline(report).as_deref(),
506 Some("The docs audit found 3 stale links.")
507 );
508 // A dotted version or file name inside the sentence does not end it.
509 assert_eq!(
510 result_headline("Bumped to v0.10.1 in Cargo.toml and tagged it. Done.").as_deref(),
511 Some("Bumped to v0.10.1 in Cargo.toml and tagged it.")
512 );
513 assert_eq!(
514 result_headline("修复了两个问题。其余正常。").as_deref(),
515 Some("修复了两个问题。")
516 );
517 // Only headings: the first one, without its marks.
518 assert_eq!(
519 result_headline("# Only a heading\n## Another").as_deref(),
520 Some("Only a heading")
521 );
522 assert_eq!(result_headline(""), None);
523 assert_eq!(
524 result_headline(" \n***\n<codewhale:subagent.done>{}</codewhale:subagent.done>"),
525 None
526 );
527 }
528
529 #[test]
530 fn a_finished_worker_shows_its_result_not_its_last_tool() {
531 // #6565: the roster said `step 6 · read_file` for an agent that had
532 // already finished and reported. A settled row leads with the outcome.
533 let mut rec = record("auditor", 1_000);
534 rec.events.push_back(AgentWorkerEvent {
535 seq: 1,
536 worker_id: "auditor".to_string(),
537 status: AgentWorkerStatus::RunningTool,
538 timestamp_ms: 1_200,
539 message: None,
540 step: Some(6),
541 tool_name: Some("read_file".to_string()),
542 });
543 let long_tail = "detail ".repeat(400);
544 rec.status = AgentWorkerStatus::Completed;
545 rec.completed_at_ms = Some(1_900);
546 rec.result_summary = Some(format!(
547 "## Summary\n\nThe docs audit found 3 stale links.\n\n{long_tail}\n<codewhale:subagent.done>{{}}</codewhale:subagent.done>"
548 ));
549 let rows = build_agent_roster(&[rec.clone()], 2_000);
550 assert_eq!(
551 rows[0].activity.as_deref(),
552 Some("The docs audit found 3 stale links.")
553 );
554 // The row keeps the whole answer for the focused view.
555 assert!(
556 rows[0]
557 .outcome
558 .as_deref()
559 .is_some_and(|outcome| outcome.contains(long_tail.trim_end()))
560 );
561
562 // Failed leads with the error; a live worker still shows its step and
563 // carries no outcome.
564 rec.status = AgentWorkerStatus::Failed;
565 rec.error = Some("provider returned 429".to_string());
566 let rows = build_agent_roster(&[rec.clone()], 2_000);
567 assert_eq!(rows[0].activity.as_deref(), Some("provider returned 429"));
568 assert_eq!(rows[0].outcome.as_deref(), Some("provider returned 429"));
569
570 rec.status = AgentWorkerStatus::RunningTool;
571 let rows = build_agent_roster(&[rec], 2_000);
572 assert_eq!(rows[0].activity.as_deref(), Some("step 6 · read_file"));
573 assert_eq!(rows[0].outcome, None);
574 }
575
576 #[test]
577 fn a_finished_worker_without_a_result_falls_back_to_its_last_step() {
578 let mut rec = record("quiet", 1_000);
579 rec.events.push_back(AgentWorkerEvent {
580 seq: 1,
581 worker_id: "quiet".to_string(),
582 status: AgentWorkerStatus::RunningTool,
583 timestamp_ms: 1_200,
584 message: None,
585 step: Some(2),
586 tool_name: Some("Grep".to_string()),
587 });
588 rec.status = AgentWorkerStatus::Completed;
589 rec.result_summary = Some(" \n".to_string());
590 let rows = build_agent_roster(&[rec], 2_000);
591 assert_eq!(rows[0].activity.as_deref(), Some("step 2 · Grep"));
592 assert_eq!(rows[0].outcome, None);
593 }
594
594 lines RUST