octomind 0.25.0

Session-based AI development assistant with conversational codebase interaction, multimodal vision support, built-in MCP tools, and multi-provider AI integration
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
// Copyright 2026 Muvon Un Limited
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// Session report generation module

use crate::log_debug;
use crate::session::chat::formatting::format_duration;
use crate::session::chat::markdown::MarkdownRenderer;
use anyhow::Result;
use serde_json::Value;
use std::collections::HashMap;
use std::fs::File;
use std::io::{BufRead, BufReader};

#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct SessionReport {
	pub entries: Vec<ReportEntry>,
	pub totals: ReportTotals,
}

#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct ReportEntry {
	pub user_request: String,
	pub cost: String,
	pub tool_calls: u32,
	pub tools_used: String,
	pub task_time: String,
	pub ai_time: String,
	pub processing_time: String,
}

#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct ReportTotals {
	pub total_cost: f64,
	pub total_tool_calls: u32,
	pub total_task_time_ms: u64,
	pub total_ai_time_ms: u64,
	pub total_processing_time_ms: u64,
	pub total_requests: u32,
}

#[derive(Debug, Clone)]
struct RequestContext {
	pub user_request: String,
	pub start_timestamp: u64,
	pub end_timestamp: u64, // Last activity timestamp for this request
	pub cost_before: f64,
	pub cost_after: f64,
	pub tools: HashMap<String, u32>,
	pub api_time_before: u64,  // Total API time before this request
	pub api_time_after: u64,   // Total API time after this request
	pub tool_time_before: u64, // Total tool time before this request
	pub tool_time_after: u64,  // Total tool time after this request
}

