Skip to main content

usage/
text.rs

1//! The session report as text (`ultron/session-report-text.ts`): the full report of one session and the
2//! one-line-per-session table. A number the session did not keep prints as `not recorded` (`n/r` in the table), and
3//! a cost nobody reported as `unknown`: neither is ever printed as zero. Plain style only (the CLI prints no color).
4
5use jsrt::localtime::Zone;
6use serde_json::{Map, Value};
7
8const NOT_RECORDED: &str = "not recorded";
9
10pub struct TextOptions<'a> {
11    pub utc: bool,
12    pub home: &'a str,
13    pub zone: &'a Zone,
14}
15
16pub fn format_tokens(tokens: f64) -> String {
17    if tokens < 1000.0 {
18        return jsrt::number::to_string(tokens);
19    }
20    if tokens < 999_950.0 {
21        return format!("{}k", jsrt::number::to_fixed(tokens / 1000.0, 1));
22    }
23    format!(
24        "{}M",
25        jsrt::number::to_fixed(tokens / 1_000_000.0, if tokens < 99_950_000.0 { 2 } else { 1 })
26    )
27}
28
29pub fn format_elapsed(ms: f64) -> String {
30    let seconds = jsrt::number::round(ms / 1000.0);
31    if seconds < 60.0 {
32        return format!("{}s", jsrt::number::to_string(seconds));
33    }
34    let minutes = (seconds / 60.0).floor();
35    if minutes < 60.0 {
36        return format!(
37            "{}m{:0>2}s",
38            jsrt::number::to_string(minutes),
39            jsrt::number::to_string(seconds % 60.0)
40        );
41    }
42    format!(
43        "{}h{:0>2}m",
44        jsrt::number::to_string((minutes / 60.0).floor()),
45        jsrt::number::to_string(minutes % 60.0)
46    )
47}
48
49fn usd(amount: f64) -> String {
50    format!(
51        "${}",
52        jsrt::number::to_fixed(amount, if amount >= 10.0 { 2 } else { 3 })
53    )
54}
55
56fn n(value: &Value, pointer: &str) -> f64 {
57    value.pointer(pointer).and_then(Value::as_f64).unwrap_or(0.0)
58}
59
60/// `$1.234`, `$3.287 (sub)`, `unknown`, or a sum of those; `-` when nothing was spent.
61fn format_cost(cost: &Value, tokens: f64) -> String {
62    let mut parts = Vec::new();
63    if let Some(reported) = cost["reportedUsd"].as_f64() {
64        parts.push(usd(reported));
65    }
66    if let Some(sub) = cost["subscriptionUsd"].as_f64() {
67        parts.push(if sub > 0.0 {
68            format!("{} (sub)", usd(sub))
69        } else {
70            "subscription".into()
71        });
72    }
73    let unpriced = n(cost, "/unpricedResponses");
74    if unpriced > 0.0 {
75        parts.push(if parts.is_empty() {
76            "unknown".into()
77        } else {
78            format!("unknown ({} unpriced)", jsrt::number::to_string(unpriced))
79        });
80    }
81    if parts.is_empty() {
82        return if tokens > 0.0 { "unknown".into() } else { "-".into() };
83    }
84    parts.join(" + ")
85}
86
87fn format_date(at: f64, options: &TextOptions) -> String {
88    let f = if options.utc {
89        jsrt::localtime::fields(at, 0)
90    } else {
91        options.zone.fields(at)
92    };
93    format!("{}-{:02}-{:02} {:02}:{:02}", f.year, f.month, f.day, f.hour, f.minute)
94}
95
96fn short_path(path: &str, home: &str) -> String {
97    if !home.is_empty() && (path == home || path.starts_with(&format!("{home}/"))) {
98        format!("~{}", &path[home.len()..])
99    } else {
100        path.to_string()
101    }
102}
103
104fn format_bytes(bytes: f64) -> String {
105    if bytes < 1024.0 {
106        return format!("{} B", jsrt::number::to_string(bytes));
107    }
108    if bytes < 1024.0 * 1024.0 {
109        return format!("{} kB", jsrt::number::to_fixed(bytes / 1024.0, 1));
110    }
111    format!("{} MB", jsrt::number::to_fixed(bytes / (1024.0 * 1024.0), 1))
112}
113
114fn plural(count: f64, one: &str) -> String {
115    format!(
116        "{} {}{}",
117        jsrt::number::to_string(count),
118        one,
119        if count == 1.0 { "" } else { "s" }
120    )
121}
122
123fn non_zero(pairs: &[(&str, f64)]) -> String {
124    pairs
125        .iter()
126        .filter(|(_, c)| *c > 0.0)
127        .map(|(label, c)| format!("{} {label}", jsrt::number::to_string(*c)))
128        .collect::<Vec<_>>()
129        .join(", ")
130}
131
132fn entries(value: &Value) -> Vec<(&String, &Value)> {
133    value.as_object().map(jsrt::json::object_entries).unwrap_or_default()
134}
135
136fn apis_line(apis: &Value) -> String {
137    entries(apis)
138        .into_iter()
139        .filter(|(_, c)| c.as_f64().unwrap_or(0.0) > 0.0)
140        .map(|(name, c)| format!("{name} {}", jsrt::number::to_string(c.as_f64().unwrap_or(0.0))))
141        .collect::<Vec<_>>()
142        .join(" · ")
143}
144
145fn cells_line(cells: &Value) -> String {
146    let count = n(cells, "/count");
147    format!(
148        "{}{}",
149        plural(count, "cell"),
150        if count > 0.0 {
151            format!(", {} failed", jsrt::number::to_string(n(cells, "/failed")))
152        } else {
153            String::new()
154        }
155    )
156}
157
158fn tokens_text(bucket: &Value) -> String {
159    let unmeasured = n(bucket, "/unmeasured");
160    if n(bucket, "/responses") == 0.0 && unmeasured > 0.0 {
161        return NOT_RECORDED.into();
162    }
163    format!(
164        "{}{}",
165        format_tokens(n(bucket, "/totalTokens")),
166        if unmeasured > 0.0 { " +?" } else { "" }
167    )
168}
169
170fn table(rows: &[Vec<String>], right: &[usize]) -> Vec<String> {
171    let mut widths: Vec<usize> = Vec::new();
172    for row in rows {
173        for (i, cell) in row.iter().enumerate() {
174            if widths.len() <= i {
175                widths.push(0);
176            }
177            widths[i] = widths[i].max(jsrt::utf16::len(cell));
178        }
179    }
180    rows.iter()
181        .map(|row| {
182            row.iter()
183                .enumerate()
184                .map(|(i, cell)| {
185                    if right.contains(&i) {
186                        pad_start(cell, widths[i])
187                    } else {
188                        pad_end(cell, widths[i])
189                    }
190                })
191                .collect::<Vec<_>>()
192                .join("  ")
193                .trim_end_matches(|c: char| jsrt::string::is_space(c))
194                .to_string()
195        })
196        .collect()
197}
198
199fn str_of<'a>(value: &'a Value, pointer: &str) -> &'a str {
200    value.pointer(pointer).and_then(Value::as_str).unwrap_or("")
201}
202
203/// The full report of one session, as lines.
204pub fn render_session_report(report: &Value, options: &TextOptions) -> Vec<String> {
205    let mut lines: Vec<String> = Vec::new();
206    let empty = Map::new();
207    let unrecorded = report["unrecorded"].as_object().unwrap_or(&empty);
208    let missing = |path: &str| match unrecorded.get(path).and_then(Value::as_str).filter(|s| !s.is_empty()) {
209        Some(why) => format!("{NOT_RECORDED} ({why})"),
210        None => NOT_RECORDED.into(),
211    };
212    let row = |lines: &mut Vec<String>, name: &str, text: &str| lines.push(format!("{}{text}", pad_end(name, 11)));
213    let more = |lines: &mut Vec<String>, text: &str| lines.push(format!("{}{text}", " ".repeat(11)));
214    let session = &report["session"];
215    let depth = &report["depth"];
216    let mode = str_of(report, "/mode");
217    let name = str_of(session, "/name");
218    lines.push(format!(
219        "Session {}{}  [{mode}]",
220        str_of(session, "/id"),
221        if name.is_empty() {
222            String::new()
223        } else {
224            format!("  {name}")
225        }
226    ));
227    lines.push(format!(
228        "{}  ·  {} to {}{}  ·  {}",
229        short_path(str_of(session, "/cwd"), options.home),
230        format_date(n(session, "/createdAt"), options),
231        format_date(n(session, "/modifiedAt"), options),
232        if options.utc { " UTC" } else { "" },
233        format_bytes(n(session, "/bytes"))
234    ));
235    lines.push(String::new());
236    row(&mut lines, "Depth", str_of(depth, "/verdict"));
237    let counters_since = report.pointer("/guardrails/countersSince").and_then(Value::as_f64);
238    let partial = match counters_since {
239        Some(since) if mode == "ultron claude" => format!(" (counted since {})", format_date(since, options)),
240        _ => String::new(),
241    };
242    let turns = &report["turns"];
243    if turns.is_null() {
244        row(&mut lines, "Turns", &missing("turns"));
245    } else {
246        let ended = non_zero(&[
247            ("aborted", n(turns, "/aborted")),
248            ("failed", n(turns, "/failed")),
249            ("running", n(turns, "/running")),
250        ]);
251        row(
252            &mut lines,
253            "Turns",
254            &format!(
255                "{}, {} wall{}{partial}",
256                plural(n(turns, "/count"), "turn"),
257                format_elapsed(n(turns, "/wallMs")),
258                if ended.is_empty() {
259                    String::new()
260                } else {
261                    format!(" ({ended})")
262                }
263            ),
264        );
265    }
266    let root_models = report
267        .pointer("/root/models")
268        .and_then(Value::as_array)
269        .cloned()
270        .unwrap_or_default();
271    let root_text = if !root_models.is_empty() {
272        root_models
273            .iter()
274            .map(|m| format!("{} ({})", str_of(m, "/model"), plural(n(m, "/responses"), "response")))
275            .collect::<Vec<_>>()
276            .join(", ")
277    } else if unrecorded
278        .get("root.models")
279        .and_then(Value::as_str)
280        .is_some_and(|s| !s.is_empty())
281    {
282        missing("root.models")
283    } else {
284        "no model response yet".into()
285    };
286    row(&mut lines, "Root", &root_text);
287    let cells = &report["cells"];
288    if cells.is_null() {
289        row(&mut lines, "Cells", &missing("cells"));
290    } else {
291        row(
292            &mut lines,
293            "Cells",
294            &format!(
295                "{}{}{partial}",
296                cells_line(&cells["total"]),
297                if str_of(cells, "/source") == "counters" {
298                    "  (runtime count)"
299                } else {
300                    ""
301                }
302            ),
303        );
304        let apis = apis_line(&cells["total"]["apis"]);
305        if !apis.is_empty() {
306            more(&mut lines, &apis);
307        }
308        let (sub, other) = (n(cells, "/subagents/count"), n(cells, "/other/count"));
309        if sub > 0.0 || other > 0.0 {
310            more(
311                &mut lines,
312                &format!(
313                    "root {} · sub-agents {}{}",
314                    jsrt::number::to_string(n(cells, "/root/count")),
315                    jsrt::number::to_string(sub),
316                    if other > 0.0 {
317                        format!(" · other lanes {}", jsrt::number::to_string(other))
318                    } else {
319                        String::new()
320                    }
321                ),
322            );
323        }
324        let tools = entries(&cells["otherTools"]);
325        if !tools.is_empty() {
326            let text = tools
327                .iter()
328                .map(|(name, tool)| {
329                    let failed = n(tool, "/failed");
330                    format!(
331                        "{name} {}{}",
332                        jsrt::number::to_string(n(tool, "/calls")),
333                        if failed > 0.0 {
334                            format!(" ({} failed)", jsrt::number::to_string(failed))
335                        } else {
336                            String::new()
337                        }
338                    )
339                })
340                .collect::<Vec<_>>()
341                .join(" · ");
342            more(&mut lines, &format!("other tools: {text}"));
343        }
344    }
345
346    // Depth.
347    let frames = &depth["frames"];
348    let subagents = &depth["subagents"];
349    if n(frames, "/count") == 0.0 {
350        row(&mut lines, "Frames", "0");
351    } else {
352        let states = non_zero(&[
353            ("complete", n(frames, "/complete")),
354            ("incomplete", n(frames, "/incomplete")),
355            ("failed", n(frames, "/failed")),
356            ("cancelled", n(frames, "/cancelled")),
357            ("running", n(frames, "/running")),
358        ]);
359        let nested = n(frames, "/nested");
360        row(
361            &mut lines,
362            "Frames",
363            &format!(
364                "{}: {states}{} · {} tokens",
365                jsrt::number::to_string(n(frames, "/count")),
366                if nested > 0.0 {
367                    format!(" · {} nested", jsrt::number::to_string(nested))
368                } else {
369                    String::new()
370                },
371                tokens_text(&report["usage"]["lanes"]["frames"])
372            ),
373        );
374        let calls = &frames["calls"];
375        if !calls.is_null() {
376            more(
377                &mut lines,
378                &format!(
379                    "from {} and {}",
380                    plural(n(calls, "/map"), "rlm.map call"),
381                    plural(n(calls, "/infer"), "rlm.infer call")
382                ),
383            );
384        }
385        let reasons = entries(&frames["incompleteReasons"]);
386        if !reasons.is_empty() {
387            let text = reasons
388                .iter()
389                .map(|(r, c)| format!("{r} {}", jsrt::number::to_string(c.as_f64().unwrap_or(0.0))))
390                .collect::<Vec<_>>()
391                .join(" · ");
392            more(&mut lines, &format!("incomplete: {text}"));
393        }
394        for model in frames["byModel"].as_array().into_iter().flatten() {
395            more(
396                &mut lines,
397                &format!(
398                    "{}  {}  {} tokens",
399                    str_of(model, "/model"),
400                    plural(n(model, "/count"), "frame"),
401                    format_tokens(n(model, "/tokens"))
402                ),
403            );
404        }
405    }
406    if n(subagents, "/count") == 0.0 {
407        row(&mut lines, "Sub-agents", "0");
408    } else {
409        let states = non_zero(&[
410            ("completed", n(subagents, "/completed")),
411            ("failed", n(subagents, "/failed")),
412            ("cancelled", n(subagents, "/cancelled")),
413            ("interrupted", n(subagents, "/interrupted")),
414            ("running", n(subagents, "/running")),
415        ]);
416        let nested = n(subagents, "/nested");
417        row(
418            &mut lines,
419            "Sub-agents",
420            &format!(
421                "{}: {states} · max depth {}{}",
422                jsrt::number::to_string(n(subagents, "/count")),
423                jsrt::number::to_string(n(subagents, "/maxDepth")),
424                if nested > 0.0 {
425                    format!(" ({} nested)", jsrt::number::to_string(nested))
426                } else {
427                    String::new()
428                }
429            ),
430        );
431        let v = &subagents["verdicts"];
432        let unverified = n(v, "/unverified");
433        more(
434            &mut lines,
435            &format!(
436                "verdicts: {} verified · {} contradicted · {} unverified{}",
437                jsrt::number::to_string(n(v, "/verified")),
438                jsrt::number::to_string(n(v, "/contradicted")),
439                jsrt::number::to_string(unverified),
440                if unverified > 0.0 {
441                    format!(
442                        " ({})",
443                        non_zero(&[
444                            ("without a verdict", n(v, "/none")),
445                            ("unchecked", n(v, "/unchecked")),
446                            ("invalid", n(v, "/invalid")),
447                        ])
448                    )
449                } else {
450                    String::new()
451                }
452            ),
453        );
454        for model in subagents["byModel"].as_array().into_iter().flatten() {
455            let (count, unmeasured) = (n(model, "/count"), n(model, "/unmeasured"));
456            let tokens = if unmeasured == count {
457                format!("tokens {NOT_RECORDED}")
458            } else {
459                format!(
460                    "{} tokens{}",
461                    format_tokens(n(model, "/tokens")),
462                    if unmeasured > 0.0 {
463                        format!(" ({} {NOT_RECORDED})", jsrt::number::to_string(unmeasured))
464                    } else {
465                        String::new()
466                    }
467                )
468            };
469            more(
470                &mut lines,
471                &format!("{}  {}  {tokens}", str_of(model, "/model"), plural(count, "sub-agent")),
472            );
473        }
474        for worktree in subagents["worktrees"].as_array().into_iter().flatten() {
475            more(
476                &mut lines,
477                &format!(
478                    "worktree {}: {}, merge {}",
479                    str_of(worktree, "/branch"),
480                    plural(n(worktree, "/changedFiles"), "file"),
481                    worktree["merge"].as_str().unwrap_or(NOT_RECORDED)
482                ),
483            );
484        }
485    }
486    let workflows = &depth["workflows"];
487    row(
488        &mut lines,
489        "Workflows",
490        &if workflows.is_null() {
491            missing("depth.workflows")
492        } else {
493            plural(n(workflows, "/runs"), "run")
494        },
495    );
496    let typed = entries(&depth["typedAgents"]["byDefinition"]);
497    row(
498        &mut lines,
499        "Other work",
500        &format!(
501            "{}{} · {}",
502            plural(n(depth, "/typedAgents/count"), "typed-agent task"),
503            if typed.is_empty() {
504                String::new()
505            } else {
506                format!(
507                    " ({})",
508                    typed
509                        .iter()
510                        .map(|(d, c)| format!("{d} {}", jsrt::number::to_string(c.as_f64().unwrap_or(0.0))))
511                        .collect::<Vec<_>>()
512                        .join(", ")
513                )
514            },
515            plural(n(depth, "/backgroundJobs/count"), "background job")
516        ),
517    );
518
519    // Tokens and cost.
520    lines.push(String::new());
521    lines.push("Tokens and cost".into());
522    let usage_row = |name: &str, bucket: &Value| -> Vec<String> {
523        vec![
524            format!("  {name}"),
525            jsrt::number::to_string(n(bucket, "/responses")),
526            format_tokens(n(bucket, "/input")),
527            format_tokens(n(bucket, "/output")),
528            format_tokens(n(bucket, "/cacheRead")),
529            format_tokens(n(bucket, "/cacheWrite")),
530            tokens_text(bucket),
531            format_cost(&bucket["cost"], n(bucket, "/totalTokens")),
532        ]
533    };
534    let header = |first: &str| -> Vec<String> {
535        [
536            first,
537            "responses",
538            "input",
539            "output",
540            "cache read",
541            "cache write",
542            "total",
543            "cost",
544        ]
545        .map(String::from)
546        .to_vec()
547    };
548    let usage = &report["usage"];
549    let lanes = &usage["lanes"];
550    let mut rows = vec![header("  lane")];
551    if mode == "ultron claude" && n(lanes, "/root/responses") == 0.0 {
552        let mut r = vec!["  root".to_string()];
553        r.extend(std::iter::repeat_n("n/r".to_string(), 7));
554        rows.push(r);
555    } else {
556        rows.push(usage_row("root", &lanes["root"]));
557    }
558    rows.push(usage_row("frames", &lanes["frames"]));
559    rows.push(usage_row("sub-agents", &lanes["subagents"]));
560    if n(lanes, "/other/responses") > 0.0 || n(lanes, "/other/unmeasured") > 0.0 {
561        rows.push(usage_row("other", &lanes["other"]));
562    }
563    rows.push(usage_row("total", &usage["total"]));
564    let numeric = [1, 2, 3, 4, 5, 6];
565    lines.extend(table(&rows, &numeric));
566    let models = usage["models"].as_array().cloned().unwrap_or_default();
567    if !models.is_empty() {
568        let mut model_rows = vec![header("  model")];
569        for model in &models {
570            model_rows.push(usage_row(str_of(model, "/model"), model));
571        }
572        lines.extend(table(&model_rows, &numeric));
573    }
574    let total = &usage["total"];
575    let mut notes = Vec::new();
576    if mode == "ultron claude" {
577        notes.push(
578            "root n/r: Claude Code owns the root conversation; its tokens and cost are Claude Code's, not in this session."
579                .to_string(),
580        );
581    }
582    if !total["cost"]["subscriptionUsd"].is_null() {
583        notes.push(
584            "(sub): made on a subscription login; the amount is the provider's notional figure, not a charge.".into(),
585        );
586    }
587    let unpriced = n(total, "/cost/unpricedResponses");
588    if unpriced > 0.0 {
589        notes.push(format!(
590            "unknown: {} used tokens and reported no price.",
591            plural(unpriced, "response")
592        ));
593    }
594    let unmeasured = n(total, "/unmeasured");
595    if unmeasured > 0.0 {
596        notes.push(format!(
597            "+?: {} reported no usage; their tokens are not in the totals.",
598            plural(unmeasured, "sub-agent")
599        ));
600    }
601    for note in notes {
602        lines.push(format!("  {note}"));
603    }
604
605    // Guardrails.
606    lines.push(String::new());
607    lines.push("Guardrails".into());
608    let guardrails = &report["guardrails"];
609    let since = counters_since.map_or(String::new(), |s| {
610        format!(" (counted since {})", format_date(s, options))
611    });
612    let guards = &guardrails["guards"];
613    if guards.is_null() {
614        row(&mut lines, "  Loki", &missing("guardrails.guards"));
615    } else if entries(guards).is_empty() {
616        row(&mut lines, "  Loki", &format!("no write was checked{since}"));
617    } else {
618        for (name, g) in entries(guards) {
619            row(
620                &mut lines,
621                &format!("  {name}"),
622                &format!(
623                    "{}, {} blocked, {} unchecked · after cells: {}, {} · {}{since}",
624                    plural(n(g, "/checks"), "check"),
625                    jsrt::number::to_string(n(g, "/blocked")),
626                    jsrt::number::to_string(n(g, "/unchecked")),
627                    plural(n(g, "/afterChecks"), "check"),
628                    plural(n(g, "/afterFindings"), "finding"),
629                    format_elapsed(n(g, "/ms"))
630                ),
631            );
632        }
633    }
634    let secrets = &guardrails["secretsMasked"];
635    row(
636        &mut lines,
637        "  Secrets",
638        &if secrets.is_null() {
639            missing("guardrails.secretsMasked")
640        } else {
641            format!("{} masked", jsrt::number::to_string(secrets.as_f64().unwrap_or(0.0)))
642        },
643    );
644    let hints = entries(&guardrails["hints"]);
645    let stuck = guardrails["hints"]["stuck-loop"].as_f64().unwrap_or(0.0);
646    row(
647        &mut lines,
648        "  Hints",
649        &format!(
650            "stuck-loop {}{}",
651            jsrt::number::to_string(stuck),
652            hints
653                .iter()
654                .filter(|(tag, _)| tag.as_str() != "stuck-loop")
655                .map(|(tag, c)| format!(" · {tag} {}", jsrt::number::to_string(c.as_f64().unwrap_or(0.0))))
656                .collect::<String>()
657        ),
658    );
659    let nudges = &guardrails["nudges"];
660    row(
661        &mut lines,
662        "  Nudges",
663        &if nudges.is_null() {
664            missing("guardrails.nudges")
665        } else {
666            format!(
667                "tool rounds {} · wait {} · skill {}",
668                jsrt::number::to_string(n(nudges, "/toolRounds")),
669                jsrt::number::to_string(n(nudges, "/wait")),
670                jsrt::number::to_string(n(nudges, "/skill"))
671            )
672        },
673    );
674    let limits = &guardrails["usageLimitBlocks"];
675    row(
676        &mut lines,
677        "  Limits",
678        &if limits.is_null() {
679            missing("guardrails.usageLimitBlocks")
680        } else {
681            format!("{}{since}", plural(limits.as_f64().unwrap_or(0.0), "usage-limit block"))
682        },
683    );
684
685    // Memory.
686    lines.push(String::new());
687    lines.push("Memory".into());
688    let operations = &report["memory"]["operations"];
689    if operations.is_null() {
690        row(&mut lines, "  Store", &missing("memory.operations"));
691    } else {
692        let text = entries(operations)
693            .iter()
694            .map(|(op, c)| format!("{op} {}", jsrt::number::to_string(c.as_f64().unwrap_or(0.0))))
695            .collect::<Vec<_>>()
696            .join(" · ");
697        row(&mut lines, "  Store", &text);
698    }
699    let recall = &report["memory"]["recall"];
700    if recall.is_object() {
701        let count = |key: &str| recall[key].as_f64().unwrap_or(0.0);
702        let memories = count("memories");
703        let mut text = format!(
704            "{} · {} {}",
705            plural(count("messages"), "automatic recall"),
706            jsrt::number::to_string(memories),
707            if memories == 1.0 { "memory" } else { "memories" }
708        );
709        if count("briefs") > 0.0 {
710            text.push_str(&format!(" · {}", plural(count("briefs"), "project brief")));
711        }
712        if count("stale") > 0.0 {
713            text.push_str(&format!(" · {} stale", jsrt::number::to_string(count("stale"))));
714        }
715        row(&mut lines, "  Recall", &text);
716    }
717    lines
718}
719
720fn table_model(report: &Value) -> String {
721    let models = report.pointer("/root/models").and_then(Value::as_array);
722    match models.and_then(|m| m.first()) {
723        Some(first) => {
724            let model = str_of(first, "/model").to_string();
725            let count = models.map_or(0, Vec::len);
726            if count > 1 {
727                format!("{model} +{}", count - 1)
728            } else {
729                model
730            }
731        }
732        None if str_of(report, "/mode") == "ultron claude" => "Claude Code".into(),
733        None => "-".into(),
734    }
735}
736
737fn clip(text: &str, width: usize) -> String {
738    if jsrt::utf16::len(text) <= width {
739        text.to_string()
740    } else {
741        format!("…{}", jsrt::utf16::skip(text, jsrt::utf16::len(text) - width + 1))
742    }
743}
744
745/// One line per session, in the order given.
746pub fn render_session_table(reports: &[Value], options: &TextOptions) -> Vec<String> {
747    let mut rows: Vec<Vec<String>> = vec![
748        [
749            "LAST ACTIVE",
750            "ID",
751            "CWD",
752            "MODE",
753            "MODEL",
754            "TURNS",
755            "CELLS",
756            "FRAMES",
757            "SUBS",
758            "TOKENS",
759            "COST",
760            "DEPTH",
761        ]
762        .map(String::from)
763        .to_vec(),
764    ];
765    let mut unrecorded = false;
766    for report in reports {
767        let mut count = |value: Option<f64>| match value {
768            None => {
769                unrecorded = true;
770                "n/r".to_string()
771            }
772            Some(v) => jsrt::number::to_string(v),
773        };
774        let total = &report["usage"]["total"];
775        let unknown_usage = str_of(report, "/mode") == "ultron claude"
776            && n(total, "/responses") == 0.0
777            && n(total, "/unmeasured") == 0.0;
778        let id = str_of(report, "/session/id");
779        let turns = report.pointer("/turns/count").and_then(Value::as_f64);
780        let cells = report.pointer("/cells/total/count").and_then(Value::as_f64);
781        let turns = count(turns);
782        let cells = count(cells);
783        let (tokens, cost) = if unknown_usage {
784            (count(None), count(None))
785        } else {
786            (
787                tokens_text(total),
788                format_cost(&total["cost"], n(total, "/totalTokens")),
789            )
790        };
791        rows.push(vec![
792            format_date(n(report, "/session/modifiedAt"), options),
793            jsrt::utf16::head(id, 13).to_string(),
794            clip(&short_path(str_of(report, "/session/cwd"), options.home), 32),
795            str_of(report, "/mode").to_string(),
796            clip(&table_model(report), 34),
797            turns,
798            cells,
799            jsrt::number::to_string(n(report, "/depth/frames/count")),
800            jsrt::number::to_string(n(report, "/depth/subagents/count")),
801            tokens,
802            cost,
803            str_of(report, "/depth/verdict").to_string(),
804        ]);
805    }
806    let mut lines = table(&rows, &[5, 6, 7, 8, 9]);
807    if unrecorded {
808        lines.push(
809            "n/r: not recorded by that session (never zero). Tokens and cost of an `ultron claude` session leave out the root, which is Claude Code's."
810                .into(),
811        );
812    }
813    lines
814}
815
816/// `text.padEnd(width)`, in UTF-16 code units.
817fn pad_end(text: &str, width: usize) -> String {
818    format!("{text}{}", " ".repeat(width.saturating_sub(jsrt::utf16::len(text))))
819}
820
821/// `text.padStart(width)`, in UTF-16 code units.
822fn pad_start(text: &str, width: usize) -> String {
823    format!("{}{text}", " ".repeat(width.saturating_sub(jsrt::utf16::len(text))))
824}