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`), [`render_workstream_table`] (a
14//! tmux-`list-sessions`-style table for `tcode workstream list`, #3296), and
15//! [`exit_code_for_status`] (maps a terminal `SessionStatus` onto the SAME
16//! `run_task::ExitCode` values the legacy in-process `run-task` path already
17//! used, so scripts checking `$?` see a consistent contract regardless of
18//! which path produced the run).
19//! Test: `render::tests::*`.
20
21use crate::events::{Event, SessionEventEnvelope};
22use crate::run_task::ExitCode;
23use crate::session::{Session, SessionStatus, TranscriptRecord};
24use crate::workstreams::{WorkstreamId, WorkstreamState};
25
26/// Render a fixed-width table of sessions for `tcode session list`.
27///
28/// Why: `session.list`'s raw JSON is unreadable at a glance; operators want
29/// id/status/task/agent at one line each.
30/// What: one header line + one row per session, columns
31/// `ID | STATUS | AGENT | TASK` (task truncated to keep rows terminal-width
32/// friendly). An empty list renders a single explanatory line, not an empty
33/// string, so scripts piping through a pager see something.
34/// Test: `tests::render_session_table_lists_every_session`,
35/// `tests::render_session_table_handles_empty_list`.
36pub 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(); // drop the trailing newline; callers add their own via println!
54    out
55}
56
57/// Render one line for a single streamed event, for `attach`/`run-task`.
58///
59/// Why: a human watching a live run wants a compact, timestamped narration
60/// — not the raw internally-tagged JSON.
61/// What: matches the handful of variants the M1 cut line actually produces
62/// (session lifecycle, tool lifecycle, generic message/log/progress) with a
63/// readable one-liner; anything else falls back to `[<kind>]` using the
64/// envelope's own `kind` string rather than an exhaustive match on
65/// [`Event`], so a future variant added elsewhere never breaks this
66/// function's compilation.
67/// Test: `tests::render_event_line_covers_key_variants`,
68/// `tests::render_event_line_falls_back_for_unknown_kind`.
69pub 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        // (UI Phase 1) `agent` prefixes every tool line so an attached CLI
77        // shows WHO made each call — the same attribution the SPA renders.
78        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
131/// Render a `TranscriptRecord` as a readable turn-by-turn view for
132/// `tcode transcript` (human mode; `--json` bypasses this entirely and
133/// pretty-prints the raw result).
134///
135/// Why: a bare JSON dump of the transcript is hard to scan; a human wants
136/// "who said what, with which tools" plus the cost/usage summary.
137/// What: one block per turn (`role` header, prose if any, tool calls if
138/// any), then a trailing usage/cost summary line. A never-run session (empty
139/// `turns`) renders a single explanatory line rather than an empty string.
140/// Test: `tests::render_transcript_human_lists_turns_and_totals`,
141/// `tests::render_transcript_human_handles_never_run_session`.
142pub 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/// One row of `workstream.list`'s wire response, as needed to render
174/// [`render_workstream_table`] (#3296, DOC-48 §5.4).
175///
176/// Why: the daemon's `workstream.list` response nests each record as
177/// `crate::workstreams::protocol::WorkstreamView` — private to that module,
178/// and carrying fields (`metadata`, `created_at`) the table never displays.
179/// This is the CLI's own minimal read-only projection of that wire shape;
180/// serde's default "ignore unknown fields" behavior means it deserializes
181/// straight out of the same JSON without the protocol module needing to
182/// expose anything new.
183/// What: `id`/`state` reuse the library's own [`WorkstreamId`]/
184/// [`WorkstreamState`] types (both already `pub` from `crate::workstreams`)
185/// so the table can never disagree with the domain model on what "active"
186/// means; `session_ids` is only read for its length (live session count).
187/// Test: `tests::render_workstream_table_marks_the_active_row`.
188#[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
199/// Render a tmux-`list-sessions`-style table of workstreams for
200/// `tcode workstream list` (DOC-48 §5.4, AC-5.1, issue #3296).
201///
202/// Why: rhymes with `tm`'s session-listing conventions (fixed-width columns,
203/// a leading marker for "the one that's current") WITHOUT importing from
204/// `trusty-mpm` — this crate has no dependency on it, so the shape is
205/// reinvented small and pure here. The leading `*` marker mirrors tmux's own
206/// `list-sessions` attached-session convention, which DOC-48 §5.3 already
207/// cites as the mental model for workstream observation ("tmux-attach-like
208/// behavior").
209/// What: one header line + one row per workstream: a leading `*` on the
210/// active workstream (blank otherwise), an 8-hex-char id prefix (DISPLAY
211/// ONLY — `tcode workstream get`/`activate`/`close` still require the full
212/// id; see `crate::cli::workstream`'s module docs in the `tcode` binary for
213/// why prefix resolution isn't implemented client-side), the computed
214/// state, the live session count, a humanized `updated_at` age, and the
215/// name (`(untitled)` when empty, DOC-48 §5.1: "Name is initially empty").
216/// An empty list renders one explanatory line instead of a bare header.
217/// Test: `tests::render_workstream_table_marks_the_active_row`,
218/// `tests::render_workstream_table_handles_empty_list`.
219pub 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(); // drop the trailing newline; callers add their own via println!
246    out
247}
248
249/// Render a compact "time ago" string for a past UTC timestamp.
250///
251/// Why: `updated_at`'s raw ISO-8601 timestamp is hard to scan at a glance;
252/// an operator wants "how stale is this workstream" in one short token.
253/// What: buckets the age into `just now` (<60s), `<N>m ago` (<1h), `<N>h ago`
254/// (<24h), `<N>d ago` (<30d), or `<N>w ago` beyond that. Never panics on a
255/// future timestamp (clock skew) — `signed_duration_since` is clamped to a
256/// minimum of zero seconds.
257/// Test: `tests::humanize_age_buckets_common_durations`.
258fn 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
276/// Map a terminal `SessionStatus` onto the CLI process exit code.
277///
278/// Why: `run-task` via the thin client and the legacy in-process
279/// `run-task` must agree on what a script checking `$?` sees.
280/// What: `Finished` -> `ExitCode::Success`; `Cancelled`/`Failed` ->
281/// `ExitCode::RunFailure`; `DeadlineExceeded` (#2207) -> its own distinct
282/// `ExitCode::DeadlineExceeded`, so a script can tell "timed out" from
283/// "errored" the same way the legacy path's `RunReport::exit` does;
284/// `TurnCapExceeded` (#3888) -> the pre-existing `ExitCode::Partial`, the
285/// same code the legacy `run_task::report` path already uses for "the PM's
286/// turn cap was exhausted" — this call didn't reach a natural stop, but the
287/// session is resumable (unlike `RunFailure`), matching that code's
288/// existing "not done, not dead" semantics; `Created`/`Running` (should
289/// never be passed here — the caller only calls this once a run has reached
290/// a terminal status) also map to `RunFailure` defensively rather than
291/// panicking.
292/// Test: `tests::exit_code_for_status_maps_terminal_states`.
293pub 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
303/// Truncate `s` to at most `max` chars, appending `…` when it was longer.
304fn 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        // (UI Phase 1) The two structured retrieval events render their own
378        // lines rather than degrading to the generic `[kind]` fallback.
379        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}