1use hashbrown::HashMap;
10use serde::{Deserialize, Serialize};
11use std::path::PathBuf;
12
13#[cfg(test)]
14use crate::config::constants::tools;
15use crate::utils::tokens::estimate_tokens;
16
17#[derive(Debug, Clone, Serialize, Deserialize)]
25pub struct ToolResult {
26 pub tool_name: String,
28
29 pub llm_content: String,
34
35 pub ui_content: String,
40
41 pub success: bool,
43
44 pub error: Option<String>,
46
47 pub metadata: ToolMetadata,
49}
50
51#[derive(Debug, Clone, Default, Serialize, Deserialize)]
56pub struct ToolMetadata {
57 pub files: Vec<PathBuf>,
59
60 pub lines: Vec<usize>,
62
63 pub data: HashMap<String, serde_json::Value>,
70
71 pub token_counts: TokenCounts,
73}
74
75#[derive(Debug, Clone, Default, Serialize, Deserialize)]
77pub struct TokenCounts {
78 pub llm_tokens: usize,
80
81 pub ui_tokens: usize,
83
84 pub savings_tokens: usize,
86
87 pub savings_percent: f32,
89}
90
91impl ToolResult {
92 pub fn new(tool_name: impl Into<String>, llm_content: impl Into<String>, ui_content: impl Into<String>) -> Self {
94 let llm_str = llm_content.into();
95 let ui_str = ui_content.into();
96
97 let llm_tokens = estimate_tokens(&llm_str);
98 let ui_tokens = estimate_tokens(&ui_str);
99 let savings = ui_tokens.saturating_sub(llm_tokens);
100 let savings_pct = if ui_tokens > 0 {
101 (savings as f32 / ui_tokens as f32) * 100.0
102 } else {
103 0.0
104 };
105
106 Self {
107 tool_name: tool_name.into(),
108 llm_content: llm_str,
109 ui_content: ui_str,
110 success: true,
111 error: None,
112 metadata: ToolMetadata {
113 token_counts: TokenCounts {
114 llm_tokens,
115 ui_tokens,
116 savings_tokens: savings,
117 savings_percent: savings_pct,
118 },
119 ..Default::default()
120 },
121 }
122 }
123
124 pub fn error(tool_name: impl Into<String>, error: impl Into<String>) -> Self {
126 let error_msg = error.into();
127 Self {
128 tool_name: tool_name.into(),
129 llm_content: format!("Tool failed: {error_msg}"),
130 ui_content: format!("Error: {error_msg}"),
131 success: false,
132 error: Some(error_msg),
133 metadata: ToolMetadata::default(),
134 }
135 }
136
137 pub fn simple(tool_name: impl Into<String>, content: impl Into<String>) -> Self {
141 let content_str = content.into();
142 Self::new(tool_name, content_str.clone(), content_str)
143 }
144
145 #[must_use]
147 pub fn with_metadata(mut self, metadata: ToolMetadata) -> Self {
148 let token_counts = std::mem::take(&mut self.metadata.token_counts);
150 self.metadata = metadata;
151 self.metadata.token_counts = token_counts;
152 self
153 }
154
155 #[must_use]
157 pub fn with_files(mut self, files: Vec<PathBuf>) -> Self {
158 self.metadata.files = files;
159 self
160 }
161
162 #[must_use]
164 pub fn with_data(mut self, key: impl Into<String>, value: serde_json::Value) -> Self {
165 self.metadata.data.insert(key.into(), value);
166 self
167 }
168
169 pub fn savings_summary(&self) -> String {
171 let counts = &self.metadata.token_counts;
172 format!("{} → {} tokens ({:.1}% saved)", counts.ui_tokens, counts.llm_tokens, counts.savings_percent)
173 }
174
175 pub fn has_significant_savings(&self) -> bool {
177 self.metadata.token_counts.savings_percent > 50.0
178 }
179}
180
181#[must_use = "build the metadata before discarding the builder"]
183#[derive(Default)]
184pub struct ToolMetadataBuilder {
185 files: Vec<PathBuf>,
186 lines: Vec<usize>,
187 data: HashMap<String, serde_json::Value>,
188}
189
190impl ToolMetadataBuilder {
191 pub fn new() -> Self {
192 Self::default()
193 }
194
195 pub fn file(mut self, path: PathBuf) -> Self {
196 self.files.push(path);
197 self
198 }
199
200 pub fn files(mut self, paths: Vec<PathBuf>) -> Self {
201 self.files.extend(paths);
202 self
203 }
204
205 pub fn line(mut self, line: usize) -> Self {
206 self.lines.push(line);
207 self
208 }
209
210 pub fn lines(mut self, lines: Vec<usize>) -> Self {
211 self.lines.extend(lines);
212 self
213 }
214
215 pub fn data(mut self, key: impl Into<String>, value: serde_json::Value) -> Self {
216 self.data.insert(key.into(), value);
217 self
218 }
219
220 #[must_use]
221 pub fn build(self) -> ToolMetadata {
222 ToolMetadata {
223 files: self.files,
224 lines: self.lines,
225 data: self.data,
226 token_counts: TokenCounts::default(), }
228 }
229}
230
231#[cfg(test)]
232mod tests {
233 use super::*;
234
235 #[test]
236 fn test_tool_result_creation() {
237 let result = ToolResult::new(
238 tools::GREP_FILE,
239 "Found 127 matches in 15 files",
240 "Very long output with 127 full match listings...",
241 );
242
243 assert_eq!(result.tool_name, tools::GREP_FILE);
244 assert!(result.success);
245 assert!(result.error.is_none());
246 assert!(result.metadata.token_counts.llm_tokens > 0);
247 assert!(result.metadata.token_counts.ui_tokens > 0);
248 assert!(result.metadata.token_counts.savings_tokens > 0);
249 }
250
251 #[test]
252 fn test_error_result() {
253 let result = ToolResult::error(tools::GREP_FILE, "Pattern invalid");
254
255 assert_eq!(result.tool_name, tools::GREP_FILE);
256 assert!(!result.success);
257 assert_eq!(result.error, Some("Pattern invalid".to_string()));
258 assert!(result.llm_content.contains("failed"));
259 }
260
261 #[test]
262 fn test_simple_result() {
263 let result = ToolResult::simple("test_tool", "Same content");
264
265 assert_eq!(result.llm_content, result.ui_content);
266 assert_eq!(result.metadata.token_counts.savings_tokens, 0);
267 }
268
269 #[test]
270 fn test_token_estimation() {
271 let text = "Hello world";
272 let tokens = estimate_tokens(text);
273 assert_eq!(tokens, 2);
275
276 let long_text = "a".repeat(1000);
277 let long_tokens = estimate_tokens(&long_text);
278 assert_eq!(long_tokens, 125);
280 }
281
282 #[test]
283 fn test_metadata_builder() {
284 let metadata = ToolMetadataBuilder::new()
285 .file(PathBuf::from("src/main.rs"))
286 .file(PathBuf::from("src/lib.rs"))
287 .line(42)
288 .line(100)
289 .data("match_count", serde_json::json!(127))
290 .data("files_searched", serde_json::json!(50))
291 .build();
292
293 assert_eq!(metadata.files.len(), 2);
294 assert_eq!(metadata.lines.len(), 2);
295 assert_eq!(metadata.data.len(), 2);
296 assert_eq!(metadata.data["match_count"], 127);
297 }
298
299 #[test]
300 fn test_with_methods() {
301 let result = ToolResult::new("test", "llm", "ui")
302 .with_files(vec![PathBuf::from("test.rs")])
303 .with_data("key", serde_json::json!("value"));
304
305 assert_eq!(result.metadata.files.len(), 1);
306 assert_eq!(result.metadata.data["key"], "value");
307 }
308
309 #[test]
310 fn test_savings_calculation() {
311 let result = ToolResult::new(
312 "grep",
313 "Short summary", "a".repeat(1000), );
316
317 assert!(result.metadata.token_counts.savings_tokens > 100);
318 assert!(result.metadata.token_counts.savings_percent > 90.0);
319 assert!(result.has_significant_savings());
320 }
321
322 #[test]
323 fn test_savings_summary() {
324 let result = ToolResult::new("grep", "Short", "Long content here");
325
326 let summary = result.savings_summary();
327 assert!(summary.contains("→"));
328 assert!(summary.contains("tokens"));
329 assert!(summary.contains("%"));
330 }
331}