Skip to main content

vtcode_core/utils/session_archive/
snapshot.rs

1use 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    // SessionProgress is heavy and frequently absent in final snapshots.
27    #[serde(default, skip_serializing_if = "Option::is_none")]
28    pub progress: Option<Box<SessionProgress>>,
29    /// ERROR-level log entries captured during the session for post-mortem debugging.
30    #[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    /// Names of skills loaded at checkpoint time
46    #[serde(default)]
47    pub loaded_skills: Vec<String>,
48    /// Diagnostics for the most recently checkpointed turn, including turns
49    /// that ended blocked, cancelled, or aborted before a turn snapshot.
50    #[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/// Minimal projection of [`SessionSnapshot`] used to filter, sort, and limit
61/// archive listings without deserializing transcripts, messages, or progress.
62///
63/// Unknown fields are ignored, so this parses every file a full snapshot
64/// parse accepts. Files it rejects are skipped exactly as a failed full parse.
65#[derive(Debug, Deserialize)]
66pub(crate) struct SessionListHeader {
67    pub metadata: SessionListHeaderMetadata,
68    pub ended_at: DateTime<Utc>,
69}
70
71/// Header-only view of [`SessionArchiveMetadata`](super::metadata::SessionArchiveMetadata).
72#[derive(Debug, Deserialize)]
73pub(crate) struct SessionListHeaderMetadata {
74    #[serde(default)]
75    pub workspace_path: String,
76}
77
78/// Small archive metadata retained by desktop session-list queries.
79#[derive(Debug, Clone, PartialEq, Eq)]
80pub struct SessionArchiveSummary {
81    /// Stable archive identifier.
82    pub identifier: String,
83    /// First user prompt preview, when present.
84    pub title: Option<String>,
85    /// Workspace path recorded in the archive.
86    pub workspace_path: String,
87    /// Whether the saved archive is terminal rather than in progress.
88    pub completed: bool,
89    /// Whether saved messages are available to resume.
90    pub resumable: bool,
91    /// Archive file size in bytes, zero when the file cannot be inspected.
92    pub size_bytes: u64,
93    /// Snapshot end time as unix seconds, zero when out of range.
94    pub updated_at: u64,
95}
96
97/// An archive identifier derived from a loaded session listing.
98///
99/// The inner value is crate-private so callers cannot mark an arbitrary
100/// runtime/session ID as resumable. Obtain one from
101/// [`super::SessionArchive::verify_persisted_resume_identifier`].
102#[derive(Debug, Clone, PartialEq, Eq)]
103pub struct VerifiedSessionArchiveIdentifier(pub(crate) String);
104
105impl VerifiedSessionArchiveIdentifier {
106    /// Borrow the verified archive identifier.
107    #[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    /// Optional diagnostics for the turn represented by this checkpoint.
124    pub turn_diagnostics: Option<SnapshotTurnDiagnostics>,
125}
126
127/// Outcome of an asynchronous session-progress checkpoint.
128#[derive(Debug, Clone, PartialEq, Eq)]
129pub enum SessionProgressPersistenceStatus {
130    /// The archive file was written successfully.
131    Persisted(PathBuf),
132    /// The call was intentionally skipped by the progress throttle.
133    Throttled(PathBuf),
134    /// History persistence is disabled, so no archive file was written.
135    Disabled(PathBuf),
136}
137
138impl SessionProgressPersistenceStatus {
139    /// Return the archive path associated with this checkpoint attempt.
140    #[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    /// Return whether this outcome guarantees that the current snapshot was
148    /// written to the archive.
149    #[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    /// Return an identifier that is safe to advertise as an archive resume target.
165    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    /// Archive file size in bytes, zero when the file cannot be inspected.
184    pub fn size_bytes(&self) -> u64 {
185        std::fs::metadata(&self.path).map(|metadata| metadata.len()).unwrap_or(0)
186    }
187
188    /// Snapshot end time as unix seconds, zero when out of range.
189    pub fn updated_at(&self) -> u64 {
190        u64::try_from(self.snapshot.ended_at.timestamp()).unwrap_or(0)
191    }
192
193    /// Project the fields needed for recent-session navigation and release the full transcript.
194    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
258/// Normalize a list-query workspace once so per-file matching avoids a
259/// repeated `current_dir` + normalization per archive.
260pub(crate) fn normalize_list_query_workspace(path: &Path) -> PathBuf {
261    normalize_workspace_for_match(path)
262}
263
264/// Match a raw `metadata.workspace_path` against a pre-normalized query.
265///
266/// This is the single matching core behind [`session_listing_matches_workspace`];
267/// header scans call it directly with an already-normalized query.
268pub(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}