Skip to main content

trusty_code/cli_client/
render.rs

1//! Pure, unit-tested formatting for the `tcode` CLI's human-readable output
2//! (#2060).
3//!
4//! Why: every subcommand handler in the binary needs to turn a wire-shaped
5//! `Session`/`SessionEventEnvelope`/`TranscriptRecord` into something a
6//! terminal user can read. Keeping the formatting logic here (rather than
7//! inline `println!`s scattered across the binary's subcommand handlers)
8//! makes it independently unit-testable without spawning a subprocess, and
9//! keeps each handler a thin "call the client, print the result" wrapper.
10//! What: [`render_session_table`] (a fixed-width table for `session list`),
11//! [`render_event_line`] (one line per streamed [`SessionEventEnvelope`],
12//! used by `attach`/`run-task`), [`render_transcript_human`] (a readable
13//! turn-by-turn view for `transcript`), and [`exit_code_for_status`] (maps a
14//! terminal `SessionStatus` onto the SAME `run_task::ExitCode` values the
15//! legacy in-process `run-task` path already used, so scripts checking `$?`
16//! see a consistent contract regardless of which path produced the run).
17//! Test: `render::tests::*`.
18
19use crate::events::{Event, SessionEventEnvelope};
20use crate::run_task::ExitCode;
21use crate::session::{Session, SessionStatus, TranscriptRecord};
22
23/// Render a fixed-width table of sessions for `tcode session list`.
24///
25/// Why: `session.list`'s raw JSON is unreadable at a glance; operators want
26/// id/status/task/agent at one line each.
27/// What: one header line + one row per session, columns
28/// `ID | STATUS | AGENT | TASK` (task truncated to keep rows terminal-width
29/// friendly). An empty list renders a single explanatory line, not an empty
30/// string, so scripts piping through a pager see something.
31/// Test: `tests::render_session_table_lists_every_session`,
32/// `tests::render_session_table_handles_empty_list`.
33pub fn render_session_table(sessions: &[Session]) -> String {
34    if sessions.is_empty() {
35        return "(no sessions)".to_string();
36    }
37    let mut out =
38        String::from("ID                                    STATUS     AGENT           TASK\n");
39    for s in sessions {
40        let agent = s.agent.as_deref().unwrap_or("-");
41        let task_preview = truncate(&s.task, 40);
42        out.push_str(&format!(
43            "{:<38}{:<11}{:<16}{}\n",
44            s.id,
45            s.status.as_str(),
46            truncate(agent, 15),
47            task_preview
48        ));
49    }
50    out.pop(); // drop the trailing newline; callers add their own via println!
51    out
52}
53
54/// Render one line for a single streamed event, for `attach`/`run-task`.
55///
56/// Why: a human watching a live run wants a compact, timestamped narration
57/// — not the raw internally-tagged JSON.
58/// What: matches the handful of variants the M1 cut line actually produces
59/// (session lifecycle, tool lifecycle, generic message/log/progress) with a
60/// readable one-liner; anything else falls back to `[<kind>]` using the
61/// envelope's own `kind` string rather than an exhaustive match on
62/// [`Event`], so a future variant added elsewhere never breaks this
63/// function's compilation.
64/// Test: `tests::render_event_line_covers_key_variants`,
65/// `tests::render_event_line_falls_back_for_unknown_kind`.
66pub fn render_event_line(envelope: &SessionEventEnvelope) -> String {
67    let ts = envelope.at.format("%H:%M:%S");
68    let detail = match &envelope.event {
69        Event::SessionStarted { project, .. } => format!("session started (project: {project})"),
70        Event::SessionStatusChanged { status, .. } => format!("status -> {status}"),
71        Event::SessionDone { status, .. } => format!("done ({status})"),
72        Event::SessionCancelled { .. } => "cancelled".to_string(),
73        Event::ToolStarted {
74            tool, args_preview, ..
75        } => format!("tool_started  {tool}  {args_preview}"),
76        Event::ToolFinished {
77            tool,
78            success,
79            result_preview,
80            ..
81        } => format!(
82            "tool_finished {tool}  {} {result_preview}",
83            if *success { "ok" } else { "error" }
84        ),
85        Event::ToolError { tool, error, .. } => format!("tool_error    {tool}  {error}"),
86        Event::Message { text, .. } => text.clone(),
87        Event::Log { level, message, .. } => format!("[{level}] {message}"),
88        Event::Progress {
89            message, percent, ..
90        } => match percent {
91            Some(p) => format!("{message} ({p:.0}%)"),
92            None => message.clone(),
93        },
94        _ => format!("[{}]", envelope.kind),
95    };
96    format!("[{ts}] {detail}")
97}
98
99/// Render a `TranscriptRecord` as a readable turn-by-turn view for
100/// `tcode transcript` (human mode; `--json` bypasses this entirely and
101/// pretty-prints the raw result).
102///
103/// Why: a bare JSON dump of the transcript is hard to scan; a human wants
104/// "who said what, with which tools" plus the cost/usage summary.
105/// What: one block per turn (`role` header, prose if any, tool calls if
106/// any), then a trailing usage/cost summary line. A never-run session (empty
107/// `turns`) renders a single explanatory line rather than an empty string.
108/// Test: `tests::render_transcript_human_lists_turns_and_totals`,
109/// `tests::render_transcript_human_handles_never_run_session`.
110pub fn render_transcript_human(record: &TranscriptRecord) -> String {
111    if record.turns.is_empty() {
112        return format!(
113            "session {} has not run a task yet (no transcript)",
114            record.session_id
115        );
116    }
117    let mut out = String::new();
118    for turn in &record.turns {
119        out.push_str(&format!("--- {} ({}) ---\n", turn.role, turn.model));
120        if !turn.text.is_empty() {
121            out.push_str(&turn.text);
122            out.push('\n');
123        }
124        if !turn.tool_calls.is_empty() {
125            out.push_str(&format!("tool calls: {}\n", turn.tool_calls.join(", ")));
126        }
127    }
128    out.push_str(&format!(
129        "\ntotal: {} prompt + {} completion tokens, cost: {}\n",
130        record.usage.prompt_tokens,
131        record.usage.completion_tokens,
132        record
133            .cost_usd
134            .map(|c| format!("${c:.4}"))
135            .unwrap_or_else(|| "unknown".to_string())
136    ));
137    out.pop();
138    out
139}
140
141/// Map a terminal `SessionStatus` onto the CLI process exit code.
142///
143/// Why: `run-task` via the thin client and the legacy in-process
144/// `run-task` must agree on what a script checking `$?` sees.
145/// What: `Finished` -> `ExitCode::Success`; `Cancelled`/`Failed` ->
146/// `ExitCode::RunFailure`; `DeadlineExceeded` (#2207) -> its own distinct
147/// `ExitCode::DeadlineExceeded`, so a script can tell "timed out" from
148/// "errored" the same way the legacy path's `RunReport::exit` does;
149/// `Created`/`Running` (should never be passed here — the caller only calls
150/// this once a run has reached a terminal status) also map to `RunFailure`
151/// defensively rather than panicking.
152/// Test: `tests::exit_code_for_status_maps_terminal_states`.
153pub fn exit_code_for_status(status: SessionStatus) -> ExitCode {
154    match status {
155        SessionStatus::Finished => ExitCode::Success,
156        SessionStatus::Cancelled | SessionStatus::Failed => ExitCode::RunFailure,
157        SessionStatus::DeadlineExceeded => ExitCode::DeadlineExceeded,
158        SessionStatus::Created | SessionStatus::Running => ExitCode::RunFailure,
159    }
160}
161
162/// Truncate `s` to at most `max` chars, appending `…` when it was longer.
163fn truncate(s: &str, max: usize) -> String {
164    if s.chars().count() <= max {
165        s.to_string()
166    } else {
167        let mut out: String = s.chars().take(max.saturating_sub(1)).collect();
168        out.push('…');
169        out
170    }
171}
172
173#[cfg(test)]
174mod tests {
175    use super::*;
176    use crate::perf::TokenUsage;
177    use crate::run_task::TurnRecord;
178    use chrono::Utc;
179
180    fn session(id: &str, status: SessionStatus) -> Session {
181        Session {
182            id: id.to_string(),
183            task: "do the thing".to_string(),
184            agent: Some("pm".to_string()),
185            project: None,
186            status,
187            created_at: Utc::now(),
188            mode: None,
189        }
190    }
191
192    #[test]
193    fn render_session_table_lists_every_session() {
194        let sessions = vec![
195            session("s-1", SessionStatus::Running),
196            session("s-2", SessionStatus::Finished),
197        ];
198        let table = render_session_table(&sessions);
199        assert!(table.contains("s-1"));
200        assert!(table.contains("running"));
201        assert!(table.contains("s-2"));
202        assert!(table.contains("finished"));
203    }
204
205    #[test]
206    fn render_session_table_handles_empty_list() {
207        assert_eq!(render_session_table(&[]), "(no sessions)");
208    }
209
210    fn envelope(event: Event) -> SessionEventEnvelope {
211        SessionEventEnvelope::new("s-1".to_string(), 1, Utc::now(), event)
212    }
213
214    #[test]
215    fn render_event_line_covers_key_variants() {
216        let line = render_event_line(&envelope(Event::ToolStarted {
217            session_id: "s-1".to_string(),
218            tool: "bash".to_string(),
219            call_id: "c1".to_string(),
220            args_preview: "echo hi".to_string(),
221        }));
222        assert!(line.contains("tool_started"));
223        assert!(line.contains("bash"));
224        assert!(line.contains("echo hi"));
225
226        let line = render_event_line(&envelope(Event::SessionDone {
227            session_id: "s-1".to_string(),
228            status: "finished".to_string(),
229        }));
230        assert!(line.contains("done (finished)"));
231    }
232
233    #[test]
234    fn render_event_line_falls_back_for_unknown_kind() {
235        let line = render_event_line(&envelope(Event::Ping));
236        assert!(line.contains("[ping]"));
237    }
238
239    #[test]
240    fn render_transcript_human_lists_turns_and_totals() {
241        let record = TranscriptRecord {
242            session_id: "s-1".to_string(),
243            turns: vec![TurnRecord {
244                role: "pm".to_string(),
245                model: "openai/gpt-4o-mini".to_string(),
246                text: "done".to_string(),
247                tool_calls: vec!["delegate_to_agent".to_string()],
248                usage: TokenUsage::new(10, 5, 0, 0),
249            }],
250            usage: TokenUsage::new(10, 5, 0, 0),
251            cost_usd: Some(0.01),
252            mode: Some(crate::mode::HarnessMode::DailyDriver),
253        };
254        let out = render_transcript_human(&record);
255        assert!(out.contains("pm"));
256        assert!(out.contains("done"));
257        assert!(out.contains("delegate_to_agent"));
258        assert!(out.contains("$0.0100"));
259    }
260
261    #[test]
262    fn render_transcript_human_handles_never_run_session() {
263        let record = TranscriptRecord {
264            session_id: "s-1".to_string(),
265            turns: vec![],
266            usage: TokenUsage::default(),
267            cost_usd: None,
268            mode: None,
269        };
270        let out = render_transcript_human(&record);
271        assert!(out.contains("s-1"));
272        assert!(out.contains("has not run"));
273    }
274
275    #[test]
276    fn exit_code_for_status_maps_terminal_states() {
277        assert_eq!(
278            exit_code_for_status(SessionStatus::Finished).code(),
279            ExitCode::Success.code()
280        );
281        assert_eq!(
282            exit_code_for_status(SessionStatus::Cancelled).code(),
283            ExitCode::RunFailure.code()
284        );
285        assert_eq!(
286            exit_code_for_status(SessionStatus::Failed).code(),
287            ExitCode::RunFailure.code()
288        );
289        assert_eq!(
290            exit_code_for_status(SessionStatus::DeadlineExceeded).code(),
291            ExitCode::DeadlineExceeded.code()
292        );
293    }
294}