Skip to main content

vtcode_core/core/
threads.rs

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    // Preserve the source session's primary agent ("mode") so a resume/fork keeps
339    // running the same agent instead of falling back to the config default.
340    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
377fn preserve_prompt_cache_lineage_if_compatible(
378    mut metadata: SessionArchiveMetadata,
379    source: &SessionArchiveMetadata,
380) -> SessionArchiveMetadata {
381    let is_compatible = metadata.workspace_path == source.workspace_path
382        && metadata.provider == source.provider
383        && metadata.model == source.model;
384    if is_compatible && let Some(lineage_id) = source.prompt_cache_lineage_id.as_ref() {
385        metadata.prompt_cache_lineage_id = Some(lineage_id.clone());
386    }
387    metadata
388}
389
390pub fn messages_from_session_listing(listing: &SessionListing) -> Vec<Message> {
391    if !listing.snapshot.messages.is_empty() {
392        listing.snapshot.messages.iter().map(Message::from).collect()
393    } else if let Some(progress) = &listing.snapshot.progress
394        && !progress.recent_messages.is_empty()
395    {
396        progress.recent_messages.iter().map(Message::from).collect()
397    } else {
398        Vec::new()
399    }
400}
401
402pub fn loaded_skills_from_session_listing(listing: &SessionListing) -> Vec<String> {
403    listing
404        .snapshot
405        .progress
406        .as_ref()
407        .map(|progress| progress.loaded_skills.clone())
408        .filter(|skills| !skills.is_empty())
409        .unwrap_or_else(|| listing.snapshot.metadata.loaded_skills.clone())
410}
411
412pub fn build_thread_archive_metadata(
413    workspace: &Path,
414    model: &str,
415    provider: &str,
416    theme: &str,
417    reasoning_effort: &str,
418) -> SessionArchiveMetadata {
419    let workspace_label = workspace.file_name().and_then(|value| value.to_str()).unwrap_or("workspace");
420
421    SessionArchiveMetadata::new(
422        workspace_label,
423        workspace.to_string_lossy().to_string(),
424        model,
425        provider,
426        theme,
427        reasoning_effort,
428    )
429    .ensure_prompt_cache_lineage_id()
430}
431
432#[cfg(test)]
433mod tests {
434    use super::*;
435    use crate::exec::events::{ThreadEvent, ThreadStartedEvent};
436    use crate::llm::provider::MessageRole;
437    use crate::utils::session_archive::{
438        SessionArchiveMetadata, SessionMessage, SessionProgress, SessionSnapshot,
439        clear_sessions_dir_override_for_tests, override_sessions_dir_for_tests,
440    };
441    use chrono::Utc;
442    use std::sync::{LazyLock, Mutex};
443    use tempfile::TempDir;
444
445    static SESSION_DIR_TEST_GUARD: LazyLock<Mutex<()>> = LazyLock::new(|| Mutex::new(()));
446
447    #[test]
448    fn event_store_evicts_old_records() {
449        let manager = ThreadManager::with_event_buffer_capacity(2);
450        let handle = manager.start_thread_with_identifier("thread-1", ThreadBootstrap::new(None));
451
452        handle.record_event(
453            None,
454            None,
455            ThreadEvent::ThreadStarted(ThreadStartedEvent { thread_id: "thread-1".to_string() }),
456        );
457        handle.record_event(
458            None,
459            Some("turn-1".to_string()),
460            ThreadEvent::ThreadStarted(ThreadStartedEvent { thread_id: "thread-1-turn-1".to_string() }),
461        );
462        handle.record_event(
463            None,
464            Some("turn-2".to_string()),
465            ThreadEvent::ThreadStarted(ThreadStartedEvent { thread_id: "thread-1-turn-2".to_string() }),
466        );
467
468        let records = handle.replay_recent();
469        assert_eq!(records.len(), 2);
470        assert_eq!(records[0].sequence, 1);
471        assert_eq!(records[1].sequence, 2);
472    }
473
474    #[test]
475    fn start_thread_with_identifier_preserves_message_history() {
476        let manager = ThreadManager::new();
477        let bootstrap = ThreadBootstrap::new(None)
478            .with_messages(vec![Message::user("hello".to_string())])
479            .with_loaded_skills(vec!["repo-skill".to_string()]);
480        let handle = manager.start_thread_with_identifier("thread-123", bootstrap);
481
482        assert_eq!(handle.thread_id().as_str(), "thread-123");
483        let snapshot = handle.snapshot();
484        assert_eq!(snapshot.messages.len(), 1);
485        assert_eq!(snapshot.loaded_skills, vec!["repo-skill".to_string()]);
486    }
487
488    #[test]
489    fn submit_enforces_single_in_flight_turn() {
490        let manager = ThreadManager::new();
491        let handle = manager.start_thread_with_identifier("thread-123", ThreadBootstrap::new(None));
492
493        let _first = handle.begin_turn().expect("first turn");
494        let err = handle.begin_turn().expect_err("second turn should fail");
495        assert!(err.to_string().contains("in-flight turn"));
496        handle.finish_turn();
497        handle.begin_turn().expect("turn after finish");
498    }
499
500    #[test]
501    #[serial_test::serial(session_dir_override)]
502    fn list_recent_sessions_in_scope_filters_by_workspace() {
503        let _guard = SESSION_DIR_TEST_GUARD.lock().expect("session dir test guard");
504        let tmp = TempDir::new().expect("temp dir");
505        override_sessions_dir_for_tests(tmp.path());
506
507        let listing = SessionListing {
508            path: tmp.path().join("session-alpha.json"),
509            snapshot: SessionSnapshot {
510                metadata: SessionArchiveMetadata::new(
511                    "ws",
512                    tmp.path().join("workspace").display().to_string(),
513                    "model",
514                    "provider",
515                    "theme",
516                    "medium",
517                ),
518                started_at: Utc::now(),
519                ended_at: Utc::now(),
520                total_messages: 1,
521                distinct_tools: Vec::new(),
522                transcript: Vec::new(),
523                messages: vec![SessionMessage::new(MessageRole::User, "hello")],
524                progress: None,
525                error_logs: Vec::new(),
526            },
527        };
528        std::fs::write(&listing.path, serde_json::to_string(&listing.snapshot).expect("serialize snapshot"))
529            .expect("write listing");
530
531        let runtime = tokio::runtime::Runtime::new().expect("runtime");
532        let filtered = runtime
533            .block_on(list_recent_sessions_in_scope(
534                5,
535                &SessionQueryScope::CurrentWorkspace(tmp.path().join("workspace")),
536            ))
537            .expect("filter by workspace");
538        let all = runtime
539            .block_on(list_recent_sessions_in_scope(5, &SessionQueryScope::All))
540            .expect("list all");
541
542        clear_sessions_dir_override_for_tests();
543
544        assert_eq!(filtered.len(), 1);
545        assert_eq!(all.len(), 1);
546    }
547
548    #[test]
549    #[serial_test::serial(session_dir_override)]
550    fn prepare_archived_session_resume_reuses_source_identifier_and_archive() {
551        let _guard = SESSION_DIR_TEST_GUARD.lock().expect("session dir test guard");
552        let tmp = TempDir::new().expect("temp dir");
553        override_sessions_dir_for_tests(tmp.path());
554
555        let listing = SessionListing {
556            path: tmp.path().join("session-source.json"),
557            snapshot: SessionSnapshot {
558                metadata: SessionArchiveMetadata::new(
559                    "ws",
560                    tmp.path().join("workspace").display().to_string(),
561                    "old-model",
562                    "old-provider",
563                    "old-theme",
564                    "medium",
565                )
566                .with_primary_agent("plan"),
567                started_at: Utc::now(),
568                ended_at: Utc::now(),
569                total_messages: 2,
570                distinct_tools: vec!["tool_a".to_string()],
571                transcript: Vec::new(),
572                messages: vec![SessionMessage::new(MessageRole::User, "hello")],
573                progress: Some(Box::new(SessionProgress {
574                    turn_number: 1,
575                    recent_messages: vec![SessionMessage::new(MessageRole::Assistant, "recent")],
576                    tool_summaries: Vec::new(),
577                    token_usage: None,
578                    max_context_tokens: None,
579                    loaded_skills: vec!["skill_a".to_string()],
580                    turn_diagnostics: None,
581                })),
582                error_logs: Vec::new(),
583            },
584        };
585
586        let runtime = tokio::runtime::Runtime::new().expect("runtime");
587        let prepared = runtime
588            .block_on(prepare_archived_session(
589                listing.clone(),
590                tmp.path().join("workspace"),
591                SessionArchiveMetadata::new(
592                    "ws",
593                    tmp.path().join("workspace").display().to_string(),
594                    "new-model",
595                    "new-provider",
596                    "new-theme",
597                    "high",
598                ),
599                ArchivedSessionIntent::ResumeInPlace,
600                Some("should-not-be-used".to_string()),
601            ))
602            .expect("prepare resume");
603
604        clear_sessions_dir_override_for_tests();
605
606        assert_eq!(prepared.thread_id, listing.identifier());
607        assert_eq!(prepared.archive.path(), listing.path.as_path());
608        assert_eq!(prepared.bootstrap.messages[0].content.as_text(), "hello");
609        assert_eq!(prepared.bootstrap.loaded_skills, vec!["skill_a".to_string()]);
610        assert_eq!(prepared.bootstrap.metadata.as_ref().expect("metadata").model, "new-model");
611        // Resume preserves the source session's primary agent ("mode").
612        assert_eq!(prepared.bootstrap.metadata.as_ref().expect("metadata").primary_agent.as_deref(), Some("plan"));
613    }
614
615    #[test]
616    #[serial_test::serial(session_dir_override)]
617    fn prepare_archived_session_fork_uses_new_identifier_and_preserves_history() {
618        let _guard = SESSION_DIR_TEST_GUARD.lock().expect("session dir test guard");
619        let tmp = TempDir::new().expect("temp dir");
620        override_sessions_dir_for_tests(tmp.path());
621
622        let listing = SessionListing {
623            path: tmp.path().join("session-source.json"),
624            snapshot: SessionSnapshot {
625                metadata: SessionArchiveMetadata::new(
626                    "ws",
627                    tmp.path().join("workspace").display().to_string(),
628                    "model",
629                    "provider",
630                    "theme",
631                    "medium",
632                ),
633                started_at: Utc::now(),
634                ended_at: Utc::now(),
635                total_messages: 1,
636                distinct_tools: Vec::new(),
637                transcript: Vec::new(),
638                messages: vec![SessionMessage::new(MessageRole::User, "hello")],
639                progress: None,
640                error_logs: Vec::new(),
641            },
642        };
643
644        let runtime = tokio::runtime::Runtime::new().expect("runtime");
645        let prepared = runtime
646            .block_on(prepare_archived_session(
647                listing.clone(),
648                tmp.path().join("workspace"),
649                SessionArchiveMetadata::new(
650                    "ws",
651                    tmp.path().join("workspace").display().to_string(),
652                    "model",
653                    "provider",
654                    "theme",
655                    "medium",
656                ),
657                ArchivedSessionIntent::ForkNewArchive {
658                    custom_suffix: Some("branch".to_string()),
659                    summarize: false,
660                },
661                Some("session-forked".to_string()),
662            ))
663            .expect("prepare fork");
664
665        clear_sessions_dir_override_for_tests();
666
667        assert_eq!(prepared.thread_id, "session-forked");
668        assert_ne!(prepared.archive.path(), listing.path.as_path());
669        assert!(prepared.archive.path().ends_with(Path::new("session-forked.json")));
670        assert_eq!(prepared.bootstrap.messages[0].content.as_text(), "hello");
671        assert_eq!(
672            prepared
673                .bootstrap
674                .metadata
675                .as_ref()
676                .and_then(|metadata| metadata.parent_session_id.as_deref()),
677            Some("session-source")
678        );
679        assert_eq!(
680            prepared.bootstrap.metadata.as_ref().and_then(|metadata| metadata.fork_mode),
681            Some(SessionForkMode::FullCopy)
682        );
683    }
684
685    #[test]
686    #[serial_test::serial(session_dir_override)]
687    fn prepare_archived_session_preserves_prompt_cache_lineage_when_compatible() {
688        let _guard = SESSION_DIR_TEST_GUARD.lock().expect("session dir test guard");
689        let tmp = TempDir::new().expect("temp dir");
690        override_sessions_dir_for_tests(tmp.path());
691
692        let listing = SessionListing {
693            path: tmp.path().join("session-source.json"),
694            snapshot: SessionSnapshot {
695                metadata: SessionArchiveMetadata::new(
696                    "ws",
697                    tmp.path().join("workspace").display().to_string(),
698                    "model",
699                    "provider",
700                    "theme",
701                    "medium",
702                )
703                .with_prompt_cache_lineage_id("lineage-source"),
704                started_at: Utc::now(),
705                ended_at: Utc::now(),
706                total_messages: 1,
707                distinct_tools: Vec::new(),
708                transcript: Vec::new(),
709                messages: vec![SessionMessage::new(MessageRole::User, "hello")],
710                progress: None,
711                error_logs: Vec::new(),
712            },
713        };
714
715        let runtime = tokio::runtime::Runtime::new().expect("runtime");
716        let prepared = runtime
717            .block_on(prepare_archived_session(
718                listing,
719                tmp.path().join("workspace"),
720                SessionArchiveMetadata::new(
721                    "ws",
722                    tmp.path().join("workspace").display().to_string(),
723                    "model",
724                    "provider",
725                    "theme",
726                    "medium",
727                )
728                .with_prompt_cache_lineage_id("lineage-new"),
729                ArchivedSessionIntent::ResumeInPlace,
730                None,
731            ))
732            .expect("prepare resume");
733
734        clear_sessions_dir_override_for_tests();
735
736        assert_eq!(
737            prepared
738                .bootstrap
739                .metadata
740                .as_ref()
741                .and_then(|metadata| metadata.prompt_cache_lineage_id.as_deref()),
742            Some("lineage-source")
743        );
744    }
745
746    #[test]
747    #[serial_test::serial(session_dir_override)]
748    fn prepare_archived_session_resets_prompt_cache_lineage_on_model_change() {
749        let _guard = SESSION_DIR_TEST_GUARD.lock().expect("session dir test guard");
750        let tmp = TempDir::new().expect("temp dir");
751        override_sessions_dir_for_tests(tmp.path());
752
753        let listing = SessionListing {
754            path: tmp.path().join("session-source.json"),
755            snapshot: SessionSnapshot {
756                metadata: SessionArchiveMetadata::new(
757                    "ws",
758                    tmp.path().join("workspace").display().to_string(),
759                    "model-a",
760                    "provider",
761                    "theme",
762                    "medium",
763                )
764                .with_prompt_cache_lineage_id("lineage-source"),
765                started_at: Utc::now(),
766                ended_at: Utc::now(),
767                total_messages: 1,
768                distinct_tools: Vec::new(),
769                transcript: Vec::new(),
770                messages: vec![SessionMessage::new(MessageRole::User, "hello")],
771                progress: None,
772                error_logs: Vec::new(),
773            },
774        };
775
776        let runtime = tokio::runtime::Runtime::new().expect("runtime");
777        let prepared = runtime
778            .block_on(prepare_archived_session(
779                listing,
780                tmp.path().join("workspace"),
781                SessionArchiveMetadata::new(
782                    "ws",
783                    tmp.path().join("workspace").display().to_string(),
784                    "model-b",
785                    "provider",
786                    "theme",
787                    "medium",
788                )
789                .with_prompt_cache_lineage_id("lineage-new"),
790                ArchivedSessionIntent::ResumeInPlace,
791                None,
792            ))
793            .expect("prepare resume");
794
795        clear_sessions_dir_override_for_tests();
796
797        assert_eq!(
798            prepared
799                .bootstrap
800                .metadata
801                .as_ref()
802                .and_then(|metadata| metadata.prompt_cache_lineage_id.as_deref()),
803            Some("lineage-new")
804        );
805    }
806
807    #[test]
808    fn messages_from_session_listing_preserves_assistant_phases_from_progress() {
809        let listing = SessionListing {
810            path: PathBuf::from("session.json"),
811            snapshot: SessionSnapshot {
812                metadata: SessionArchiveMetadata::new("ws", "/tmp/ws", "gpt-5.6-sol", "openai", "theme", "medium"),
813                started_at: Utc::now(),
814                ended_at: Utc::now(),
815                total_messages: 2,
816                distinct_tools: Vec::new(),
817                transcript: Vec::new(),
818                messages: Vec::new(),
819                progress: Some(Box::new(SessionProgress {
820                    turn_number: 2,
821                    recent_messages: vec![
822                        SessionMessage::from(
823                            &Message::assistant("Working".to_string())
824                                .with_phase(Some(crate::llm::provider::AssistantPhase::Commentary)),
825                        ),
826                        SessionMessage::from(
827                            &Message::assistant("Done".to_string())
828                                .with_phase(Some(crate::llm::provider::AssistantPhase::FinalAnswer)),
829                        ),
830                    ],
831                    tool_summaries: Vec::new(),
832                    token_usage: None,
833                    max_context_tokens: None,
834                    loaded_skills: Vec::new(),
835                    turn_diagnostics: None,
836                })),
837                error_logs: Vec::new(),
838            },
839        };
840
841        let messages = messages_from_session_listing(&listing);
842        assert_eq!(
843            messages.iter().map(|message| message.phase).collect::<Vec<_>>(),
844            vec![
845                Some(crate::llm::provider::AssistantPhase::Commentary),
846                Some(crate::llm::provider::AssistantPhase::FinalAnswer),
847            ]
848        );
849    }
850}