impl SessionReport {
	/// Generate a session report from the session log file
	pub fn generate_from_log(session_log_path: &str) -> Result<SessionReport> {
		let file = File::open(session_log_path)?;
		let reader = BufReader::new(file);

		let mut contexts: Vec<RequestContext> = Vec::new();
		let mut current_context: Option<RequestContext> = None;
		let mut last_total_cost = 0.0;
		let mut last_total_api_time_ms = 0u64;
		let mut last_total_tool_time_ms = 0u64;

		// Read all log entries
		let mut all_entries: Vec<Value> = Vec::new();
		for line in reader.lines() {
			let line = line?;
			if line.trim().is_empty() {
				continue;
			}
			if let Ok(log_entry) = serde_json::from_str::<Value>(&line) {
				all_entries.push(log_entry);
			}
		}

		// Process entries and track cost/time
		for log_entry in all_entries.iter() {
			let log_type = log_entry.get("type").and_then(|t| t.as_str()).unwrap_or("");
			let entry_timestamp = log_entry
				.get("timestamp")
				.and_then(|t| t.as_u64())
				.unwrap_or(0);

			match log_type {
				"STATS" => {
					// Update last known totals from session stats
					if let Some(total_cost) = log_entry.get("total_cost").and_then(|c| c.as_f64()) {
						last_total_cost = total_cost;
					}
					if let Some(total_api_time) =
						log_entry.get("total_api_time_ms").and_then(|t| t.as_u64())
					{
						last_total_api_time_ms = total_api_time;
					}
					if let Some(total_tool_time) =
						log_entry.get("total_tool_time_ms").and_then(|t| t.as_u64())
					{
						last_total_tool_time_ms = total_tool_time;
					}
				}
				"USER" | "COMMAND" => {
					// Save previous context if exists
					if let Some(mut ctx) = current_context.take() {
						ctx.cost_after = last_total_cost;
						ctx.api_time_after = last_total_api_time_ms;
						ctx.tool_time_after = last_total_tool_time_ms;
						contexts.push(ctx);
					}

					// Start new context
					let content = if log_type == "USER" {
						log_entry
							.get("content")
							.and_then(|c| c.as_str())
							.unwrap_or("")
							.to_string()
					} else {
						log_entry
							.get("command")
							.and_then(|c| c.as_str())
							.unwrap_or("")
							.to_string()
					};

					current_context = Some(RequestContext {
						user_request: content,
						start_timestamp: entry_timestamp,
						end_timestamp: entry_timestamp,
						cost_before: last_total_cost,
						cost_after: last_total_cost,
						tools: HashMap::new(),
						api_time_before: last_total_api_time_ms,
						api_time_after: last_total_api_time_ms,
						tool_time_before: last_total_tool_time_ms,
						tool_time_after: last_total_tool_time_ms,
					});
				}
				"TOOL_CALL" => {
					// Track tool usage
					if let Some(ref mut ctx) = current_context {
						if let Some(tool_name) = log_entry.get("tool_name").and_then(|t| t.as_str())
						{
							*ctx.tools.entry(tool_name.to_string()).or_insert(0) += 1;
						}
					}
				}
				_ => {
					// Check for any other entries that might contain session cost updates
					if let Some(session_info) = log_entry.get("session_info") {
						if let Some(total_cost) =
							session_info.get("total_cost").and_then(|c| c.as_f64())
						{
							last_total_cost = total_cost;
						}
					}
				}
			}

			// Track end timestamp for task time: last activity during this request
			if log_type != "USER" && log_type != "COMMAND" {
				if let Some(ref mut ctx) = current_context {
					if entry_timestamp > ctx.end_timestamp {
						ctx.end_timestamp = entry_timestamp;
					}
				}
			}
		}

		// Save the last context if exists
		if let Some(mut ctx) = current_context {
			ctx.cost_after = last_total_cost;
			ctx.api_time_after = last_total_api_time_ms;
			ctx.tool_time_after = last_total_tool_time_ms;
			contexts.push(ctx);
		}

		// Convert contexts to report entries
		let mut entries = Vec::new();
		let mut totals = ReportTotals {
			total_cost: 0.0,
			total_tool_calls: 0,
			total_task_time_ms: 0,
			total_ai_time_ms: 0,
			total_processing_time_ms: 0,
			total_requests: 0,
		};

		for (i, ctx) in contexts.iter().enumerate() {
			let tool_calls: u32 = ctx.tools.values().sum();
			let tools_used = Self::format_tools_used(&ctx.tools);
			let cost_delta = ctx.cost_after - ctx.cost_before;

			// AI Time = API latency delta from STATS entries
			let ai_time_ms = ctx.api_time_after.saturating_sub(ctx.api_time_before);

			// Processing Time = Tool execution time delta from STATS entries
			let processing_time_ms = ctx.tool_time_after.saturating_sub(ctx.tool_time_before);

			// Task time = wall-clock time from user input to last activity for this request
			let task_time_ms = if ctx.end_timestamp > ctx.start_timestamp {
				(ctx.end_timestamp - ctx.start_timestamp) * 1000 // Convert to ms
			} else if i + 1 < contexts.len() {
				// Fallback: no end_timestamp tracked (e.g. commands with no activity)
				0
			} else {
				// Last request still in progress — measure to now
				let current_timestamp = std::time::SystemTime::now()
					.duration_since(std::time::UNIX_EPOCH)
					.unwrap_or_default()
					.as_secs();

				if current_timestamp > ctx.start_timestamp {
					(current_timestamp - ctx.start_timestamp) * 1000 // Convert to ms
				} else {
					0
				}
			};

			totals.total_cost += cost_delta;
			totals.total_tool_calls += tool_calls;
			totals.total_task_time_ms += task_time_ms;
			totals.total_ai_time_ms += ai_time_ms;
			totals.total_processing_time_ms += processing_time_ms;
			totals.total_requests += 1;

			// Debug output to understand what we're getting
			log_debug!(
				"Request: '{}', Cost delta: {:.5}, AI time: {}ms, Processing time: {}ms",
				ctx.user_request,
				cost_delta,
				ai_time_ms,
				processing_time_ms
			);

			// Debug task time calculation
			log_debug!(
				"Task time calc: start={}, end={}, task_time_ms={}",
				ctx.start_timestamp,
				ctx.end_timestamp,
				task_time_ms
			);

			entries.push(ReportEntry {
				user_request: Self::truncate_request(&ctx.user_request, 35),
				cost: format!("{:.5}", cost_delta),
				tool_calls,
				tools_used,
				task_time: format_duration(task_time_ms),
				ai_time: format_duration(ai_time_ms),
				processing_time: format_duration(processing_time_ms),
			});
		}

		Ok(SessionReport { entries, totals })
	}

	/// Format tools used as "tool_name(count), tool_name(count)"
	fn format_tools_used(tools: &HashMap<String, u32>) -> String {
		if tools.is_empty() {
			return "-".to_string();
		}

		let mut tool_list: Vec<String> = tools
			.iter()
			.map(|(name, count)| format!("{}({})", name, count))
			.collect();
		tool_list.sort();
		tool_list.join(", ")
	}

	/// Truncate long user requests for table display
	fn truncate_request(request: &str, max_len: usize) -> String {
		if request.chars().count() <= max_len {
			request.to_string()
		} else {
			let truncated: String = request.chars().take(max_len - 3).collect();
			format!("{}...", truncated)
		}
	}

