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        }
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        // (UI Phase 1) The two structured retrieval events render their own
376        // lines rather than degrading to the generic `[kind]` fallback.
377        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}