vtcode_core/utils/session_archive/
snapshot.rs1use std::env;
2use std::path::{Path, PathBuf};
3
4use anyhow::{Context, Result};
5use chrono::{DateTime, Utc};
6use serde::{Deserialize, Serialize};
7
8use super::identifier::validate_session_identifier;
9use super::message::SessionMessage;
10use super::metadata::SessionArchiveMetadata;
11use super::shrink::truncate_preview;
12use crate::core::agent::snapshots::SnapshotTurnDiagnostics;
13use crate::llm::provider::MessageRole;
14use crate::utils::error_log_collector::ErrorLogEntry;
15
16#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
17pub struct SessionSnapshot {
18 pub metadata: SessionArchiveMetadata,
19 pub started_at: DateTime<Utc>,
20 pub ended_at: DateTime<Utc>,
21 pub total_messages: usize,
22 pub distinct_tools: Vec<String>,
23 pub transcript: Vec<String>,
24 #[serde(default)]
25 pub messages: Vec<SessionMessage>,
26 #[serde(default, skip_serializing_if = "Option::is_none")]
28 pub progress: Option<Box<SessionProgress>>,
29 #[serde(default, skip_serializing_if = "Vec::is_empty")]
31 pub error_logs: Vec<ErrorLogEntry>,
32}
33
34#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
35pub struct SessionProgress {
36 pub turn_number: usize,
37 #[serde(default)]
38 pub recent_messages: Vec<SessionMessage>,
39 #[serde(default)]
40 pub tool_summaries: Vec<String>,
41 #[serde(default, skip_serializing_if = "Option::is_none")]
42 pub token_usage: Option<String>,
43 #[serde(default, skip_serializing_if = "Option::is_none")]
44 pub max_context_tokens: Option<usize>,
45 #[serde(default)]
47 pub loaded_skills: Vec<String>,
48 #[serde(default, skip_serializing_if = "Option::is_none")]
51 pub turn_diagnostics: Option<SnapshotTurnDiagnostics>,
52}
53
54#[derive(Debug, Clone)]
55pub struct SessionListing {
56 pub path: PathBuf,
57 pub snapshot: SessionSnapshot,
58}
59
60#[derive(Debug, Deserialize)]
66pub(crate) struct SessionListHeader {
67 pub metadata: SessionListHeaderMetadata,
68 pub ended_at: DateTime<Utc>,
69}
70
71#[derive(Debug, Deserialize)]
73pub(crate) struct SessionListHeaderMetadata {
74 #[serde(default)]
75 pub workspace_path: String,
76}
77
78#[derive(Debug, Clone, PartialEq, Eq)]
80pub struct SessionArchiveSummary {
81 pub identifier: String,
83 pub title: Option<String>,
85 pub workspace_path: String,
87 pub completed: bool,
89 pub resumable: bool,
91 pub size_bytes: u64,
93 pub updated_at: u64,
95}
96
97#[derive(Debug, Clone, PartialEq, Eq)]
103pub struct VerifiedSessionArchiveIdentifier(pub(crate) String);
104
105impl VerifiedSessionArchiveIdentifier {
106 #[must_use]
108 pub fn as_str(&self) -> &str {
109 &self.0
110 }
111}
112
113#[derive(Debug, Clone)]
114pub struct SessionProgressArgs {
115 pub total_messages: usize,
116 pub distinct_tools: Vec<String>,
117 pub messages: Vec<SessionMessage>,
118 pub recent_messages: Vec<SessionMessage>,
119 pub turn_number: usize,
120 pub token_usage: Option<String>,
121 pub max_context_tokens: Option<usize>,
122 pub loaded_skills: Option<Vec<String>>,
123 pub turn_diagnostics: Option<SnapshotTurnDiagnostics>,
125}
126
127#[derive(Debug, Clone, PartialEq, Eq)]
129pub enum SessionProgressPersistenceStatus {
130 Persisted(PathBuf),
132 Throttled(PathBuf),
134 Disabled(PathBuf),
136}
137
138impl SessionProgressPersistenceStatus {
139 #[must_use]
141 pub fn path(&self) -> &Path {
142 match self {
143 Self::Persisted(path) | Self::Throttled(path) | Self::Disabled(path) => path,
144 }
145 }
146
147 #[must_use]
150 pub fn is_persisted(&self) -> bool {
151 matches!(self, Self::Persisted(_))
152 }
153}
154
155impl SessionListing {
156 pub fn identifier(&self) -> String {
157 self.path
158 .file_stem()
159 .and_then(|value| value.to_str())
160 .map(|value| value.to_string())
161 .unwrap_or_else(|| self.path.display().to_string())
162 }
163
164 pub(crate) fn verified_identifier(&self) -> Result<VerifiedSessionArchiveIdentifier> {
166 let identifier = self
167 .path
168 .file_stem()
169 .and_then(|value| value.to_str())
170 .with_context(|| format!("session archive path has no valid identifier: {}", self.path.display()))?;
171 validate_session_identifier(identifier)?;
172 Ok(VerifiedSessionArchiveIdentifier(identifier.to_owned()))
173 }
174
175 pub fn first_prompt_preview(&self) -> Option<String> {
176 self.preview_for_role(MessageRole::User)
177 }
178
179 pub fn first_reply_preview(&self) -> Option<String> {
180 self.preview_for_role(MessageRole::Assistant)
181 }
182
183 pub fn size_bytes(&self) -> u64 {
185 std::fs::metadata(&self.path).map(|metadata| metadata.len()).unwrap_or(0)
186 }
187
188 pub fn updated_at(&self) -> u64 {
190 u64::try_from(self.snapshot.ended_at.timestamp()).unwrap_or(0)
191 }
192
193 pub(crate) fn into_summary(self) -> SessionArchiveSummary {
195 let size_bytes = self.size_bytes();
196 let updated_at = self.updated_at();
197 let identifier = self.identifier();
198 let title = self.first_prompt_preview();
199 let completed = self.snapshot.progress.is_none();
200 let resumable = !self.snapshot.messages.is_empty();
201 let workspace_path = self.snapshot.metadata.workspace_path;
202 SessionArchiveSummary {
203 identifier,
204 title,
205 workspace_path,
206 completed,
207 resumable,
208 size_bytes,
209 updated_at,
210 }
211 }
212
213 fn preview_for_role(&self, role: MessageRole) -> Option<String> {
214 self.snapshot.messages.iter().find_map(|message| {
215 if message.role != role {
216 return None;
217 }
218
219 let text_projection = message.content.as_text();
220 if text_projection.trim().is_empty() {
221 return None;
222 }
223
224 text_projection.lines().find_map(|line| {
225 let trimmed = line.trim();
226 if trimmed.is_empty() {
227 None
228 } else {
229 Some(truncate_preview(trimmed, 80))
230 }
231 })
232 })
233 }
234}
235
236fn normalize_workspace_for_match(path: &Path) -> PathBuf {
237 let absolute = if path.is_absolute() {
238 path.to_path_buf()
239 } else {
240 env::current_dir().unwrap_or_else(|_| PathBuf::from(".")).join(path)
241 };
242
243 crate::utils::path::normalize_path(&absolute)
244}
245
246pub fn session_workspace_path(listing: &SessionListing) -> Option<PathBuf> {
247 let raw = listing.snapshot.metadata.workspace_path.trim();
248 if raw.is_empty() { None } else { Some(PathBuf::from(raw)) }
249}
250
251pub fn session_listing_matches_workspace(listing: &SessionListing, workspace: &Path) -> bool {
252 raw_workspace_path_matches_query(
253 &listing.snapshot.metadata.workspace_path,
254 &normalize_workspace_for_match(workspace),
255 )
256}
257
258pub(crate) fn normalize_list_query_workspace(path: &Path) -> PathBuf {
261 normalize_workspace_for_match(path)
262}
263
264pub(crate) fn raw_workspace_path_matches_query(workspace_path: &str, normalized_query: &Path) -> bool {
269 let raw = workspace_path.trim();
270 if raw.is_empty() {
271 return false;
272 }
273
274 normalize_workspace_for_match(Path::new(raw)).as_path() == normalized_query
275}