1use crate::context::AppContext;
4use crate::context::SemanticIndexStatus;
5use crate::protocol::{RawRequest, Response, StatusPayload, DEFAULT_SESSION_ID};
6
7pub fn handle_status(req: &RawRequest, ctx: &AppContext) -> Response {
8 Response::success(
9 &req.id,
10 ctx.build_status_snapshot_for_session(req.session()),
11 )
12}
13
14impl AppContext {
15 pub fn build_status_snapshot(&self) -> StatusPayload {
16 self.build_status_snapshot_for_session(DEFAULT_SESSION_ID)
17 }
18
19 pub fn build_status_snapshot_for_session(&self, session_id: &str) -> StatusPayload {
20 let config = self.config();
21
22 let search_index_info = {
24 let index = self.search_index().borrow();
25 match index.as_ref() {
26 Some(idx) if idx.ready => {
27 let file_count = idx.file_count();
28 let trigram_count = idx.trigram_count();
29 serde_json::json!({
30 "status": "ready",
31 "files": file_count,
32 "trigrams": trigram_count,
33 })
34 }
35 Some(_) => serde_json::json!({ "status": "building" }),
36 None => {
37 let status = if self.config().search_index {
38 "loading"
39 } else {
40 "disabled"
41 };
42 serde_json::json!({ "status": status })
43 }
44 }
45 };
46
47 let semantic_index_info = {
49 let index = self.semantic_index().borrow();
50 match index.as_ref() {
51 Some(idx) => {
52 serde_json::json!({
53 "status": idx.status_label(),
54 "entries": idx.entry_count(),
55 "dimension": idx.dimension(),
56 "backend": idx.backend_label().unwrap_or(config.semantic_backend_label()),
57 "model": idx.model_label().unwrap_or(config.semantic.model.as_str()),
58 })
59 }
60 None => match &*self.semantic_index_status().borrow() {
61 SemanticIndexStatus::Disabled => serde_json::json!({
62 "status": "disabled",
63 "backend": config.semantic_backend_label(),
64 "model": config.semantic.model.as_str(),
65 }),
66 SemanticIndexStatus::Building {
67 stage,
68 files,
69 entries_done,
70 entries_total,
71 } => serde_json::json!({
72 "status": "loading",
73 "stage": stage,
74 "files": files,
75 "entries_done": entries_done,
76 "entries_total": entries_total,
77 "backend": config.semantic_backend_label(),
78 "model": config.semantic.model.as_str(),
79 }),
80 SemanticIndexStatus::Ready => serde_json::json!({
81 "status": "ready",
82 "backend": config.semantic_backend_label(),
83 "model": config.semantic.model.as_str(),
84 }),
85 SemanticIndexStatus::Failed(error) => serde_json::json!({
86 "status": "failed",
87 "error": error,
88 "backend": config.semantic_backend_label(),
89 "model": config.semantic.model.as_str(),
90 }),
91 },
92 }
93 };
94
95 let storage_dir = config.storage_dir.as_ref().map(|d| d.display().to_string());
111 let disk_info = match (&config.storage_dir, &config.project_root) {
112 (Some(dir), Some(root)) => {
113 let key = crate::search_index::project_cache_key(root);
114 let trigram_size = dir_size(&dir.join("index").join(&key));
115 let semantic_size = dir_size(&dir.join("semantic").join(&key));
116 serde_json::json!({
117 "storage_dir": dir.display().to_string(),
118 "project_cache_key": key,
119 "trigram_disk_bytes": trigram_size,
120 "semantic_disk_bytes": semantic_size,
121 })
122 }
123 (Some(dir), None) => serde_json::json!({
124 "storage_dir": dir.display().to_string(),
125 "project_cache_key": null,
126 "trigram_disk_bytes": 0,
127 "semantic_disk_bytes": 0,
128 }),
129 _ => serde_json::json!({
130 "storage_dir": null,
131 "project_cache_key": null,
132 "trigram_disk_bytes": 0,
133 "semantic_disk_bytes": 0,
134 }),
135 };
136
137 let lsp_count = self.lsp_server_count();
139
140 let symbol_cache_stats = self.symbol_cache_stats();
142
143 let checkpoint_total = self.checkpoint().borrow().total_count();
147 let session_checkpoints = self.checkpoint().borrow().list(session_id).len();
148 let session_tracked_files = self.backup().borrow().tracked_files(session_id).len();
149
150 serde_json::json!({
151 "version": env!("CARGO_PKG_VERSION"),
152 "project_root": config.project_root.as_ref().map(|p| p.display().to_string()),
153 "canonical_root": self.canonical_cache_root_opt().map(|p| p.display().to_string()),
154 "cache_role": self.cache_role(),
155 "features": {
156 "format_on_edit": config.format_on_edit,
157 "validate_on_edit": config.validate_on_edit.as_deref().unwrap_or("off"),
158 "restrict_to_project_root": config.restrict_to_project_root,
159 "search_index": config.search_index,
160 "semantic_search": config.semantic_search,
161 },
162 "search_index": search_index_info,
163 "semantic_index": semantic_index_info,
164 "disk": disk_info,
165 "lsp_servers": lsp_count,
166 "symbol_cache": symbol_cache_stats,
167 "storage_dir": storage_dir,
168 "checkpoints_total": checkpoint_total,
170 "session": {
172 "id": session_id,
173 "tracked_files": session_tracked_files,
174 "checkpoints": session_checkpoints,
175 },
176 })
177 }
178}
179
180fn dir_size(path: &std::path::Path) -> u64 {
182 if !path.exists() {
183 return 0;
184 }
185 dir_size_recursive(path)
186}
187
188fn dir_size_recursive(path: &std::path::Path) -> u64 {
189 let mut total = 0u64;
190 let entries = match std::fs::read_dir(path) {
191 Ok(e) => e,
192 Err(_) => return 0,
193 };
194 for entry in entries.flatten() {
195 let ft = match entry.file_type() {
196 Ok(ft) => ft,
197 Err(_) => continue,
198 };
199 if ft.is_file() {
200 total += entry.metadata().map(|m| m.len()).unwrap_or(0);
201 } else if ft.is_dir() {
202 total += dir_size_recursive(&entry.path());
203 }
204 }
205 total
206}
207
208#[cfg(test)]
209mod tests {
210 use super::handle_status;
211 use crate::config::Config;
212 use crate::context::AppContext;
213 use crate::parser::TreeSitterProvider;
214 use crate::protocol::RawRequest;
215 use serde_json::json;
216
217 fn request() -> RawRequest {
218 RawRequest {
219 id: "status".to_string(),
220 command: "status".to_string(),
221 lsp_hints: None,
222 session_id: None,
223 params: json!({}),
224 }
225 }
226
227 #[test]
228 fn status_exposes_cache_role_and_canonical_root() {
229 let ctx = AppContext::new(Box::new(TreeSitterProvider::new()), Config::default());
230 let response = handle_status(&request(), &ctx);
231 assert_eq!(response.data["cache_role"], "not_initialized");
232 assert!(response.data["canonical_root"].is_null());
233
234 let temp = tempfile::tempdir().unwrap();
235 ctx.config_mut().project_root = Some(temp.path().to_path_buf());
236 ctx.set_canonical_cache_root(std::fs::canonicalize(temp.path()).unwrap());
237 ctx.set_cache_role(false, None);
238 let response = handle_status(&request(), &ctx);
239 assert_eq!(response.data["cache_role"], "main");
240 assert!(response.data["canonical_root"].as_str().is_some());
241
242 ctx.set_cache_role(true, None);
243 let response = handle_status(&request(), &ctx);
244 assert_eq!(response.data["cache_role"], "worktree");
245 }
246}