use crate::events::{Event, SessionEventEnvelope};
use crate::run_task::ExitCode;
use crate::session::{Session, SessionStatus, TranscriptRecord};
use crate::workstreams::{WorkstreamId, WorkstreamState};
pub fn render_session_table(sessions: &[Session]) -> String {
if sessions.is_empty() {
return "(no sessions)".to_string();
}
let mut out =
String::from("ID STATUS AGENT TASK\n");
for s in sessions {
let agent = s.agent.as_deref().unwrap_or("-");
let task_preview = truncate(&s.task, 40);
out.push_str(&format!(
"{:<38}{:<11}{:<16}{}\n",
s.id,
s.status.as_str(),
truncate(agent, 15),
task_preview
));
}
out.pop(); out
}
pub fn render_event_line(envelope: &SessionEventEnvelope) -> String {
let ts = envelope.at.format("%H:%M:%S");
let detail = match &envelope.event {
Event::SessionStarted { project, .. } => format!("session started (project: {project})"),
Event::SessionStatusChanged { status, .. } => format!("status -> {status}"),
Event::SessionDone { status, .. } => format!("done ({status})"),
Event::SessionCancelled { .. } => "cancelled".to_string(),
Event::ToolStarted {
agent,
tool,
args_preview,
..
} => format!("tool_started [{agent}] {tool} {args_preview}"),
Event::ToolFinished {
agent,
tool,
success,
result_preview,
..
} => format!(
"tool_finished [{agent}] {tool} {} {result_preview}",
if *success { "ok" } else { "error" }
),
Event::ToolError {
agent, tool, error, ..
} => format!("tool_error [{agent}] {tool} {error}"),
Event::SearchPerformed {
agent,
lane,
query,
hit_count,
latency_ms,
..
} => format!(
"search [{agent}] {lane} \"{query}\" {} hits {latency_ms}ms",
hit_count.map_or_else(|| "?".to_string(), |c| c.to_string())
),
Event::MemoryRecalled {
agent,
query,
results,
..
} => format!(
"recall [{agent}] \"{query}\" {} injected / {} recalled",
results.iter().filter(|r| r.injected).count(),
results.len()
),
Event::Message { text, .. } => text.clone(),
Event::Log { level, message, .. } => format!("[{level}] {message}"),
Event::Progress {
message, percent, ..
} => match percent {
Some(p) => format!("{message} ({p:.0}%)"),
None => message.clone(),
},
_ => format!("[{}]", envelope.kind),
};
format!("[{ts}] {detail}")
}
pub fn render_transcript_human(record: &TranscriptRecord) -> String {
if record.turns.is_empty() {
return format!(
"session {} has not run a task yet (no transcript)",
record.session_id
);
}
let mut out = String::new();
for turn in &record.turns {
out.push_str(&format!("--- {} ({}) ---\n", turn.role, turn.model));
if !turn.text.is_empty() {
out.push_str(&turn.text);
out.push('\n');
}
if !turn.tool_calls.is_empty() {
out.push_str(&format!("tool calls: {}\n", turn.tool_calls.join(", ")));
}
}
out.push_str(&format!(
"\ntotal: {} prompt + {} completion tokens, cost: {}\n",
record.usage.prompt_tokens,
record.usage.completion_tokens,
record
.cost_usd
.map(|c| format!("${c:.4}"))
.unwrap_or_else(|| "unknown".to_string())
));
out.pop();
out
}
#[derive(Debug, serde::Deserialize)]
pub struct WorkstreamRow {
pub id: WorkstreamId,
#[serde(default)]
pub name: String,
pub state: WorkstreamState,
#[serde(default)]
pub session_ids: Vec<String>,
pub updated_at: chrono::DateTime<chrono::Utc>,
}
pub fn render_workstream_table(rows: &[WorkstreamRow]) -> String {
if rows.is_empty() {
return "(no workstreams)".to_string();
}
let mut out = String::from(" ID STATE SESSIONS UPDATED NAME\n");
for r in rows {
let marker = if r.state == WorkstreamState::Active {
'*'
} else {
' '
};
let id_prefix: String = r.id.to_string().chars().take(8).collect();
let name = if r.name.is_empty() {
"(untitled)"
} else {
&r.name
};
out.push_str(&format!(
"{marker} {:<9} {:<7} {:<9} {:<9} {}\n",
id_prefix,
r.state.to_string(),
r.session_ids.len(),
humanize_age(r.updated_at),
truncate(name, 40),
));
}
out.pop(); out
}
fn humanize_age(at: chrono::DateTime<chrono::Utc>) -> String {
let secs = chrono::Utc::now()
.signed_duration_since(at)
.num_seconds()
.max(0);
if secs < 60 {
"just now".to_string()
} else if secs < 3_600 {
format!("{}m ago", secs / 60)
} else if secs < 86_400 {
format!("{}h ago", secs / 3_600)
} else if secs < 30 * 86_400 {
format!("{}d ago", secs / 86_400)
} else {
format!("{}w ago", secs / (7 * 86_400))
}
}
pub fn exit_code_for_status(status: SessionStatus) -> ExitCode {
match status {
SessionStatus::Finished => ExitCode::Success,
SessionStatus::Cancelled | SessionStatus::Failed => ExitCode::RunFailure,
SessionStatus::DeadlineExceeded => ExitCode::DeadlineExceeded,
SessionStatus::TurnCapExceeded => ExitCode::Partial,
SessionStatus::Created | SessionStatus::Running => ExitCode::RunFailure,
}
}
fn truncate(s: &str, max: usize) -> String {
if s.chars().count() <= max {
s.to_string()
} else {
let mut out: String = s.chars().take(max.saturating_sub(1)).collect();
out.push('…');
out
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::perf::TokenUsage;
use crate::run_task::TurnRecord;
use chrono::Utc;
fn session(id: &str, status: SessionStatus) -> Session {
Session {
id: id.to_string(),
task: "do the thing".to_string(),
agent: Some("pm".to_string()),
project: None,
binding: crate::binding::ProjectBinding::None,
status,
created_at: Utc::now(),
mode: None,
workstream_id: None,
result: None,
no_delegate: false,
}
}
#[test]
fn render_session_table_lists_every_session() {
let sessions = vec![
session("s-1", SessionStatus::Running),
session("s-2", SessionStatus::Finished),
];
let table = render_session_table(&sessions);
assert!(table.contains("s-1"));
assert!(table.contains("running"));
assert!(table.contains("s-2"));
assert!(table.contains("finished"));
}
#[test]
fn render_session_table_handles_empty_list() {
assert_eq!(render_session_table(&[]), "(no sessions)");
}
fn envelope(event: Event) -> SessionEventEnvelope {
SessionEventEnvelope::new("s-1".to_string(), 1, Utc::now(), event)
}
#[test]
fn render_event_line_covers_key_variants() {
let line = render_event_line(&envelope(Event::ToolStarted {
session_id: "s-1".to_string(),
agent: "python-engineer".to_string(),
agent_id: "eng-1".to_string(),
tool: "bash".to_string(),
call_id: "c1".to_string(),
args_preview: "echo hi".to_string(),
}));
assert!(line.contains("tool_started"));
assert!(line.contains("bash"));
assert!(line.contains("echo hi"));
assert!(
line.contains("[python-engineer]"),
"an attached CLI must show WHO made the call: {line}"
);
let line = render_event_line(&envelope(Event::SearchPerformed {
session_id: "s-1".to_string(),
agent: "python-engineer".to_string(),
agent_id: "eng-1".to_string(),
lane: "lexical".to_string(),
query: "where is auth".to_string(),
hit_count: Some(3),
hits: vec![],
latency_ms: 42,
}));
assert!(line.contains("[python-engineer]"), "{line}");
assert!(line.contains("lexical"), "the REAL routed lane: {line}");
assert!(line.contains("3 hits"), "{line}");
let line = render_event_line(&envelope(Event::MemoryRecalled {
session_id: "s-1".to_string(),
agent: "pm".to_string(),
agent_id: "pm-1".to_string(),
query: "pkce".to_string(),
results: vec![
crate::events::RecalledMemory {
score: 0.9,
injected: true,
text: "injected memory".to_string(),
run_id: None,
},
crate::events::RecalledMemory {
score: 0.41,
injected: false,
text: "held-back memory".to_string(),
run_id: None,
},
],
}));
assert!(
line.contains("1 injected / 2 recalled"),
"the injected/held-back split is the point: {line}"
);
let line = render_event_line(&envelope(Event::SessionDone {
session_id: "s-1".to_string(),
status: "finished".to_string(),
}));
assert!(line.contains("done (finished)"));
}
#[test]
fn render_event_line_falls_back_for_unknown_kind() {
let line = render_event_line(&envelope(Event::Ping));
assert!(line.contains("[ping]"));
}
#[test]
fn render_transcript_human_lists_turns_and_totals() {
let record = TranscriptRecord {
session_id: "s-1".to_string(),
turns: vec![TurnRecord {
role: "pm".to_string(),
model: "openai/gpt-4o-mini".to_string(),
text: "done".to_string(),
tool_calls: vec!["delegate_to_agent".to_string()],
ran_test_command: false,
usage: TokenUsage::new(10, 5, 0, 0),
}],
usage: TokenUsage::new(10, 5, 0, 0),
cost_usd: Some(0.01),
mode: Some(crate::mode::HarnessMode::DailyDriver),
compaction_events: 0,
goals: vec![],
memory_durability: crate::session::MemoryDurabilityStatus::default(),
};
let out = render_transcript_human(&record);
assert!(out.contains("pm"));
assert!(out.contains("done"));
assert!(out.contains("delegate_to_agent"));
assert!(out.contains("$0.0100"));
}
#[test]
fn render_transcript_human_handles_never_run_session() {
let record = TranscriptRecord {
session_id: "s-1".to_string(),
turns: vec![],
usage: TokenUsage::default(),
cost_usd: None,
mode: None,
compaction_events: 0,
goals: vec![],
memory_durability: crate::session::MemoryDurabilityStatus::default(),
};
let out = render_transcript_human(&record);
assert!(out.contains("s-1"));
assert!(out.contains("has not run"));
}
#[test]
fn render_workstream_table_marks_the_active_row() {
use uuid::Uuid;
let active_id =
WorkstreamId(Uuid::parse_str("a1b2c3d4-e5f6-4748-9a0b-1c2d3e4f5a6b").unwrap());
let idle_id =
WorkstreamId(Uuid::parse_str("b2c3d4e5-f6a1-4748-9a0b-1c2d3e4f5a6b").unwrap());
let rows = vec![
WorkstreamRow {
id: active_id,
name: "Token rotation hardening".to_string(),
state: WorkstreamState::Active,
session_ids: vec!["s-1".to_string(), "s-2".to_string()],
updated_at: Utc::now(),
},
WorkstreamRow {
id: idle_id,
name: String::new(),
state: WorkstreamState::Idle,
session_ids: vec![],
updated_at: Utc::now() - chrono::Duration::hours(2),
},
];
let table = render_workstream_table(&rows);
assert!(
table.contains('*'),
"active row must carry the marker: {table}"
);
assert!(
table.contains("a1b2c3d4"),
"expected the 8-char id prefix: {table}"
);
assert!(table.contains("active"));
assert!(table.contains("Token rotation hardening"));
assert!(
table.contains("(untitled)"),
"an empty name must render a placeholder: {table}"
);
assert!(
table.contains("2h ago"),
"expected a humanized age: {table}"
);
assert!(
table.contains('2'),
"active row's session count must be 2: {table}"
);
}
#[test]
fn render_workstream_table_handles_empty_list() {
assert_eq!(render_workstream_table(&[]), "(no workstreams)");
}
#[test]
fn humanize_age_buckets_common_durations() {
assert_eq!(humanize_age(Utc::now()), "just now");
assert_eq!(
humanize_age(Utc::now() - chrono::Duration::minutes(5)),
"5m ago"
);
assert_eq!(
humanize_age(Utc::now() - chrono::Duration::hours(3)),
"3h ago"
);
assert_eq!(
humanize_age(Utc::now() - chrono::Duration::days(2)),
"2d ago"
);
assert_eq!(
humanize_age(Utc::now() - chrono::Duration::days(45)),
"6w ago"
);
}
#[test]
fn exit_code_for_status_maps_terminal_states() {
assert_eq!(
exit_code_for_status(SessionStatus::Finished).code(),
ExitCode::Success.code()
);
assert_eq!(
exit_code_for_status(SessionStatus::Cancelled).code(),
ExitCode::RunFailure.code()
);
assert_eq!(
exit_code_for_status(SessionStatus::Failed).code(),
ExitCode::RunFailure.code()
);
assert_eq!(
exit_code_for_status(SessionStatus::DeadlineExceeded).code(),
ExitCode::DeadlineExceeded.code()
);
assert_eq!(
exit_code_for_status(SessionStatus::TurnCapExceeded).code(),
ExitCode::Partial.code(),
"a turn-cap-exceeded (resumable) session must exit Partial, not RunFailure (#3888)"
);
}
}