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 }
333 }
334
335 #[test]
336 fn render_session_table_lists_every_session() {
337 let sessions = vec![
338 session("s-1", SessionStatus::Running),
339 session("s-2", SessionStatus::Finished),
340 ];
341 let table = render_session_table(&sessions);
342 assert!(table.contains("s-1"));
343 assert!(table.contains("running"));
344 assert!(table.contains("s-2"));
345 assert!(table.contains("finished"));
346 }
347
348 #[test]
349 fn render_session_table_handles_empty_list() {
350 assert_eq!(render_session_table(&[]), "(no sessions)");
351 }
352
353 fn envelope(event: Event) -> SessionEventEnvelope {
354 SessionEventEnvelope::new("s-1".to_string(), 1, Utc::now(), event)
355 }
356
357 #[test]
358 fn render_event_line_covers_key_variants() {
359 let line = render_event_line(&envelope(Event::ToolStarted {
360 session_id: "s-1".to_string(),
361 agent: "python-engineer".to_string(),
362 agent_id: "eng-1".to_string(),
363 tool: "bash".to_string(),
364 call_id: "c1".to_string(),
365 args_preview: "echo hi".to_string(),
366 }));
367 assert!(line.contains("tool_started"));
368 assert!(line.contains("bash"));
369 assert!(line.contains("echo hi"));
370 assert!(
371 line.contains("[python-engineer]"),
372 "an attached CLI must show WHO made the call: {line}"
373 );
374
375 let line = render_event_line(&envelope(Event::SearchPerformed {
378 session_id: "s-1".to_string(),
379 agent: "python-engineer".to_string(),
380 agent_id: "eng-1".to_string(),
381 lane: "lexical".to_string(),
382 query: "where is auth".to_string(),
383 hit_count: Some(3),
384 hits: vec![],
385 latency_ms: 42,
386 }));
387 assert!(line.contains("[python-engineer]"), "{line}");
388 assert!(line.contains("lexical"), "the REAL routed lane: {line}");
389 assert!(line.contains("3 hits"), "{line}");
390
391 let line = render_event_line(&envelope(Event::MemoryRecalled {
392 session_id: "s-1".to_string(),
393 agent: "pm".to_string(),
394 agent_id: "pm-1".to_string(),
395 query: "pkce".to_string(),
396 results: vec![
397 crate::events::RecalledMemory {
398 score: 0.9,
399 injected: true,
400 text: "injected memory".to_string(),
401 run_id: None,
402 },
403 crate::events::RecalledMemory {
404 score: 0.41,
405 injected: false,
406 text: "held-back memory".to_string(),
407 run_id: None,
408 },
409 ],
410 }));
411 assert!(
412 line.contains("1 injected / 2 recalled"),
413 "the injected/held-back split is the point: {line}"
414 );
415
416 let line = render_event_line(&envelope(Event::SessionDone {
417 session_id: "s-1".to_string(),
418 status: "finished".to_string(),
419 }));
420 assert!(line.contains("done (finished)"));
421 }
422
423 #[test]
424 fn render_event_line_falls_back_for_unknown_kind() {
425 let line = render_event_line(&envelope(Event::Ping));
426 assert!(line.contains("[ping]"));
427 }
428
429 #[test]
430 fn render_transcript_human_lists_turns_and_totals() {
431 let record = TranscriptRecord {
432 session_id: "s-1".to_string(),
433 turns: vec![TurnRecord {
434 role: "pm".to_string(),
435 model: "openai/gpt-4o-mini".to_string(),
436 text: "done".to_string(),
437 tool_calls: vec!["delegate_to_agent".to_string()],
438 ran_test_command: false,
439 usage: TokenUsage::new(10, 5, 0, 0),
440 }],
441 usage: TokenUsage::new(10, 5, 0, 0),
442 cost_usd: Some(0.01),
443 mode: Some(crate::mode::HarnessMode::DailyDriver),
444 compaction_events: 0,
445 goals: vec![],
446 memory_durability: crate::session::MemoryDurabilityStatus::default(),
447 };
448 let out = render_transcript_human(&record);
449 assert!(out.contains("pm"));
450 assert!(out.contains("done"));
451 assert!(out.contains("delegate_to_agent"));
452 assert!(out.contains("$0.0100"));
453 }
454
455 #[test]
456 fn render_transcript_human_handles_never_run_session() {
457 let record = TranscriptRecord {
458 session_id: "s-1".to_string(),
459 turns: vec![],
460 usage: TokenUsage::default(),
461 cost_usd: None,
462 mode: None,
463 compaction_events: 0,
464 goals: vec![],
465 memory_durability: crate::session::MemoryDurabilityStatus::default(),
466 };
467 let out = render_transcript_human(&record);
468 assert!(out.contains("s-1"));
469 assert!(out.contains("has not run"));
470 }
471
472 #[test]
473 fn render_workstream_table_marks_the_active_row() {
474 use uuid::Uuid;
475
476 let active_id =
477 WorkstreamId(Uuid::parse_str("a1b2c3d4-e5f6-4748-9a0b-1c2d3e4f5a6b").unwrap());
478 let idle_id =
479 WorkstreamId(Uuid::parse_str("b2c3d4e5-f6a1-4748-9a0b-1c2d3e4f5a6b").unwrap());
480 let rows = vec![
481 WorkstreamRow {
482 id: active_id,
483 name: "Token rotation hardening".to_string(),
484 state: WorkstreamState::Active,
485 session_ids: vec!["s-1".to_string(), "s-2".to_string()],
486 updated_at: Utc::now(),
487 },
488 WorkstreamRow {
489 id: idle_id,
490 name: String::new(),
491 state: WorkstreamState::Idle,
492 session_ids: vec![],
493 updated_at: Utc::now() - chrono::Duration::hours(2),
494 },
495 ];
496 let table = render_workstream_table(&rows);
497 assert!(
498 table.contains('*'),
499 "active row must carry the marker: {table}"
500 );
501 assert!(
502 table.contains("a1b2c3d4"),
503 "expected the 8-char id prefix: {table}"
504 );
505 assert!(table.contains("active"));
506 assert!(table.contains("Token rotation hardening"));
507 assert!(
508 table.contains("(untitled)"),
509 "an empty name must render a placeholder: {table}"
510 );
511 assert!(
512 table.contains("2h ago"),
513 "expected a humanized age: {table}"
514 );
515 assert!(
516 table.contains('2'),
517 "active row's session count must be 2: {table}"
518 );
519 }
520
521 #[test]
522 fn render_workstream_table_handles_empty_list() {
523 assert_eq!(render_workstream_table(&[]), "(no workstreams)");
524 }
525
526 #[test]
527 fn humanize_age_buckets_common_durations() {
528 assert_eq!(humanize_age(Utc::now()), "just now");
529 assert_eq!(
530 humanize_age(Utc::now() - chrono::Duration::minutes(5)),
531 "5m ago"
532 );
533 assert_eq!(
534 humanize_age(Utc::now() - chrono::Duration::hours(3)),
535 "3h ago"
536 );
537 assert_eq!(
538 humanize_age(Utc::now() - chrono::Duration::days(2)),
539 "2d ago"
540 );
541 assert_eq!(
542 humanize_age(Utc::now() - chrono::Duration::days(45)),
543 "6w ago"
544 );
545 }
546
547 #[test]
548 fn exit_code_for_status_maps_terminal_states() {
549 assert_eq!(
550 exit_code_for_status(SessionStatus::Finished).code(),
551 ExitCode::Success.code()
552 );
553 assert_eq!(
554 exit_code_for_status(SessionStatus::Cancelled).code(),
555 ExitCode::RunFailure.code()
556 );
557 assert_eq!(
558 exit_code_for_status(SessionStatus::Failed).code(),
559 ExitCode::RunFailure.code()
560 );
561 assert_eq!(
562 exit_code_for_status(SessionStatus::DeadlineExceeded).code(),
563 ExitCode::DeadlineExceeded.code()
564 );
565 assert_eq!(
566 exit_code_for_status(SessionStatus::TurnCapExceeded).code(),
567 ExitCode::Partial.code(),
568 "a turn-cap-exceeded (resumable) session must exit Partial, not RunFailure (#3888)"
569 );
570 }
571}