artifactize_core/agent/session/transcript/
render.rs1use rig_core::message::{ToolResult, ToolResultContent};
4use std::path::Path;
5
6const HEADER_CHARS: usize = 180;
8
9#[derive(Debug, Clone, PartialEq, Eq)]
10pub enum State {
11 Running,
12 Succeeded,
13 Failed(String),
14 CompletedUnknown,
15 Unfinished,
16}
17impl State {
18 fn label(&self) -> &str {
19 match self {
20 Self::Running => "running",
21 Self::Succeeded => "done",
22 Self::Failed(_) => "failed",
23 Self::CompletedUnknown => "completed (status not recorded)",
24 Self::Unfinished => "not completed",
25 }
26 }
27}
28#[derive(Debug, Clone)]
29pub struct Activity {
30 pub name: String,
31 pub target: String,
32 pub state: State,
33 pub orphan: bool,
34}
35#[derive(Debug, Default)]
36pub struct Group {
37 pub activities: Vec<Activity>,
38}
39impl Group {
40 pub fn text(&self, expanded: bool) -> String {
41 let active = self
42 .activities
43 .iter()
44 .find(|activity| activity.state == State::Running);
45 let failed = self
46 .activities
47 .iter()
48 .filter_map(|activity| match &activity.state {
49 State::Failed(reason) => Some((activity, reason)),
50 _ => None,
51 })
52 .collect::<Vec<_>>();
53 let mut text = match active {
54 Some(activity) => format!(
55 "{} {} {} — running{}",
56 if expanded { "▾" } else { "▸" },
57 activity_label(&activity.name),
58 activity.target,
59 if self.activities.len() > 1 {
60 format!(" · {} activities", self.activities.len())
61 } else {
62 String::new()
63 }
64 ),
65 None => {
66 let label = self
67 .activities
68 .first()
69 .map(|activity| activity_label(&activity.name))
70 .unwrap_or("Tools");
71 let target = self
72 .activities
73 .first()
74 .map(|activity| activity.target.as_str())
75 .unwrap_or_default();
76 format!(
77 "{} {label} {target} — {}{}",
78 if expanded { "▾" } else { "▸" },
79 if failed.is_empty() {
80 "completed"
81 } else {
82 "failed"
83 },
84 if self.activities.len() > 1 {
85 format!(" · {} activities", self.activities.len())
86 } else {
87 String::new()
88 }
89 )
90 }
91 };
92 for (activity, reason) in failed {
94 text.push_str(&format!(
95 "{}{} {} — failed: {}",
96 if expanded { "\n " } else { " · " },
97 activity.name,
98 activity.target,
99 reason
100 ));
101 }
102 if expanded {
103 for activity in &self.activities {
104 if matches!(activity.state, State::Failed(_)) {
105 continue;
106 }
107 text.push_str(&format!(
108 "\n {} {} — {}{}",
109 activity.name,
110 activity.target,
111 activity.state.label(),
112 if activity.orphan {
113 " (unmatched recorded result)"
114 } else {
115 ""
116 }
117 ));
118 }
119 } else if self.activities.iter().any(|activity| {
120 activity.orphan || matches!(activity.state, State::CompletedUnknown | State::Unfinished)
121 }) {
122 text.push_str(" · incomplete/status unreported");
123 }
124 text.push_str("\n\n");
125 text
126 }
127}
128
129pub(super) fn header(text: &str) -> String {
130 text.chars()
131 .map(|character| {
132 if character.is_control() {
133 ' '
134 } else {
135 character
136 }
137 })
138 .take(HEADER_CHARS)
139 .collect()
140}
141fn activity_label(name: &str) -> &str {
142 if name == "read" || name.starts_with("read_") {
143 "Read"
144 } else if name == "grep"
145 || name == "glob"
146 || name.starts_with("grep_")
147 || name.starts_with("glob_")
148 {
149 "Search"
150 } else if name == "list" || name.starts_with("list_") {
151 "List"
152 } else if name == "view_image" || name.starts_with("view_image_") {
153 "View image"
154 } else {
155 name
156 }
157}
158pub(super) enum Target<'a> {
159 Builtin {
160 path: Option<&'a Path>,
161 pattern: Option<&'a str>,
162 },
163 Unrecorded,
164}
165
166pub(super) fn target(target: Target<'_>) -> String {
167 let Target::Builtin { path, pattern } = target else {
168 return "target not recorded".into();
169 };
170 let path = path
171 .map(|path| header(&crate::platform::path_text(path)))
172 .filter(|text| !text.is_empty())
173 .unwrap_or_else(|| ".".into());
174 match pattern {
175 Some(pattern) => format!("{path} · {}", header(pattern)),
176 None => path,
177 }
178}
179pub(super) fn failure_reason(result: &ToolResult) -> String {
180 result
181 .content
182 .iter()
183 .find_map(|part| match part {
184 ToolResultContent::Text(text) => Some(header(&text.text)),
185 _ => None,
186 })
187 .filter(|text| !text.is_empty())
188 .unwrap_or_else(|| "failure reason not recorded".into())
189}
190
191pub(super) fn result_text(result: &crate::agent::verdict::ValidatedResult) -> String {
194 fn field(label: &str, value: &serde_json::Value, indent: usize, lines: &mut Vec<String>) {
195 let prefix = " ".repeat(indent);
196 match value {
197 serde_json::Value::Object(fields) => {
198 if !label.is_empty() {
199 lines.push(format!("{prefix}{label}"));
200 }
201 for (name, value) in fields {
202 field(name, value, indent + usize::from(!label.is_empty()), lines);
203 }
204 }
205 serde_json::Value::Array(items) => {
206 if !label.is_empty() {
207 lines.push(format!("{prefix}{label}"));
208 }
209 for value in items {
210 field("-", value, indent + 1, lines);
211 }
212 }
213 serde_json::Value::String(text) => lines.push(format!(
214 "{prefix}{}{}",
215 if label.is_empty() {
216 String::new()
217 } else {
218 format!("{label}: ")
219 },
220 markdown(text)
221 )),
222 value => lines.push(format!("{prefix}{label}: {value}")),
223 }
224 }
225 let mut lines = vec![format!("Verdict: {}", header(result.verdict.as_str()))];
226 for (name, value) in &result.fields() {
227 field(name, value, 0, &mut lines);
228 }
229 lines.join("\n")
230}
231
232pub fn markdown(text: &str) -> String {
235 let mut code = false;
236 text.lines()
237 .map(|line| {
238 if line.trim_start().starts_with("```") || line.trim_start().starts_with("~~~") {
239 code = !code;
240 return String::new();
241 }
242 if code {
243 return format!(" {line}");
244 }
245 let heading = line.trim_start_matches('#');
246 if heading.len() != line.len() && heading.starts_with(' ') {
247 heading.trim_start().to_owned()
248 } else {
249 line.to_owned()
250 }
251 })
252 .collect::<Vec<_>>()
253 .join("\n")
254}