1use crate::exec::events::ThreadEvent;
2use crate::llm::provider::Message;
3use crate::utils::session_archive::{
4 SessionArchive, SessionArchiveMetadata, SessionForkMode, SessionListing, find_session_by_identifier,
5 list_recent_sessions, reserve_session_archive_identifier, session_listing_matches_workspace,
6};
7use crate::utils::session_debug::runtime_archive_session_id;
8use anyhow::{Result, anyhow};
9use parking_lot::Mutex;
10use std::collections::VecDeque;
11use std::path::{Path, PathBuf};
12use std::sync::Arc;
13
14pub use vtcode_threads::{SubmissionId, ThreadId};
15
16const DEFAULT_EVENT_BUFFER_CAPACITY: usize = 512;
17
18#[derive(Debug, Clone)]
19pub struct ThreadEventRecord {
20 pub sequence: u64,
21 pub thread_id: ThreadId,
22 pub submission_id: Option<SubmissionId>,
23 pub turn_id: Option<String>,
24 pub event: ThreadEvent,
25}
26
27#[derive(Debug, Clone)]
28pub struct ThreadSnapshot {
29 pub thread_id: ThreadId,
30 pub metadata: Option<SessionArchiveMetadata>,
31 pub archive_listing: Option<SessionListing>,
32 pub messages: Vec<Message>,
33 pub loaded_skills: Vec<String>,
34 pub turn_in_flight: bool,
35}
36
37#[derive(Debug, Clone)]
38pub struct ThreadBootstrap {
39 pub metadata: Option<SessionArchiveMetadata>,
40 pub archive_listing: Option<SessionListing>,
41 pub messages: Vec<Message>,
42 pub loaded_skills: Vec<String>,
43}
44
45impl ThreadBootstrap {
46 pub fn new(metadata: Option<SessionArchiveMetadata>) -> Self {
47 Self {
48 metadata,
49 archive_listing: None,
50 messages: Vec::new(),
51 loaded_skills: Vec::new(),
52 }
53 }
54
55 pub fn from_listing(listing: SessionListing) -> Self {
56 Self {
57 metadata: Some(listing.snapshot.metadata.clone()),
58 messages: messages_from_session_listing(&listing),
59 loaded_skills: loaded_skills_from_session_listing(&listing),
60 archive_listing: Some(listing),
61 }
62 }
63
64 pub fn from_snapshot(snapshot: ThreadSnapshot) -> Self {
65 Self {
66 metadata: snapshot.metadata,
67 archive_listing: snapshot.archive_listing,
68 messages: snapshot.messages,
69 loaded_skills: snapshot.loaded_skills,
70 }
71 }
72
73 pub fn with_messages(mut self, messages: Vec<Message>) -> Self {
74 self.messages = messages;
75 self
76 }
77
78 pub fn with_loaded_skills(mut self, loaded_skills: Vec<String>) -> Self {
79 self.loaded_skills = loaded_skills;
80 self
81 }
82}
83
84#[derive(Debug, Clone, PartialEq, Eq)]
85pub enum SessionQueryScope {
86 CurrentWorkspace(PathBuf),
87 All,
88}
89
90#[derive(Debug, Clone, PartialEq, Eq)]
91pub enum ArchivedSessionIntent {
92 ResumeInPlace,
93 ForkNewArchive {
94 custom_suffix: Option<String>,
95 summarize: bool,
96 },
97}
98
99#[derive(Debug, Clone)]
100pub struct PreparedArchivedSession {
101 pub source: SessionListing,
102 pub workspace: PathBuf,
103 pub bootstrap: ThreadBootstrap,
104 pub thread_id: String,
105 pub archive: SessionArchive,
106}
107
108#[derive(Default)]
109struct ThreadEventStore {
110 capacity: usize,
111 next_sequence: u64,
112 events: VecDeque<ThreadEventRecord>,
113}
114
115impl ThreadEventStore {
116 fn with_capacity(capacity: usize) -> Self {
117 Self { capacity: capacity.max(1), ..Self::default() }
118 }
119
120 fn push(
121 &mut self,
122 thread_id: &ThreadId,
123 submission_id: Option<SubmissionId>,
124 turn_id: Option<String>,
125 event: ThreadEvent,
126 ) {
127 let record = ThreadEventRecord {
128 sequence: self.next_sequence,
129 thread_id: thread_id.clone(),
130 submission_id,
131 turn_id,
132 event,
133 };
134 self.next_sequence = self.next_sequence.saturating_add(1);
135
136 if self.events.len() >= self.capacity {
137 self.events.pop_front();
138 }
139 self.events.push_back(record);
140 }
141
142 fn snapshot(&self) -> Vec<ThreadEventRecord> {
143 self.events.iter().cloned().collect()
144 }
145}
146
147struct ThreadSessionState {
148 thread_id: ThreadId,
149 metadata: Option<SessionArchiveMetadata>,
150 archive_listing: Option<SessionListing>,
151 messages: Vec<Message>,
152 loaded_skills: Vec<String>,
153 turn_in_flight: bool,
154}
155
156impl ThreadSessionState {
157 fn snapshot(&self) -> ThreadSnapshot {
158 ThreadSnapshot {
159 thread_id: self.thread_id.clone(),
160 metadata: self.metadata.clone(),
161 archive_listing: self.archive_listing.clone(),
162 messages: self.messages.clone(),
163 loaded_skills: self.loaded_skills.clone(),
164 turn_in_flight: self.turn_in_flight,
165 }
166 }
167}
168
169#[derive(Clone)]
170pub struct ThreadRuntimeHandle {
171 inner: Arc<ThreadRuntimeInner>,
172}
173
174struct ThreadRuntimeInner {
175 session: Mutex<ThreadSessionState>,
176 event_store: Mutex<ThreadEventStore>,
177}
178
179impl ThreadRuntimeHandle {
180 fn new(thread_id: ThreadId, bootstrap: ThreadBootstrap, event_capacity: usize) -> Self {
181 let session = ThreadSessionState {
182 thread_id,
183 metadata: bootstrap.metadata,
184 archive_listing: bootstrap.archive_listing,
185 messages: bootstrap.messages,
186 loaded_skills: bootstrap.loaded_skills,
187 turn_in_flight: false,
188 };
189
190 Self {
191 inner: Arc::new(ThreadRuntimeInner {
192 session: Mutex::new(session),
193 event_store: Mutex::new(ThreadEventStore::with_capacity(event_capacity)),
194 }),
195 }
196 }
197
198 pub fn thread_id(&self) -> ThreadId {
199 self.inner.session.lock().thread_id.clone()
200 }
201
202 pub fn snapshot(&self) -> ThreadSnapshot {
203 self.inner.session.lock().snapshot()
204 }
205
206 pub fn metadata(&self) -> Option<SessionArchiveMetadata> {
207 self.inner.session.lock().metadata.clone()
208 }
209
210 pub fn replace_metadata(&self, metadata: Option<SessionArchiveMetadata>) {
211 self.inner.session.lock().metadata = metadata;
212 }
213
214 pub fn archive_listing(&self) -> Option<SessionListing> {
215 self.inner.session.lock().archive_listing.clone()
216 }
217
218 pub fn messages(&self) -> Vec<Message> {
219 self.inner.session.lock().messages.clone()
220 }
221
222 pub fn replace_messages(&self, messages: Vec<Message>) {
223 self.inner.session.lock().messages = messages;
224 }
225
226 pub fn append_message(&self, message: Message) {
227 self.inner.session.lock().messages.push(message);
228 }
229
230 pub fn begin_turn(&self) -> Result<SubmissionId> {
231 let mut session = self.inner.session.lock();
232 if session.turn_in_flight {
233 return Err(anyhow!("thread '{}' already has an in-flight turn", session.thread_id));
234 }
235
236 session.turn_in_flight = true;
237 Ok(SubmissionId::generate())
238 }
239
240 pub fn finish_turn(&self) {
241 self.inner.session.lock().turn_in_flight = false;
242 }
243
244 pub fn record_event(&self, submission_id: Option<SubmissionId>, turn_id: Option<String>, event: ThreadEvent) {
245 let thread_id = self.thread_id();
246 self.inner.event_store.lock().push(&thread_id, submission_id, turn_id, event);
247 }
248
249 pub fn replay_recent(&self) -> Vec<ThreadEventRecord> {
250 self.inner.event_store.lock().snapshot()
251 }
252
253 pub fn recent_events(&self) -> Vec<ThreadEvent> {
254 self.replay_recent().into_iter().map(|record| record.event).collect()
255 }
256}
257
258#[derive(Clone)]
259pub struct ThreadManager {
260 event_buffer_capacity: usize,
261}
262
263impl Default for ThreadManager {
264 fn default() -> Self {
265 Self::new()
266 }
267}
268
269impl ThreadManager {
270 pub fn new() -> Self {
271 Self {
272 event_buffer_capacity: DEFAULT_EVENT_BUFFER_CAPACITY,
273 }
274 }
275
276 pub fn with_event_buffer_capacity(event_buffer_capacity: usize) -> Self {
277 Self {
278 event_buffer_capacity: event_buffer_capacity.max(1),
279 }
280 }
281
282 pub fn start_thread_with_identifier(
283 &self,
284 identifier: impl Into<String>,
285 bootstrap: ThreadBootstrap,
286 ) -> ThreadRuntimeHandle {
287 ThreadRuntimeHandle::new(ThreadId::new(identifier.into()), bootstrap, self.event_buffer_capacity)
288 }
289
290 pub async fn start_thread(
291 &self,
292 workspace_label: &str,
293 custom_suffix: Option<String>,
294 bootstrap: ThreadBootstrap,
295 ) -> Result<ThreadRuntimeHandle> {
296 let identifier = reserve_session_archive_identifier(workspace_label, custom_suffix).await?;
297 Ok(self.start_thread_with_identifier(identifier, bootstrap))
298 }
299
300 pub async fn resume_thread(&self, identifier: &str) -> Result<Option<ThreadRuntimeHandle>> {
301 let listing = find_session_by_identifier(identifier).await?;
302 Ok(listing.map(|listing| {
303 self.start_thread_with_identifier(listing.identifier(), ThreadBootstrap::from_listing(listing))
304 }))
305 }
306}
307
308pub async fn list_recent_sessions_in_scope(limit: usize, scope: &SessionQueryScope) -> Result<Vec<SessionListing>> {
309 let mut listings = list_recent_sessions(limit.saturating_mul(4).max(limit)).await?;
310 if let SessionQueryScope::CurrentWorkspace(workspace) = scope {
311 listings.retain(|listing| session_listing_matches_workspace(listing, workspace));
312 }
313 let current_id = runtime_archive_session_id();
314 listings.retain(|listing| {
315 if listing.snapshot.total_messages == 0 {
316 return false;
317 }
318 if let Some(ref current) = current_id
319 && listing.identifier() == *current
320 {
321 return false;
322 }
323 true
324 });
325 listings.truncate(limit);
326 Ok(listings)
327}
328
329pub async fn prepare_archived_session(
330 source: SessionListing,
331 workspace: PathBuf,
332 metadata: SessionArchiveMetadata,
333 intent: ArchivedSessionIntent,
334 reserved_identifier: Option<String>,
335) -> Result<PreparedArchivedSession> {
336 let mut metadata = preserve_prompt_cache_lineage_if_compatible(metadata, &source.snapshot.metadata);
337 metadata.continuation_metadata = source.snapshot.metadata.continuation_metadata.clone();
338 if metadata.primary_agent.is_none() {
341 metadata.primary_agent = source.snapshot.metadata.primary_agent.clone();
342 }
343 let mut bootstrap = ThreadBootstrap::from_listing(source.clone());
344 bootstrap.metadata = Some(metadata.clone());
345
346 let thread_id = match &intent {
347 ArchivedSessionIntent::ResumeInPlace => source.identifier(),
348 ArchivedSessionIntent::ForkNewArchive { custom_suffix, .. } => {
349 if let Some(identifier) = reserved_identifier {
350 identifier
351 } else {
352 reserve_session_archive_identifier(&metadata.workspace_label, custom_suffix.clone()).await?
353 }
354 }
355 };
356
357 if let ArchivedSessionIntent::ForkNewArchive { summarize, .. } = &intent {
358 metadata.parent_session_id = Some(source.identifier());
359 metadata.fork_mode = Some(if *summarize {
360 SessionForkMode::Summarized
361 } else {
362 SessionForkMode::FullCopy
363 });
364 bootstrap.metadata = Some(metadata.clone());
365 }
366
367 let archive = match intent {
368 ArchivedSessionIntent::ResumeInPlace => SessionArchive::resume_from_listing(&source, metadata),
369 ArchivedSessionIntent::ForkNewArchive { .. } => {
370 SessionArchive::new_with_identifier(metadata, thread_id.clone()).await?
371 }
372 };
373
374 Ok(PreparedArchivedSession { source, workspace, bootstrap, thread_id, archive })
375}
376
377pub async fn fork_thread_for_handoff(
387 listing: &SessionListing,
388 workspace: PathBuf,
389 metadata: SessionArchiveMetadata,
390) -> Result<(String, SessionArchive)> {
391 let prepared = prepare_archived_session(
392 listing.clone(),
393 workspace,
394 metadata,
395 ArchivedSessionIntent::ForkNewArchive { custom_suffix: None, summarize: false },
396 None,
397 )
398 .await?;
399 let mut snapshot = listing.snapshot.clone();
407 snapshot.metadata = prepared.archive.metadata().clone();
408 prepared.archive.persist_snapshot(snapshot)?;
409 Ok((prepared.thread_id, prepared.archive))
410}
411
412fn preserve_prompt_cache_lineage_if_compatible(
413 mut metadata: SessionArchiveMetadata,
414 source: &SessionArchiveMetadata,
415) -> SessionArchiveMetadata {
416 let is_compatible = metadata.workspace_path == source.workspace_path
417 && metadata.provider == source.provider
418 && metadata.model == source.model;
419 if is_compatible && let Some(lineage_id) = source.prompt_cache_lineage_id.as_ref() {
420 metadata.prompt_cache_lineage_id = Some(lineage_id.clone());
421 }
422 metadata
423}
424
425pub fn messages_from_session_listing(listing: &SessionListing) -> Vec<Message> {
426 if !listing.snapshot.messages.is_empty() {
427 listing.snapshot.messages.iter().map(Message::from).collect()
428 } else if let Some(progress) = &listing.snapshot.progress
429 && !progress.recent_messages.is_empty()
430 {
431 progress.recent_messages.iter().map(Message::from).collect()
432 } else {
433 Vec::new()
434 }
435}
436
437pub fn loaded_skills_from_session_listing(listing: &SessionListing) -> Vec<String> {
438 listing
439 .snapshot
440 .progress
441 .as_ref()
442 .map(|progress| progress.loaded_skills.clone())
443 .filter(|skills| !skills.is_empty())
444 .unwrap_or_else(|| listing.snapshot.metadata.loaded_skills.clone())
445}
446
447pub fn build_thread_archive_metadata(
448 workspace: &Path,
449 model: &str,
450 provider: &str,
451 theme: &str,
452 reasoning_effort: &str,
453) -> SessionArchiveMetadata {
454 let workspace_label = workspace.file_name().and_then(|value| value.to_str()).unwrap_or("workspace");
455
456 SessionArchiveMetadata::new(
457 workspace_label,
458 workspace.to_string_lossy().to_string(),
459 model,
460 provider,
461 theme,
462 reasoning_effort,
463 )
464 .ensure_prompt_cache_lineage_id()
465}
466
467#[cfg(test)]
468mod tests;