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
377/// Fork a live thread into a standalone archive another process can own.
378///
379/// The canonical event log is single-writer: the CLI holds an exclusive
380/// `flock` on `session.lock` for the whole session, so a second process
381/// cannot resume the same thread id. Forking sidesteps that by giving the
382/// receiver its own archive and its own (new) canonical log, so both sides
383/// keep working independently.
384///
385/// Returns the fork's session id and the archive it was written to.
386pub 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    // The fork archive must exist on disk before the receiver looks it up:
400    // `find_session_by_identifier` reads the persisted snapshot, so a fork
401    // that was only prepared in memory would not be discoverable.
402    //
403    // The source snapshot is copied whole rather than rebuilt: `progress`
404    // carries the loaded skills and turn number the receiver restores, and
405    // `finalize` would drop that block in favor of the metadata fallback.
406    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 {
469    use super::*;
470    use crate::exec::events::{ThreadEvent, ThreadStartedEvent};
471    use crate::llm::provider::MessageRole;
472    use crate::utils::session_archive::{
473        SessionArchiveMetadata, SessionMessage, SessionProgress, SessionSnapshot,
474        clear_sessions_dir_override_for_tests, override_sessions_dir_for_tests,
475    };
476    use chrono::Utc;
477    use std::sync::{LazyLock, Mutex};
478    use tempfile::TempDir;
479
480    static SESSION_DIR_TEST_GUARD: LazyLock<Mutex<()>> = LazyLock::new(|| Mutex::new(()));
481
482    /// Seed a source archive so the fork has a real listing to copy.
483    async fn seed_source_listing(sessions_dir: &Path, workspace: &Path) -> SessionListing {
484        let metadata = SessionArchiveMetadata::new(
485            "workspace",
486            workspace.display().to_string(),
487            "model",
488            "provider",
489            "theme",
490            "medium",
491        );
492        let messages = vec![SessionMessage::new(MessageRole::User, "hello")];
493        let snapshot = SessionSnapshot {
494            metadata,
495            started_at: Utc::now(),
496            ended_at: Utc::now(),
497            total_messages: messages.len(),
498            distinct_tools: Vec::new(),
499            transcript: Vec::new(),
500            messages: messages.clone(),
501            progress: Some(Box::new(SessionProgress {
502                recent_messages: messages,
503                loaded_skills: vec!["repo-skill".to_string()],
504                turn_number: 3,
505                ..Default::default()
506            })),
507            error_logs: Vec::new(),
508        };
509        let path = sessions_dir.join("session-source.json");
510        std::fs::write(&path, serde_json::to_vec(&snapshot).expect("serialize snapshot"))
511            .expect("write source archive");
512        SessionListing { path, snapshot }
513    }
514
515    #[tokio::test]
516    #[serial_test::serial(session_dir_override)]
517    async fn fork_thread_for_handoff_writes_a_discoverable_copy_with_its_own_id() {
518        let sessions_dir = TempDir::new().expect("sessions directory");
519        override_sessions_dir_for_tests(sessions_dir.path());
520        let workspace = sessions_dir.path().join("workspace");
521        let listing = seed_source_listing(sessions_dir.path(), &workspace).await;
522
523        let (fork_id, _archive) =
524            fork_thread_for_handoff(&listing, workspace.clone(), listing.snapshot.metadata.clone())
525                .await
526                .expect("fork thread");
527
528        // The fork must be discoverable by id: the receiver resolves the
529        // handoff through `find_session_by_identifier`, not through the
530        // in-memory archive handle.
531        let found = find_session_by_identifier(&fork_id)
532            .await
533            .expect("find fork")
534            .expect("fork exists");
535        assert_eq!(found.identifier(), fork_id);
536        assert_ne!(fork_id, listing.identifier(), "the fork owns a new id");
537        assert_eq!(found.snapshot.metadata.parent_session_id.as_deref(), Some("session-source"));
538        assert_eq!(found.snapshot.metadata.fork_mode, Some(SessionForkMode::FullCopy));
539        assert_eq!(found.snapshot.messages.len(), 1, "the fork carries the source transcript");
540        // The progress block carries the loaded skills and turn number the
541        // receiver restores; the fork must keep it, not just the metadata
542        // fallback.
543        let progress = found.snapshot.progress.as_ref().expect("the fork keeps the source progress");
544        assert_eq!(progress.loaded_skills, vec!["repo-skill".to_string()]);
545        assert_eq!(progress.turn_number, 3);
546
547        clear_sessions_dir_override_for_tests();
548    }
549
550    #[tokio::test]
551    #[serial_test::serial(session_dir_override)]
552    async fn fork_thread_for_handoff_copies_the_source_transcript() {
553        let sessions_dir = TempDir::new().expect("sessions directory");
554        override_sessions_dir_for_tests(sessions_dir.path());
555        let workspace = sessions_dir.path().join("workspace");
556        let listing = seed_source_listing(sessions_dir.path(), &workspace).await;
557
558        let (fork_id, _archive) =
559            fork_thread_for_handoff(&listing, workspace.clone(), listing.snapshot.metadata.clone())
560                .await
561                .expect("fork thread");
562
563        let found = find_session_by_identifier(&fork_id)
564            .await
565            .expect("find fork")
566            .expect("fork exists");
567        let messages = messages_from_session_listing(&found);
568        assert_eq!(messages.len(), 1);
569        assert_eq!(messages[0].content.as_text(), "hello");
570
571        clear_sessions_dir_override_for_tests();
572    }
573
574    #[test]
575    fn event_store_evicts_old_records() {
576        let manager = ThreadManager::with_event_buffer_capacity(2);
577        let handle = manager.start_thread_with_identifier("thread-1", ThreadBootstrap::new(None));
578
579        handle.record_event(
580            None,
581            None,
582            ThreadEvent::ThreadStarted(ThreadStartedEvent { thread_id: "thread-1".to_string() }),
583        );
584        handle.record_event(
585            None,
586            Some("turn-1".to_string()),
587            ThreadEvent::ThreadStarted(ThreadStartedEvent { thread_id: "thread-1-turn-1".to_string() }),
588        );
589        handle.record_event(
590            None,
591            Some("turn-2".to_string()),
592            ThreadEvent::ThreadStarted(ThreadStartedEvent { thread_id: "thread-1-turn-2".to_string() }),
593        );
594
595        let records = handle.replay_recent();
596        assert_eq!(records.len(), 2);
597        assert_eq!(records[0].sequence, 1);
598        assert_eq!(records[1].sequence, 2);
599    }
600
601    #[test]
602    fn start_thread_with_identifier_preserves_message_history() {
603        let manager = ThreadManager::new();
604        let bootstrap = ThreadBootstrap::new(None)
605            .with_messages(vec![Message::user("hello".to_string())])
606            .with_loaded_skills(vec!["repo-skill".to_string()]);
607        let handle = manager.start_thread_with_identifier("thread-123", bootstrap);
608
609        assert_eq!(handle.thread_id().as_str(), "thread-123");
610        let snapshot = handle.snapshot();
611        assert_eq!(snapshot.messages.len(), 1);
612        assert_eq!(snapshot.loaded_skills, vec!["repo-skill".to_string()]);
613    }
614
615    #[test]
616    fn submit_enforces_single_in_flight_turn() {
617        let manager = ThreadManager::new();
618        let handle = manager.start_thread_with_identifier("thread-123", ThreadBootstrap::new(None));
619
620        let _first = handle.begin_turn().expect("first turn");
621        let err = handle.begin_turn().expect_err("second turn should fail");
622        assert!(err.to_string().contains("in-flight turn"));
623        handle.finish_turn();
624        handle.begin_turn().expect("turn after finish");
625    }
626
627    #[test]
628    #[serial_test::serial(session_dir_override)]
629    fn list_recent_sessions_in_scope_filters_by_workspace() {
630        let _guard = SESSION_DIR_TEST_GUARD.lock().expect("session dir test guard");
631
632        let tmp = TempDir::new().expect("temp dir");
633        override_sessions_dir_for_tests(tmp.path());
634
635        let listing = SessionListing {
636            path: tmp.path().join("session-alpha.json"),
637            snapshot: SessionSnapshot {
638                metadata: SessionArchiveMetadata::new(
639                    "ws",
640                    tmp.path().join("workspace").display().to_string(),
641                    "model",
642                    "provider",
643                    "theme",
644                    "medium",
645                ),
646                started_at: Utc::now(),
647                ended_at: Utc::now(),
648                total_messages: 1,
649                distinct_tools: Vec::new(),
650                transcript: Vec::new(),
651                messages: vec![SessionMessage::new(MessageRole::User, "hello")],
652                progress: None,
653                error_logs: Vec::new(),
654            },
655        };
656        std::fs::write(&listing.path, serde_json::to_string(&listing.snapshot).expect("serialize snapshot"))
657            .expect("write listing");
658
659        let runtime = tokio::runtime::Runtime::new().expect("runtime");
660        let filtered = runtime
661            .block_on(list_recent_sessions_in_scope(
662                5,
663                &SessionQueryScope::CurrentWorkspace(tmp.path().join("workspace")),
664            ))
665            .expect("filter by workspace");
666        let all = runtime
667            .block_on(list_recent_sessions_in_scope(5, &SessionQueryScope::All))
668            .expect("list all");
669
670        clear_sessions_dir_override_for_tests();
671
672        assert_eq!(filtered.len(), 1);
673        assert_eq!(all.len(), 1);
674    }
675
676    #[test]
677    #[serial_test::serial(session_dir_override)]
678    fn prepare_archived_session_resume_reuses_source_identifier_and_archive() {
679        let _guard = SESSION_DIR_TEST_GUARD.lock().expect("session dir test guard");
680
681        let tmp = TempDir::new().expect("temp dir");
682        override_sessions_dir_for_tests(tmp.path());
683
684        let listing = SessionListing {
685            path: tmp.path().join("session-source.json"),
686            snapshot: SessionSnapshot {
687                metadata: SessionArchiveMetadata::new(
688                    "ws",
689                    tmp.path().join("workspace").display().to_string(),
690                    "old-model",
691                    "old-provider",
692                    "old-theme",
693                    "medium",
694                )
695                .with_primary_agent("plan"),
696                started_at: Utc::now(),
697                ended_at: Utc::now(),
698                total_messages: 2,
699                distinct_tools: vec!["tool_a".to_string()],
700                transcript: Vec::new(),
701                messages: vec![SessionMessage::new(MessageRole::User, "hello")],
702                progress: Some(Box::new(SessionProgress {
703                    turn_number: 1,
704                    recent_messages: vec![SessionMessage::new(MessageRole::Assistant, "recent")],
705                    tool_summaries: Vec::new(),
706                    token_usage: None,
707                    max_context_tokens: None,
708                    loaded_skills: vec!["skill_a".to_string()],
709                    turn_diagnostics: None,
710                })),
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.clone(),
719                tmp.path().join("workspace"),
720                SessionArchiveMetadata::new(
721                    "ws",
722                    tmp.path().join("workspace").display().to_string(),
723                    "new-model",
724                    "new-provider",
725                    "new-theme",
726                    "high",
727                ),
728                ArchivedSessionIntent::ResumeInPlace,
729                Some("should-not-be-used".to_string()),
730            ))
731            .expect("prepare resume");
732
733        clear_sessions_dir_override_for_tests();
734
735        assert_eq!(prepared.thread_id, listing.identifier());
736        assert_eq!(prepared.archive.path(), listing.path.as_path());
737        assert_eq!(prepared.bootstrap.messages[0].content.as_text(), "hello");
738        assert_eq!(prepared.bootstrap.loaded_skills, vec!["skill_a".to_string()]);
739        assert_eq!(prepared.bootstrap.metadata.as_ref().expect("metadata").model, "new-model");
740        // Resume preserves the source session's primary agent ("mode").
741        assert_eq!(prepared.bootstrap.metadata.as_ref().expect("metadata").primary_agent.as_deref(), Some("plan"));
742    }
743
744    #[test]
745    #[serial_test::serial(session_dir_override)]
746    fn prepare_archived_session_fork_uses_new_identifier_and_preserves_history() {
747        let _guard = SESSION_DIR_TEST_GUARD.lock().expect("session dir test guard");
748
749        let tmp = TempDir::new().expect("temp dir");
750        override_sessions_dir_for_tests(tmp.path());
751
752        let listing = SessionListing {
753            path: tmp.path().join("session-source.json"),
754            snapshot: SessionSnapshot {
755                metadata: SessionArchiveMetadata::new(
756                    "ws",
757                    tmp.path().join("workspace").display().to_string(),
758                    "model",
759                    "provider",
760                    "theme",
761                    "medium",
762                ),
763                started_at: Utc::now(),
764                ended_at: Utc::now(),
765                total_messages: 1,
766                distinct_tools: Vec::new(),
767                transcript: Vec::new(),
768                messages: vec![SessionMessage::new(MessageRole::User, "hello")],
769                progress: None,
770                error_logs: Vec::new(),
771            },
772        };
773
774        let runtime = tokio::runtime::Runtime::new().expect("runtime");
775        let prepared = runtime
776            .block_on(prepare_archived_session(
777                listing.clone(),
778                tmp.path().join("workspace"),
779                SessionArchiveMetadata::new(
780                    "ws",
781                    tmp.path().join("workspace").display().to_string(),
782                    "model",
783                    "provider",
784                    "theme",
785                    "medium",
786                ),
787                ArchivedSessionIntent::ForkNewArchive {
788                    custom_suffix: Some("branch".to_string()),
789                    summarize: false,
790                },
791                Some("session-forked".to_string()),
792            ))
793            .expect("prepare fork");
794
795        clear_sessions_dir_override_for_tests();
796
797        assert_eq!(prepared.thread_id, "session-forked");
798        assert_ne!(prepared.archive.path(), listing.path.as_path());
799        assert!(prepared.archive.path().ends_with(Path::new("session-forked.json")));
800        assert_eq!(prepared.bootstrap.messages[0].content.as_text(), "hello");
801        assert_eq!(
802            prepared
803                .bootstrap
804                .metadata
805                .as_ref()
806                .and_then(|metadata| metadata.parent_session_id.as_deref()),
807            Some("session-source")
808        );
809        assert_eq!(
810            prepared.bootstrap.metadata.as_ref().and_then(|metadata| metadata.fork_mode),
811            Some(SessionForkMode::FullCopy)
812        );
813    }
814
815    #[test]
816    #[serial_test::serial(session_dir_override)]
817    fn prepare_archived_session_preserves_prompt_cache_lineage_when_compatible() {
818        let _guard = SESSION_DIR_TEST_GUARD.lock().expect("session dir test guard");
819
820        let tmp = TempDir::new().expect("temp dir");
821        override_sessions_dir_for_tests(tmp.path());
822
823        let listing = SessionListing {
824            path: tmp.path().join("session-source.json"),
825            snapshot: SessionSnapshot {
826                metadata: SessionArchiveMetadata::new(
827                    "ws",
828                    tmp.path().join("workspace").display().to_string(),
829                    "model",
830                    "provider",
831                    "theme",
832                    "medium",
833                )
834                .with_prompt_cache_lineage_id("lineage-source"),
835                started_at: Utc::now(),
836                ended_at: Utc::now(),
837                total_messages: 1,
838                distinct_tools: Vec::new(),
839                transcript: Vec::new(),
840                messages: vec![SessionMessage::new(MessageRole::User, "hello")],
841                progress: None,
842                error_logs: Vec::new(),
843            },
844        };
845
846        let runtime = tokio::runtime::Runtime::new().expect("runtime");
847        let prepared = runtime
848            .block_on(prepare_archived_session(
849                listing,
850                tmp.path().join("workspace"),
851                SessionArchiveMetadata::new(
852                    "ws",
853                    tmp.path().join("workspace").display().to_string(),
854                    "model",
855                    "provider",
856                    "theme",
857                    "medium",
858                )
859                .with_prompt_cache_lineage_id("lineage-new"),
860                ArchivedSessionIntent::ResumeInPlace,
861                None,
862            ))
863            .expect("prepare resume");
864
865        clear_sessions_dir_override_for_tests();
866
867        assert_eq!(
868            prepared
869                .bootstrap
870                .metadata
871                .as_ref()
872                .and_then(|metadata| metadata.prompt_cache_lineage_id.as_deref()),
873            Some("lineage-source")
874        );
875    }
876
877    #[test]
878    #[serial_test::serial(session_dir_override)]
879    fn prepare_archived_session_resets_prompt_cache_lineage_on_model_change() {
880        let _guard = SESSION_DIR_TEST_GUARD.lock().expect("session dir test guard");
881
882        let tmp = TempDir::new().expect("temp dir");
883        override_sessions_dir_for_tests(tmp.path());
884
885        let listing = SessionListing {
886            path: tmp.path().join("session-source.json"),
887            snapshot: SessionSnapshot {
888                metadata: SessionArchiveMetadata::new(
889                    "ws",
890                    tmp.path().join("workspace").display().to_string(),
891                    "model-a",
892                    "provider",
893                    "theme",
894                    "medium",
895                )
896                .with_prompt_cache_lineage_id("lineage-source"),
897                started_at: Utc::now(),
898                ended_at: Utc::now(),
899                total_messages: 1,
900                distinct_tools: Vec::new(),
901                transcript: Vec::new(),
902                messages: vec![SessionMessage::new(MessageRole::User, "hello")],
903                progress: None,
904                error_logs: Vec::new(),
905            },
906        };
907
908        let runtime = tokio::runtime::Runtime::new().expect("runtime");
909        let prepared = runtime
910            .block_on(prepare_archived_session(
911                listing,
912                tmp.path().join("workspace"),
913                SessionArchiveMetadata::new(
914                    "ws",
915                    tmp.path().join("workspace").display().to_string(),
916                    "model-b",
917                    "provider",
918                    "theme",
919                    "medium",
920                )
921                .with_prompt_cache_lineage_id("lineage-new"),
922                ArchivedSessionIntent::ResumeInPlace,
923                None,
924            ))
925            .expect("prepare resume");
926
927        clear_sessions_dir_override_for_tests();
928
929        assert_eq!(
930            prepared
931                .bootstrap
932                .metadata
933                .as_ref()
934                .and_then(|metadata| metadata.prompt_cache_lineage_id.as_deref()),
935            Some("lineage-new")
936        );
937    }
938
939    #[test]
940    fn messages_from_session_listing_preserves_assistant_phases_from_progress() {
941        let listing = SessionListing {
942            path: PathBuf::from("session.json"),
943            snapshot: SessionSnapshot {
944                metadata: SessionArchiveMetadata::new("ws", "/tmp/ws", "gpt-5.6-sol", "openai", "theme", "medium"),
945                started_at: Utc::now(),
946                ended_at: Utc::now(),
947                total_messages: 2,
948                distinct_tools: Vec::new(),
949                transcript: Vec::new(),
950                messages: Vec::new(),
951                progress: Some(Box::new(SessionProgress {
952                    turn_number: 2,
953                    recent_messages: vec![
954                        SessionMessage::from(
955                            &Message::assistant("Working".to_string())
956                                .with_phase(Some(crate::llm::provider::AssistantPhase::Commentary)),
957                        ),
958                        SessionMessage::from(
959                            &Message::assistant("Done".to_string())
960                                .with_phase(Some(crate::llm::provider::AssistantPhase::FinalAnswer)),
961                        ),
962                    ],
963                    tool_summaries: Vec::new(),
964                    token_usage: None,
965                    max_context_tokens: None,
966                    loaded_skills: Vec::new(),
967                    turn_diagnostics: None,
968                })),
969                error_logs: Vec::new(),
970            },
971        };
972
973        let messages = messages_from_session_listing(&listing);
974        assert_eq!(
975            messages.iter().map(|message| message.phase).collect::<Vec<_>>(),
976            vec![
977                Some(crate::llm::provider::AssistantPhase::Commentary),
978                Some(crate::llm::provider::AssistantPhase::FinalAnswer),
979            ]
980        );
981    }
982}