1use crate::context::AppContext;
4use crate::context::SemanticIndexStatus;
5use crate::db::compression_events::CompressionAggregate;
6use crate::protocol::{RawRequest, Response, StatusPayload, DEFAULT_SESSION_ID};
7
8#[derive(Debug, Clone, Default, serde::Serialize)]
9pub struct CompressionStats {
10 pub project: CompressionAggregateSerde,
11 pub session: CompressionAggregateSerde,
12}
13
14#[derive(Debug, Clone, Default, serde::Serialize)]
15pub struct CompressionAggregateSerde {
16 pub events: u64,
17 pub original_tokens: u64,
18 pub compressed_tokens: u64,
19 pub savings_tokens: u64,
20}
21
22impl From<CompressionAggregate> for CompressionAggregateSerde {
23 fn from(agg: CompressionAggregate) -> Self {
24 Self {
25 events: agg.events,
26 original_tokens: agg.original_tokens,
27 compressed_tokens: agg.compressed_tokens,
28 savings_tokens: agg.savings_tokens(),
29 }
30 }
31}
32
33pub fn handle_status(req: &RawRequest, ctx: &AppContext) -> Response {
34 Response::success(
35 &req.id,
36 ctx.build_status_snapshot_for_session(req.session()),
37 )
38}
39
40impl AppContext {
41 pub fn build_status_snapshot(&self) -> StatusPayload {
42 self.build_status_snapshot_for_session(DEFAULT_SESSION_ID)
43 }
44
45 pub fn build_status_snapshot_for_session(&self, session_id: &str) -> StatusPayload {
46 let config = self.config();
47
48 let search_index_info = {
50 let index = self
51 .search_index()
52 .read()
53 .unwrap_or_else(std::sync::PoisonError::into_inner);
54 match index.as_ref() {
55 Some(idx) if idx.ready => {
56 let file_count = idx.file_count();
57 let trigram_count = idx.trigram_count();
58 serde_json::json!({
59 "status": "ready",
60 "files": file_count,
61 "trigrams": trigram_count,
62 })
63 }
64 Some(_) => serde_json::json!({ "status": "building" }),
65 None => {
66 let status = if config.search_index {
67 "loading"
68 } else {
69 "disabled"
70 };
71 serde_json::json!({ "status": status })
72 }
73 }
74 };
75
76 let semantic_index_info = {
78 let status = self
79 .semantic_index_status()
80 .read()
81 .unwrap_or_else(std::sync::PoisonError::into_inner)
82 .clone();
83 let refreshing_count = status.refreshing_count();
84 let index = self
85 .semantic_index()
86 .read()
87 .unwrap_or_else(std::sync::PoisonError::into_inner);
88 match index.as_ref() {
89 Some(idx) => {
90 let status_label = match status {
91 SemanticIndexStatus::Ready { .. } => "ready",
92 _ => idx.status_label(),
93 };
94 serde_json::json!({
95 "status": status_label,
96 "state": status_label,
97 "refreshing_count": refreshing_count,
98 "entries": idx.entry_count(),
99 "dimension": idx.dimension(),
100 "backend": idx.backend_label().unwrap_or(config.semantic_backend_label()),
101 "model": idx.model_label().unwrap_or(config.semantic.model.as_str()),
102 })
103 }
104 None => match status {
105 SemanticIndexStatus::Disabled => serde_json::json!({
106 "status": "disabled",
107 "state": "disabled",
108 "refreshing_count": 0,
109 "backend": config.semantic_backend_label(),
110 "model": config.semantic.model.as_str(),
111 }),
112 SemanticIndexStatus::Building {
113 stage,
114 files,
115 entries_done,
116 entries_total,
117 } => serde_json::json!({
118 "status": "loading",
119 "state": "loading",
120 "refreshing_count": 0,
121 "stage": stage,
122 "files": files,
123 "entries_done": entries_done,
124 "entries_total": entries_total,
125 "backend": config.semantic_backend_label(),
126 "model": config.semantic.model.as_str(),
127 }),
128 SemanticIndexStatus::Ready { refreshing, .. } => serde_json::json!({
129 "status": "ready",
130 "state": "ready",
131 "refreshing_count": refreshing.len(),
132 "backend": config.semantic_backend_label(),
133 "model": config.semantic.model.as_str(),
134 }),
135 SemanticIndexStatus::Failed(error) => serde_json::json!({
136 "status": "failed",
137 "state": "failed",
138 "refreshing_count": 0,
139 "error": error,
140 "backend": config.semantic_backend_label(),
141 "model": config.semantic.model.as_str(),
142 }),
143 },
144 }
145 };
146
147 let storage_dir = config.storage_dir.as_ref().map(|d| d.display().to_string());
163 let disk_info = match (&config.storage_dir, &config.project_root) {
164 (Some(dir), Some(root)) => {
165 let key = crate::search_index::artifact_cache_key(root);
166 let trigram_size = dir_size(&dir.join("index").join(&key));
167 let semantic_size = dir_size(&dir.join("semantic").join(&key));
168 serde_json::json!({
169 "storage_dir": dir.display().to_string(),
170 "project_cache_key": key,
171 "trigram_disk_bytes": trigram_size,
172 "semantic_disk_bytes": semantic_size,
173 })
174 }
175 (Some(dir), None) => serde_json::json!({
176 "storage_dir": dir.display().to_string(),
177 "project_cache_key": null,
178 "trigram_disk_bytes": 0,
179 "semantic_disk_bytes": 0,
180 }),
181 _ => serde_json::json!({
182 "storage_dir": null,
183 "project_cache_key": null,
184 "trigram_disk_bytes": 0,
185 "semantic_disk_bytes": 0,
186 }),
187 };
188
189 let lsp_count = self.lsp_server_count();
191
192 let symbol_cache_stats = self.symbol_cache_stats();
194
195 let checkpoint_total = self.checkpoint().lock().total_count();
199 let session_checkpoints = self.checkpoint().lock().list(session_id).len();
200 let session_tracked_files = self.backup().lock().tracked_files(session_id).len();
201 let compression = self.compression_stats_for_session(session_id);
202
203 let degraded_reasons = self.degraded_reasons();
211 let degraded = !degraded_reasons.is_empty();
212
213 let status_bar = match self.status_bar_counts() {
219 Some(counts) => serde_json::json!({
220 "errors": counts.errors,
221 "warnings": counts.warnings,
222 "dead_code": counts.dead_code,
223 "unused_exports": counts.unused_exports,
224 "duplicates": counts.duplicates,
225 "todos": counts.todos,
226 "tier2_stale": counts.tier2_stale,
227 }),
228 None => serde_json::Value::Null,
229 };
230
231 serde_json::json!({
232 "version": env!("CARGO_PKG_VERSION"),
233 "project_root": config.project_root.as_ref().map(|p| p.display().to_string()),
234 "canonical_root": self.canonical_cache_root_opt().map(|p| p.display().to_string()),
235 "cache_role": self.cache_role(),
236 "degraded": degraded,
237 "degraded_reasons": degraded_reasons,
238 "features": {
239 "format_on_edit": config.format_on_edit,
240 "validate_on_edit": config.validate_on_edit.as_deref().unwrap_or("off"),
241 "restrict_to_project_root": config.restrict_to_project_root,
242 "search_index": config.search_index,
243 "semantic_search": config.semantic_search,
244 "callgraph_store": config.callgraph_store,
245 },
246 "search_index": search_index_info,
247 "semantic_index": semantic_index_info,
248 "status_bar": status_bar,
249 "disk": disk_info,
250 "lsp_servers": lsp_count,
251 "symbol_cache": symbol_cache_stats,
252 "compression": compression,
253 "storage_dir": storage_dir,
254 "checkpoints_total": checkpoint_total,
256 "session": {
258 "id": session_id,
259 "tracked_files": session_tracked_files,
260 "checkpoints": session_checkpoints,
261 },
262 })
263 }
264
265 fn compression_stats_for_session(&self, session_id: &str) -> CompressionStats {
266 let mut compression = CompressionStats::default();
267 let Some(project_root) = self.config().project_root.clone() else {
268 return compression;
269 };
270 let Some(db) = self.db() else {
271 return compression;
272 };
273 let Ok(conn) = db.lock() else {
274 return compression;
275 };
276
277 let harness = self.harness().storage_segment();
278 let project_key = crate::path_identity::project_scope_key(&project_root);
279 if let Ok(project_agg) =
280 crate::db::compression_events::aggregate_for_project(&conn, &harness, &project_key)
281 {
282 compression.project = project_agg.into();
283 }
284 if let Ok(session_agg) = crate::db::compression_events::aggregate_for_session(
285 &conn,
286 &harness,
287 &project_key,
288 session_id,
289 ) {
290 compression.session = session_agg.into();
291 }
292
293 compression
294 }
295}
296
297fn dir_size(path: &std::path::Path) -> u64 {
299 if !path.exists() {
300 return 0;
301 }
302 dir_size_recursive(path)
303}
304
305fn dir_size_recursive(path: &std::path::Path) -> u64 {
306 let mut total = 0u64;
307 let entries = match std::fs::read_dir(path) {
308 Ok(e) => e,
309 Err(_) => return 0,
310 };
311 for entry in entries.flatten() {
312 let ft = match entry.file_type() {
313 Ok(ft) => ft,
314 Err(_) => continue,
315 };
316 if ft.is_file() {
317 total += entry.metadata().map(|m| m.len()).unwrap_or(0);
318 } else if ft.is_dir() {
319 total += dir_size_recursive(&entry.path());
320 }
321 }
322 total
323}
324
325#[cfg(test)]
326mod tests {
327 use super::handle_status;
328 use crate::config::Config;
329 use crate::context::AppContext;
330 use crate::parser::TreeSitterProvider;
331 use crate::protocol::RawRequest;
332 use serde_json::json;
333
334 fn request() -> RawRequest {
335 RawRequest {
336 id: "status".to_string(),
337 command: "status".to_string(),
338 lsp_hints: None,
339 session_id: None,
340 params: json!({}),
341 }
342 }
343
344 #[test]
345 fn status_exposes_cache_role_and_canonical_root() {
346 let ctx = AppContext::new(Box::new(TreeSitterProvider::new()), Config::default());
347 let response = handle_status(&request(), &ctx);
348 assert_eq!(response.data["cache_role"], "not_initialized");
349 assert!(response.data["canonical_root"].is_null());
350
351 let temp = tempfile::tempdir().unwrap();
352 ctx.update_config(|config| {
353 config.project_root = Some(temp.path().to_path_buf());
354 });
355 ctx.set_canonical_cache_root(std::fs::canonicalize(temp.path()).unwrap());
356 ctx.set_cache_role(false, None);
357 let response = handle_status(&request(), &ctx);
358 assert_eq!(response.data["cache_role"], "main");
359 assert!(response.data["canonical_root"].as_str().is_some());
360
361 ctx.set_cache_role(true, None);
362 let response = handle_status(&request(), &ctx);
363 assert_eq!(response.data["cache_role"], "worktree");
364 }
365
366 #[test]
367 fn status_status_bar_is_null_until_tier2_populated() {
368 let ctx = AppContext::new(Box::new(TreeSitterProvider::new()), Config::default());
369 let response = handle_status(&request(), &ctx);
370 assert!(response.data.get("status_bar").is_some());
374 assert!(response.data["status_bar"].is_null());
375
376 ctx.update_status_bar_tier2(Some(3), Some(2), Some(1), Some(5), false);
378 let response = handle_status(&request(), &ctx);
379 assert_eq!(response.data["status_bar"]["dead_code"], 3);
380 assert_eq!(response.data["status_bar"]["unused_exports"], 2);
381 assert_eq!(response.data["status_bar"]["duplicates"], 1);
382 assert_eq!(response.data["status_bar"]["tier2_stale"], false);
383 }
384}