	/// Generate markdown table for the report
	pub fn generate_markdown_table(&self) -> String {
		let mut markdown = String::new();

		// Table header
		markdown.push_str("| User Request | Cost ($) | Tool Calls | Tools Used | Task Time | AI Time | Processing Time |\n");
		markdown.push_str("|--------------|----------|------------|------------|-----------|---------|----------------|\n");

		// Table rows
		for entry in &self.entries {
			markdown.push_str(&format!(
				"| {} | {} | {} | {} | {} | {} | {} |\n",
				self.escape_markdown(&entry.user_request),
				entry.cost,
				entry.tool_calls,
				self.escape_markdown(&entry.tools_used),
				entry.task_time,
				entry.ai_time,
				entry.processing_time
			));
		}

		// Totals row
		markdown.push_str(&format!(
			"| **TOTAL** | **{:.5}** | **{}** | **{} total calls** | **{}** | **{}** | **{}** |\n",
			self.totals.total_cost,
			self.totals.total_tool_calls,
			self.totals.total_tool_calls,
			format_duration(self.totals.total_task_time_ms),
			format_duration(self.totals.total_ai_time_ms),
			format_duration(self.totals.total_processing_time_ms)
		));

		markdown
	}

	/// Escape markdown special characters in table cells
	fn escape_markdown(&self, text: &str) -> String {
		text.replace("|", "\\|")
			.replace("\n", " ")
			.replace("\r", "")
	}

	/// Display the report with summary information using markdown rendering
	pub fn display(&self, config: &crate::config::Config) {
		// Generate the full markdown report
		let markdown_report = self.to_markdown_string();

		// Render using markdown renderer if enabled
		if config.enable_markdown_rendering {
			let theme = config.markdown_theme.parse().unwrap_or_default();
			let renderer = MarkdownRenderer::with_theme(theme);
			match renderer.render_and_print(&markdown_report) {
				Ok(_) => {
					// Successfully rendered as markdown
				}
				Err(_) => {
					// Fallback to plain text if markdown rendering fails
					self.display_plain(&markdown_report);
				}
			}
		} else {
			// Use plain text rendering
			self.display_plain(&markdown_report);
		}
	}

	/// Generate markdown report as string
	pub fn to_markdown_string(&self) -> String {
		let mut markdown_report = String::new();

		// Header
		markdown_report.push_str("# 📊 Session Usage Report\n\n");

		// Table
		markdown_report.push_str(&self.generate_markdown_table());
		markdown_report.push('\n');

		// Summary
		markdown_report.push_str(&format!(
			"## 📈 Summary\n\n**{}** requests • **${:.5}** total cost • **{}** tool calls • **{}** task time • **{}** AI time • **{}** processing time\n",
			self.totals.total_requests,
			self.totals.total_cost,
			self.totals.total_tool_calls,
			format_duration(self.totals.total_task_time_ms),
			format_duration(self.totals.total_ai_time_ms),
			format_duration(self.totals.total_processing_time_ms)
		));

		markdown_report
	}

	/// Generate plain text report (for WebSocket/API)
	pub fn to_plain_string(&self) -> String {
		let markdown = self.to_markdown_string();
		// Convert markdown to plain text
		markdown
			.replace("# ", "")
			.replace("## ", "")
			.replace("**", "")
			.replace("|", " ")
	}

	/// Generate structured JSON report (for WebSocket/API)
	pub fn to_json(&self) -> serde_json::Value {
		serde_json::json!({
			"entries": self.entries.iter().map(|e| serde_json::json!({
				"user_request": e.user_request,
				"cost": e.cost,
				"tool_calls": e.tool_calls,
				"tools_used": e.tools_used,
				"task_time": e.task_time,
				"ai_time": e.ai_time,
				"processing_time": e.processing_time
			})).collect::<Vec<_>>(),
			"totals": {
				"total_cost": self.totals.total_cost,
				"total_tool_calls": self.totals.total_tool_calls,
				"total_task_time_ms": self.totals.total_task_time_ms,
				"total_ai_time_ms": self.totals.total_ai_time_ms,
				"total_processing_time_ms": self.totals.total_processing_time_ms,
				"total_requests": self.totals.total_requests
			}
		})
	}

	/// Display report as plain text (fallback)
	fn display_plain(&self, markdown_report: &str) {
		// Convert markdown to plain text for fallback
		let plain_text = markdown_report
			.replace("# ", "")
			.replace("## ", "")
			.replace("**", "")
			.replace("*", "");
		// Use print! instead of println! to avoid extra newline since content may already have them
		print!("{}", plain_text);
	}
}