vtcode_core/utils/session_archive/
query.rs1use std::fs;
2use std::path::{Path, PathBuf};
3use std::time::Instant;
4
5use anyhow::{Context, Result};
6use serde::Serialize;
7
8use super::SESSION_FILE_EXTENSION;
9use super::identifier::session_archive_path_for_identifier;
10use super::settings::{SESSION_DIR_ENV, read_env_var_os};
11use super::snapshot::{
12 SessionArchiveSummary, SessionListHeader, SessionListing, SessionSnapshot, normalize_list_query_workspace,
13 raw_workspace_path_matches_query,
14};
15use chrono::{DateTime, Utc};
16use vtcode_commons::VtCodePaths;
17use vtcode_commons::fs::{read_private_file_no_follow, read_private_json_file};
18
19pub(crate) async fn resolve_sessions_dir_for_archive_writes() -> Result<PathBuf> {
20 resolve_sessions_dir().await
21}
22
23pub async fn list_recent_sessions(limit: usize) -> Result<Vec<SessionListing>> {
24 list_recent_sessions_matching(limit, None, |listing| listing).await
25}
26
27pub async fn list_recent_sessions_in_workspace(limit: usize, workspace: &Path) -> Result<Vec<SessionListing>> {
29 list_recent_sessions_matching(limit, Some(workspace), |listing| listing).await
30}
31
32pub async fn list_recent_session_summaries_in_workspace(
34 limit: usize,
35 workspace: &Path,
36) -> Result<Vec<SessionArchiveSummary>> {
37 list_recent_sessions_matching(limit, Some(workspace), SessionListing::into_summary).await
38}
39
40struct ScannedSession {
43 path: PathBuf,
44 ended_at: DateTime<Utc>,
45 workspace_path: String,
46 bytes: Vec<u8>,
47}
48
49async fn scan_session_headers() -> Result<Vec<ScannedSession>> {
54 let sessions_dir = match resolve_sessions_dir().await {
55 Ok(dir) => dir,
56 Err(_) => return Ok(Vec::new()),
57 };
58
59 if !sessions_dir.exists() {
60 return Ok(Vec::new());
61 }
62
63 let session_paths: Vec<PathBuf> = tokio::task::spawn_blocking(move || -> Result<Vec<PathBuf>> {
67 let mut paths = Vec::new();
68 for entry in fs::read_dir(&sessions_dir)
69 .with_context(|| format!("failed to read session directory: {}", sessions_dir.display()))?
70 {
71 let entry = entry.with_context(|| format!("failed to read session entry in {}", sessions_dir.display()))?;
72 let path = entry.path();
73 if is_session_file(&path) {
74 paths.push(path);
75 }
76 }
77 Ok(paths)
78 })
79 .await
80 .context("session directory scan task panicked")??;
81
82 const BATCH_SIZE: usize = 10;
85 let mut scanned = Vec::new();
86
87 for batch in session_paths.chunks(BATCH_SIZE) {
88 let mut tasks = Vec::with_capacity(batch.len());
89
90 for path in batch {
91 let path = path.clone();
92 let task = tokio::task::spawn(async move {
93 let bytes = match read_private_file_no_follow(&path).await {
94 Ok(bytes) => bytes,
95 Err(_) => return None,
96 };
97 let header: SessionListHeader = match serde_json::from_slice(&bytes) {
98 Ok(header) => header,
99 Err(_) => return None,
100 };
101 Some(ScannedSession {
102 path,
103 ended_at: header.ended_at,
104 workspace_path: header.metadata.workspace_path,
105 bytes,
106 })
107 });
108 tasks.push(task);
109 }
110
111 for task in tasks {
113 if let Ok(Some(entry)) = task.await {
114 scanned.push(entry);
115 }
116 }
117 }
118
119 scanned.sort_by_key(|entry| std::cmp::Reverse(entry.ended_at));
120 Ok(scanned)
121}
122
123async fn list_recent_sessions_matching<T, Project>(
124 limit: usize,
125 workspace: Option<&Path>,
126 project: Project,
127) -> Result<Vec<T>>
128where
129 T: Send + 'static,
130 Project: Fn(SessionListing) -> T + Copy + Send + 'static,
131{
132 let total_started = Instant::now();
133 let scan_started = Instant::now();
134 let scanned = scan_session_headers().await?;
135 let scan_elapsed = scan_started.elapsed();
136
137 let normalized_workspace = workspace.map(normalize_list_query_workspace);
141 let take = if limit > 0 { limit } else { usize::MAX };
142 let mut selected = Vec::with_capacity(take.min(scanned.len()));
143 let mut matching_sessions = 0;
144 let materialize_started = Instant::now();
145
146 for entry in &scanned {
147 if normalized_workspace
148 .as_deref()
149 .is_some_and(|query| !raw_workspace_path_matches_query(&entry.workspace_path, query))
150 {
151 continue;
152 }
153 matching_sessions += 1;
154 if selected.len() >= take {
155 continue;
156 }
157 let snapshot: SessionSnapshot = match serde_json::from_slice(&entry.bytes) {
158 Ok(snapshot) => snapshot,
159 Err(error) => {
160 tracing::debug!(
161 path = %entry.path.display(),
162 %error,
163 "skipping archive that fails full snapshot parse"
164 );
165 continue;
166 }
167 };
168 selected.push(project(SessionListing { path: entry.path.clone(), snapshot }));
169 }
170 let materialize_elapsed = materialize_started.elapsed();
171
172 tracing::debug!(
173 target: "vtcode::session_archive",
174 scanned_files = scanned.len(),
175 matching_sessions,
176 returned_sessions = selected.len(),
177 workspace_filtered = workspace.is_some(),
178 header_scan = ?scan_elapsed,
179 materialize = ?materialize_elapsed,
180 total = ?total_started.elapsed(),
181 "listed session archives"
182 );
183
184 Ok(selected)
185}
186
187pub async fn find_session_by_identifier(identifier: &str) -> Result<Option<SessionListing>> {
189 let sessions_dir = match resolve_sessions_dir().await {
190 Ok(dir) => dir,
191 Err(_) => return Ok(None),
192 };
193
194 if !sessions_dir.exists() {
195 return Ok(None);
196 }
197
198 let path = match session_archive_path_for_identifier(&sessions_dir, identifier) {
199 Ok(path) => path,
200 Err(_) => return Ok(None),
201 };
202 match tokio::fs::symlink_metadata(&path).await {
203 Ok(metadata) if metadata.file_type().is_symlink() || !metadata.is_file() => return Ok(None),
204 Ok(_) => {}
205 Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
206 Err(error) => {
207 return Err(error).with_context(|| format!("failed to inspect session archive {}", path.display()));
208 }
209 }
210
211 let snapshot: SessionSnapshot = read_private_json_file(&path).await?;
212 Ok(Some(SessionListing { path, snapshot }))
213}
214
215pub(crate) fn write_private_json_file_sync<T: Serialize>(path: &Path, value: &T) -> Result<()> {
216 let contents =
217 serde_json::to_vec_pretty(value).with_context(|| format!("failed to serialize {}", path.display()))?;
218 VtCodePaths::write_private_file_atomic(path, &contents)
219 .with_context(|| format!("failed to write private session archive {}", path.display()))
220}
221
222pub async fn find_session_by_id_or_name(id_or_name: &str) -> Result<SessionListing> {
228 if let Some(listing) = find_session_by_identifier(id_or_name).await? {
230 return Ok(listing);
231 }
232
233 let normalized_query = id_or_name.to_lowercase();
239
240 for entry in scan_session_headers().await?.into_iter().take(200) {
241 let stem_matches = entry
243 .path
244 .file_stem()
245 .and_then(|stem| stem.to_str())
246 .is_some_and(|stem| stem.to_lowercase().contains(&normalized_query));
247 if !stem_matches {
248 continue;
249 }
250 let snapshot: SessionSnapshot = match serde_json::from_slice(&entry.bytes) {
251 Ok(snapshot) => snapshot,
252 Err(_) => continue,
253 };
254 return Ok(SessionListing { path: entry.path, snapshot });
255 }
256
257 Err(anyhow::anyhow!("No saved chat found matching '{id_or_name}'."))
258}
259
260pub async fn delete_session_archive(identifier: &str) -> Result<bool> {
263 let sessions_dir = match resolve_sessions_dir().await {
264 Ok(dir) => dir,
265 Err(_) => return Ok(false),
266 };
267
268 if !sessions_dir.exists() {
269 return Ok(false);
270 }
271
272 let path = session_archive_path_for_identifier(&sessions_dir, identifier)?;
273 match tokio::fs::symlink_metadata(&path).await {
274 Ok(metadata) if metadata.file_type().is_symlink() || !metadata.is_file() => return Ok(false),
275 Ok(_) => {}
276 Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(false),
277 Err(error) => {
278 return Err(error).with_context(|| format!("failed to inspect session archive {}", path.display()));
279 }
280 }
281
282 tokio::fs::remove_file(&path)
283 .await
284 .with_context(|| format!("failed to delete session archive {}", path.display()))?;
285 Ok(true)
286}
287
288pub async fn sessions_dir() -> Result<PathBuf> {
290 resolve_sessions_dir().await
291}
292
293async fn resolve_sessions_dir() -> Result<PathBuf> {
294 if let Some(custom) = read_env_var_os(SESSION_DIR_ENV) {
295 let path = PathBuf::from(custom);
296 VtCodePaths::ensure_user_dir(&path)
297 .with_context(|| format!("failed to initialize session directory {}", path.display()))?;
298 return Ok(path);
299 }
300
301 let paths = VtCodePaths::resolve().context("failed to resolve VT Code paths")?;
302 paths
303 .ensure_state_dir()
304 .context("failed to initialize VT Code state directory")?;
305 let dir = paths.state_path("sessions")?;
306 VtCodePaths::ensure_user_dir(&dir)
307 .with_context(|| format!("failed to initialize session directory {}", dir.display()))?;
308 Ok(dir)
309}
310
311pub(crate) fn is_session_file(path: &Path) -> bool {
312 matches!(
313 path.extension().and_then(|ext| ext.to_str()),
314 Some(ext)
315 if ext.eq_ignore_ascii_case(SESSION_FILE_EXTENSION)
316 || ext.eq_ignore_ascii_case("jsonl")
317 || ext.eq_ignore_ascii_case("log")
318 )
319}
320
321#[cfg(test)]
322mod tests;