1use crate::events::{Event, SessionEventEnvelope};
22use crate::run_task::ExitCode;
23use crate::session::{Session, SessionStatus, TranscriptRecord};
24use crate::workstreams::{WorkstreamId, WorkstreamState};
25
26pub fn render_session_table(sessions: &[Session]) -> String {
37 if sessions.is_empty() {
38 return "(no sessions)".to_string();
39 }
40 let mut out =
41 String::from("ID STATUS AGENT TASK\n");
42 for s in sessions {
43 let agent = s.agent.as_deref().unwrap_or("-");
44 let task_preview = truncate(&s.task, 40);
45 out.push_str(&format!(
46 "{:<38}{:<11}{:<16}{}\n",
47 s.id,
48 s.status.as_str(),
49 truncate(agent, 15),
50 task_preview
51 ));
52 }
53 out.pop(); out
55}
56
57pub fn render_event_line(envelope: &SessionEventEnvelope) -> String {
70 let ts = envelope.at.format("%H:%M:%S");
71 let detail = match &envelope.event {
72 Event::SessionStarted { project, .. } => format!("session started (project: {project})"),
73 Event::SessionStatusChanged { status, .. } => format!("status -> {status}"),
74 Event::SessionDone { status, .. } => format!("done ({status})"),
75 Event::SessionCancelled { .. } => "cancelled".to_string(),
76 Event::ToolStarted {
79 agent,
80 tool,
81 args_preview,
82 ..
83 } => format!("tool_started [{agent}] {tool} {args_preview}"),
84 Event::ToolFinished {
85 agent,
86 tool,
87 success,
88 result_preview,
89 ..
90 } => format!(
91 "tool_finished [{agent}] {tool} {} {result_preview}",
92 if *success { "ok" } else { "error" }
93 ),
94 Event::ToolError {
95 agent, tool, error, ..
96 } => format!("tool_error [{agent}] {tool} {error}"),
97 Event::SearchPerformed {
98 agent,
99 lane,
100 query,
101 hit_count,
102 latency_ms,
103 ..
104 } => format!(
105 "search [{agent}] {lane} \"{query}\" {} hits {latency_ms}ms",
106 hit_count.map_or_else(|| "?".to_string(), |c| c.to_string())
107 ),
108 Event::MemoryRecalled {
109 agent,
110 query,
111 results,
112 ..
113 } => format!(
114 "recall [{agent}] \"{query}\" {} injected / {} recalled",
115 results.iter().filter(|r| r.injected).count(),
116 results.len()
117 ),
118 Event::Message { text, .. } => text.clone(),
119 Event::Log { level, message, .. } => format!("[{level}] {message}"),
120 Event::Progress {
121 message, percent, ..
122 } => match percent {
123 Some(p) => format!("{message} ({p:.0}%)"),
124 None => message.clone(),
125 },
126 _ => format!("[{}]", envelope.kind),
127 };
128 format!("[{ts}] {detail}")
129}
130
131pub fn render_transcript_human(record: &TranscriptRecord) -> String {
143 if record.turns.is_empty() {
144 return format!(
145 "session {} has not run a task yet (no transcript)",
146 record.session_id
147 );
148 }
149 let mut out = String::new();
150 for turn in &record.turns {
151 out.push_str(&format!("--- {} ({}) ---\n", turn.role, turn.model));
152 if !turn.text.is_empty() {
153 out.push_str(&turn.text);
154 out.push('\n');
155 }
156 if !turn.tool_calls.is_empty() {
157 out.push_str(&format!("tool calls: {}\n", turn.tool_calls.join(", ")));
158 }
159 }
160 out.push_str(&format!(
161 "\ntotal: {} prompt + {} completion tokens, cost: {}\n",
162 record.usage.prompt_tokens,
163 record.usage.completion_tokens,
164 record
165 .cost_usd
166 .map(|c| format!("${c:.4}"))
167 .unwrap_or_else(|| "unknown".to_string())
168 ));
169 out.pop();
170 out
171}
172
173#[derive(Debug, serde::Deserialize)]
189pub struct WorkstreamRow {
190 pub id: WorkstreamId,
191 #[serde(default)]
192 pub name: String,
193 pub state: WorkstreamState,
194 #[serde(default)]
195 pub session_ids: Vec<String>,
196 pub updated_at: chrono::DateTime<chrono::Utc>,
197}
198
199pub fn render_workstream_table(rows: &[WorkstreamRow]) -> String {
220 if rows.is_empty() {
221 return "(no workstreams)".to_string();
222 }
223 let mut out = String::from(" ID STATE SESSIONS UPDATED NAME\n");
224 for r in rows {
225 let marker = if r.state == WorkstreamState::Active {
226 '*'
227 } else {
228 ' '
229 };
230 let id_prefix: String = r.id.to_string().chars().take(8).collect();
231 let name = if r.name.is_empty() {
232 "(untitled)"
233 } else {
234 &r.name
235 };
236 out.push_str(&format!(
237 "{marker} {:<9} {:<7} {:<9} {:<9} {}\n",
238 id_prefix,
239 r.state.to_string(),
240 r.session_ids.len(),
241 humanize_age(r.updated_at),
242 truncate(name, 40),
243 ));
244 }
245 out.pop(); out
247}
248
249fn humanize_age(at: chrono::DateTime<chrono::Utc>) -> String {
259 let secs = chrono::Utc::now()
260 .signed_duration_since(at)
261 .num_seconds()
262 .max(0);
263 if secs < 60 {
264 "just now".to_string()
265 } else if secs < 3_600 {
266 format!("{}m ago", secs / 60)
267 } else if secs < 86_400 {
268 format!("{}h ago", secs / 3_600)
269 } else if secs < 30 * 86_400 {
270 format!("{}d ago", secs / 86_400)
271 } else {
272 format!("{}w ago", secs / (7 * 86_400))
273 }
274}
275
276pub fn exit_code_for_status(status: SessionStatus) -> ExitCode {
294 match status {
295 SessionStatus::Finished => ExitCode::Success,
296 SessionStatus::Cancelled | SessionStatus::Failed => ExitCode::RunFailure,
297 SessionStatus::DeadlineExceeded => ExitCode::DeadlineExceeded,
298 SessionStatus::TurnCapExceeded => ExitCode::Partial,
299 SessionStatus::Created | SessionStatus::Running => ExitCode::RunFailure,
300 }
301}
302
303fn truncate(s: &str, max: usize) -> String {
305 if s.chars().count() <= max {
306 s.to_string()
307 } else {
308 let mut out: String = s.chars().take(max.saturating_sub(1)).collect();
309 out.push('…');
310 out
311 }
312}
313
314#[cfg(test)]
315mod tests {
316 use super::*;
317 use crate::perf::TokenUsage;
318 use crate::run_task::TurnRecord;
319 use chrono::Utc;
320
321 fn session(id: &str, status: SessionStatus) -> Session {
322 Session {
323 id: id.to_string(),
324 task: "do the thing".to_string(),
325 agent: Some("pm".to_string()),
326 project: None,
327 binding: crate::binding::ProjectBinding::None,
328 status,
329 created_at: Utc::now(),
330 mode: None,
331 workstream_id: None,
332 result: None,
333 no_delegate: false,
334 }
335 }
336
337 #[test]
338 fn render_session_table_lists_every_session() {
339 let sessions = vec![
340 session("s-1", SessionStatus::Running),
341 session("s-2", SessionStatus::Finished),
342 ];
343 let table = render_session_table(&sessions);
344 assert!(table.contains("s-1"));
345 assert!(table.contains("running"));
346 assert!(table.contains("s-2"));
347 assert!(table.contains("finished"));
348 }
349
350 #[test]
351 fn render_session_table_handles_empty_list() {
352 assert_eq!(render_session_table(&[]), "(no sessions)");
353 }
354
355 fn envelope(event: Event) -> SessionEventEnvelope {
356 SessionEventEnvelope::new("s-1".to_string(), 1, Utc::now(), event)
357 }
358
359 #[test]
360 fn render_event_line_covers_key_variants() {
361 let line = render_event_line(&envelope(Event::ToolStarted {
362 session_id: "s-1".to_string(),
363 agent: "python-engineer".to_string(),
364 agent_id: "eng-1".to_string(),
365 tool: "bash".to_string(),
366 call_id: "c1".to_string(),
367 args_preview: "echo hi".to_string(),
368 }));
369 assert!(line.contains("tool_started"));
370 assert!(line.contains("bash"));
371 assert!(line.contains("echo hi"));
372 assert!(
373 line.contains("[python-engineer]"),
374 "an attached CLI must show WHO made the call: {line}"
375 );
376
377 let line = render_event_line(&envelope(Event::SearchPerformed {
380 session_id: "s-1".to_string(),
381 agent: "python-engineer".to_string(),
382 agent_id: "eng-1".to_string(),
383 lane: "lexical".to_string(),
384 query: "where is auth".to_string(),
385 hit_count: Some(3),
386 hits: vec![],
387 latency_ms: 42,
388 }));
389 assert!(line.contains("[python-engineer]"), "{line}");
390 assert!(line.contains("lexical"), "the REAL routed lane: {line}");
391 assert!(line.contains("3 hits"), "{line}");
392
393 let line = render_event_line(&envelope(Event::MemoryRecalled {
394 session_id: "s-1".to_string(),
395 agent: "pm".to_string(),
396 agent_id: "pm-1".to_string(),
397 query: "pkce".to_string(),
398 results: vec![
399 crate::events::RecalledMemory {
400 score: 0.9,
401 injected: true,
402 text: "injected memory".to_string(),
403 run_id: None,
404 },
405 crate::events::RecalledMemory {
406 score: 0.41,
407 injected: false,
408 text: "held-back memory".to_string(),
409 run_id: None,
410 },
411 ],
412 }));
413 assert!(
414 line.contains("1 injected / 2 recalled"),
415 "the injected/held-back split is the point: {line}"
416 );
417
418 let line = render_event_line(&envelope(Event::SessionDone {
419 session_id: "s-1".to_string(),
420 status: "finished".to_string(),
421 }));
422 assert!(line.contains("done (finished)"));
423 }
424
425 #[test]
426 fn render_event_line_falls_back_for_unknown_kind() {
427 let line = render_event_line(&envelope(Event::Ping));
428 assert!(line.contains("[ping]"));
429 }
430
431 #[test]
432 fn render_transcript_human_lists_turns_and_totals() {
433 let record = TranscriptRecord {
434 session_id: "s-1".to_string(),
435 turns: vec![TurnRecord {
436 role: "pm".to_string(),
437 model: "openai/gpt-4o-mini".to_string(),
438 text: "done".to_string(),
439 tool_calls: vec!["delegate_to_agent".to_string()],
440 ran_test_command: false,
441 usage: TokenUsage::new(10, 5, 0, 0),
442 }],
443 usage: TokenUsage::new(10, 5, 0, 0),
444 cost_usd: Some(0.01),
445 mode: Some(crate::mode::HarnessMode::DailyDriver),
446 compaction_events: 0,
447 goals: vec![],
448 memory_durability: crate::session::MemoryDurabilityStatus::default(),
449 };
450 let out = render_transcript_human(&record);
451 assert!(out.contains("pm"));
452 assert!(out.contains("done"));
453 assert!(out.contains("delegate_to_agent"));
454 assert!(out.contains("$0.0100"));
455 }
456
457 #[test]
458 fn render_transcript_human_handles_never_run_session() {
459 let record = TranscriptRecord {
460 session_id: "s-1".to_string(),
461 turns: vec![],
462 usage: TokenUsage::default(),
463 cost_usd: None,
464 mode: None,
465 compaction_events: 0,
466 goals: vec![],
467 memory_durability: crate::session::MemoryDurabilityStatus::default(),
468 };
469 let out = render_transcript_human(&record);
470 assert!(out.contains("s-1"));
471 assert!(out.contains("has not run"));
472 }
473
474 #[test]
475 fn render_workstream_table_marks_the_active_row() {
476 use uuid::Uuid;
477
478 let active_id =
479 WorkstreamId(Uuid::parse_str("a1b2c3d4-e5f6-4748-9a0b-1c2d3e4f5a6b").unwrap());
480 let idle_id =
481 WorkstreamId(Uuid::parse_str("b2c3d4e5-f6a1-4748-9a0b-1c2d3e4f5a6b").unwrap());
482 let rows = vec![
483 WorkstreamRow {
484 id: active_id,
485 name: "Token rotation hardening".to_string(),
486 state: WorkstreamState::Active,
487 session_ids: vec!["s-1".to_string(), "s-2".to_string()],
488 updated_at: Utc::now(),
489 },
490 WorkstreamRow {
491 id: idle_id,
492 name: String::new(),
493 state: WorkstreamState::Idle,
494 session_ids: vec![],
495 updated_at: Utc::now() - chrono::Duration::hours(2),
496 },
497 ];
498 let table = render_workstream_table(&rows);
499 assert!(
500 table.contains('*'),
501 "active row must carry the marker: {table}"
502 );
503 assert!(
504 table.contains("a1b2c3d4"),
505 "expected the 8-char id prefix: {table}"
506 );
507 assert!(table.contains("active"));
508 assert!(table.contains("Token rotation hardening"));
509 assert!(
510 table.contains("(untitled)"),
511 "an empty name must render a placeholder: {table}"
512 );
513 assert!(
514 table.contains("2h ago"),
515 "expected a humanized age: {table}"
516 );
517 assert!(
518 table.contains('2'),
519 "active row's session count must be 2: {table}"
520 );
521 }
522
523 #[test]
524 fn render_workstream_table_handles_empty_list() {
525 assert_eq!(render_workstream_table(&[]), "(no workstreams)");
526 }
527
528 #[test]
529 fn humanize_age_buckets_common_durations() {
530 assert_eq!(humanize_age(Utc::now()), "just now");
531 assert_eq!(
532 humanize_age(Utc::now() - chrono::Duration::minutes(5)),
533 "5m ago"
534 );
535 assert_eq!(
536 humanize_age(Utc::now() - chrono::Duration::hours(3)),
537 "3h ago"
538 );
539 assert_eq!(
540 humanize_age(Utc::now() - chrono::Duration::days(2)),
541 "2d ago"
542 );
543 assert_eq!(
544 humanize_age(Utc::now() - chrono::Duration::days(45)),
545 "6w ago"
546 );
547 }
548
549 #[test]
550 fn exit_code_for_status_maps_terminal_states() {
551 assert_eq!(
552 exit_code_for_status(SessionStatus::Finished).code(),
553 ExitCode::Success.code()
554 );
555 assert_eq!(
556 exit_code_for_status(SessionStatus::Cancelled).code(),
557 ExitCode::RunFailure.code()
558 );
559 assert_eq!(
560 exit_code_for_status(SessionStatus::Failed).code(),
561 ExitCode::RunFailure.code()
562 );
563 assert_eq!(
564 exit_code_for_status(SessionStatus::DeadlineExceeded).code(),
565 ExitCode::DeadlineExceeded.code()
566 );
567 assert_eq!(
568 exit_code_for_status(SessionStatus::TurnCapExceeded).code(),
569 ExitCode::Partial.code(),
570 "a turn-cap-exceeded (resumable) session must exit Partial, not RunFailure (#3888)"
571 );
572 }
573}