Skip to main content

artifactize_core/
chat.rs

1//! Artifactize's worktree-bound coding conversation. Provider selection changes the model,
2//! never the tools or the workflow.
3mod details;
4#[cfg(test)]
5mod tests;
6pub(crate) mod tools;
7mod transcript;
8
9use std::{
10    collections::{BTreeMap, btree_map::Entry as Slot},
11    path::{Path, PathBuf},
12    sync::{Arc, Mutex},
13    time::Duration,
14};
15
16use serde::{Deserialize, Serialize};
17use tokio_util::sync::CancellationToken;
18
19use crate::{
20    agent::{
21        self,
22        session::{Answer, Conversation, Kind, Recorder, Send},
23    },
24    auth::providers,
25    config::{Backend, ModelId, Provider},
26    llm,
27    monitor::live::{self, Branch, Place},
28    repository, runs,
29    store::{self, Receipts},
30    types::{SessionId, Timestamp},
31};
32
33pub use details::ToolKind;
34pub(crate) fn recorded_outcome(state: &Path, id: &SessionId) -> Option<Outcome> {
35    Conversation::load(&path(state, id))
36        .ok()
37        .flatten()
38        .as_ref()
39        .and_then(transcript::last_outcome)
40}
41
42pub use transcript::{Block, RunCard, ToolResult, Turn, TurnState};
43
44/// The Chat branch choices and the sessions observed while discovering them.
45pub struct BranchListing {
46    pub branches: Vec<Branch>,
47    pub sessions: Vec<Session>,
48}
49
50/// A description comes from the first nonempty prompt line, not another provider call.
51const TITLE_CHARS: usize = 72;
52/// Limit one prompt so a caller cannot overwhelm the transcript and model request at once.
53const PROMPT_BYTES: usize = 256 * 1024;
54/// A turn checks for a durable stop from another app even when the provider sends no data.
55const STOP_CHECK: Duration = Duration::from_millis(250);
56
57#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
58#[serde(rename_all = "camelCase")]
59pub struct Model {
60    pub backend: Backend,
61    pub model: ModelId,
62    #[serde(default)]
63    pub effort: Option<String>,
64}
65
66#[derive(Debug, PartialEq, Eq, thiserror::Error)]
67pub enum SendError {
68    #[error("Choose a model before sending a Chat message.")]
69    NoModel,
70    #[error("{0}")]
71    Failed(String),
72}
73
74impl From<String> for SendError {
75    fn from(message: String) -> Self {
76        Self::Failed(message)
77    }
78}
79
80#[derive(Debug, PartialEq, Eq, thiserror::Error)]
81pub enum MoveError {
82    #[error("Not an available Chat worktree: {0}")]
83    Invalid(String),
84    #[error("Stop the running turn first")]
85    Busy,
86    #[error("{0}")]
87    Failed(String),
88}
89
90/// Whether an accepted quit could read active ownership and deliver Stop to those turns.
91#[derive(Debug)]
92pub enum StopRunningError {
93    Unreadable(String),
94    Turns(Vec<String>),
95}
96
97/// The state of the latest accepted turn.
98#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
99#[serde(rename_all = "camelCase")]
100pub enum Outcome {
101    Running,
102    Completed,
103    Failed,
104    Stopped,
105    Interrupted,
106}
107
108/// The workspace view last used in this session, independent of its turn activity.
109#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
110#[serde(rename_all = "camelCase")]
111pub enum SessionView {
112    #[default]
113    Conversation,
114    Graph,
115}
116
117#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
118struct Activity {
119    outcome: Outcome,
120    unseen: bool,
121}
122
123#[derive(Debug, Clone, Serialize, Deserialize)]
124#[serde(rename_all = "camelCase")]
125pub struct Session {
126    pub id: SessionId,
127    pub title: String,
128    #[serde(with = "crate::platform::path_serde")]
129    pub worktree: PathBuf,
130    #[serde(default)]
131    pub repository: Option<repository::Identity>,
132    #[serde(default, alias = "selection")]
133    pub model: Option<Model>,
134    #[serde(default)]
135    pub view: SessionView,
136    pub created_at: Timestamp,
137    pub updated_at: Timestamp,
138    #[serde(default)]
139    activity: Option<Activity>,
140    #[serde(
141        default,
142        skip_serializing_if = "Option::is_none",
143        with = "crate::platform::path_serde::option"
144    )]
145    pub(crate) moved_from: Option<PathBuf>,
146    /// Live ownership of a turn, read separately from the saved session.
147    #[serde(skip)]
148    pub running: bool,
149    #[serde(skip)]
150    pub unavailable: Option<String>,
151}
152
153impl Session {
154    /// Stable across branch switches or removal of the saved checkout.
155    pub fn branch(&self) -> Place {
156        Place::for_checkout(
157            &self.worktree,
158            self.repository
159                .as_ref()
160                .unwrap_or(&repository::Identity::default()),
161        )
162    }
163
164    pub fn label(&self) -> crate::monitor::live::Label {
165        crate::monitor::live::Label::for_identity(
166            &self.worktree,
167            &self.repository.clone().unwrap_or_default(),
168        )
169    }
170
171    pub fn outcome(&self) -> Option<Outcome> {
172        self.activity.map(|activity| activity.outcome)
173    }
174
175    pub fn unseen(&self) -> bool {
176        self.activity.is_some_and(|activity| activity.unseen)
177    }
178
179    pub(crate) fn needs_activity(&self) -> bool {
180        self.activity.is_none() || (self.outcome() == Some(Outcome::Running) && !self.running)
181    }
182
183    pub(crate) fn refresh_activity(&mut self, outcome: Option<Outcome>) {
184        let owner_gone = self.outcome() == Some(Outcome::Running) && !self.running;
185        if !self.needs_activity() {
186            return;
187        }
188        // Do not present legacy history as new. If an owner died after flushing its
189        // answer and before updating the catalog, prefer that answer over Interrupted.
190        self.activity = if owner_gone {
191            Some(Activity {
192                outcome: outcome.unwrap_or(Outcome::Interrupted),
193                unseen: true,
194            })
195        } else {
196            outcome.map(|outcome| Activity {
197                outcome: if self.running {
198                    Outcome::Running
199                } else {
200                    outcome
201                },
202                unseen: false,
203            })
204        };
205    }
206
207    pub(crate) fn settle_from(&mut self, turn: &Self) {
208        self.activity = turn.activity;
209        self.updated_at = self.updated_at.max(turn.updated_at);
210    }
211
212    pub(crate) fn mark_seen(&mut self) -> bool {
213        self.activity
214            .as_mut()
215            .is_some_and(|activity| std::mem::take(&mut activity.unseen))
216    }
217
218    fn matches(&self, words: &[String]) -> bool {
219        if words.is_empty() {
220            return true;
221        }
222        let label = self.label();
223        let fields = [
224            self.title.to_lowercase(),
225            label.project.to_lowercase(),
226            label.branch.to_lowercase(),
227        ];
228        words
229            .iter()
230            .all(|word| fields.iter().any(|field| field.contains(word)))
231    }
232
233    fn check_checkout(&self) -> Result<(), String> {
234        if !self.worktree.is_dir() {
235            return Err("This Chat's worktree no longer exists.".into());
236        }
237        verify_checkout(&self.worktree, self.repository.as_ref())
238    }
239
240    fn with_checkout(mut self) -> Self {
241        self.unavailable = self.check_checkout().err();
242        self
243    }
244}
245
246async fn checkout_for(
247    worktree: &Path,
248    expected: Option<&Place>,
249) -> Result<(PathBuf, repository::Identity), String> {
250    let worktree =
251        crate::workspace::canonical_target(worktree).map_err(|error| error.to_string())?;
252    let expected = expected.cloned();
253    crate::task::blocking(move || {
254        let identity = repository::identify(&worktree);
255        if expected.is_some_and(|expected| expected != Place::for_checkout(&worktree, &identity)) {
256            return Err("This branch is no longer checked out in the worktree.".into());
257        }
258        Ok((worktree, identity))
259    })
260    .await?
261}
262
263fn verify_checkout(worktree: &Path, saved: Option<&repository::Identity>) -> Result<(), String> {
264    checkout_refusal(saved, &repository::identify(worktree)).map_or(Ok(()), Err)
265}
266
267fn checkout_refusal(
268    saved: Option<&repository::Identity>,
269    current: &repository::Identity,
270) -> Option<String> {
271    match saved {
272        Some(saved) if saved == current => None,
273        Some(saved) => Some(match &saved.branch {
274            Some(branch) => format!("Check out {branch} in this worktree to continue this Chat."),
275            None => "Restore this Chat's original checkout to continue.".into(),
276        }),
277        None if *current == repository::Identity::default() => None,
278        None => {
279            Some("This Chat was saved without a branch. Start a new Chat for this checkout.".into())
280        }
281    }
282}
283
284#[derive(Debug, Clone)]
285pub struct View {
286    pub session: Session,
287    pub running: bool,
288    pub turns: Vec<Turn>,
289}
290
291#[derive(Clone)]
292pub struct Chat {
293    state: PathBuf,
294    executable: Option<PathBuf>,
295    active: Arc<ActiveTurns>,
296}
297
298#[derive(Default)]
299struct ActiveTurns {
300    state: Mutex<Turns>,
301    settled: tokio::sync::Notify,
302}
303
304#[derive(Default)]
305struct Turns {
306    closed: bool,
307    turns: BTreeMap<SessionId, CancellationToken>,
308}
309
310impl Chat {
311    pub fn new(state: PathBuf, executable: PathBuf) -> Self {
312        Self {
313            state,
314            executable: Some(executable),
315            active: Arc::default(),
316        }
317    }
318
319    /// Desktop discovers the packaged CLI when a session needs it, not at app startup.
320    pub fn discover(state: PathBuf) -> Self {
321        Self {
322            state,
323            executable: None,
324            active: Arc::default(),
325        }
326    }
327
328    fn context(&self, worktree: &Path) -> Result<runs::Context, String> {
329        match &self.executable {
330            Some(executable) => runs::Context::new(worktree, Some(&self.state), executable),
331            None => runs::Context::discover(worktree, Some(&self.state)),
332        }
333    }
334
335    /// Stop accepting work, cancel owned Chat turns and wait for their saved outcomes and
336    /// ownership release. Verify Runs already admitted remain independent of Chat.
337    pub fn close(&self) -> impl std::future::Future<Output = ()> + use<> {
338        {
339            let mut active = self.active.state.lock().expect("Chat active turns lock");
340            active.closed = true;
341            for cancel in active.turns.values() {
342                cancel.cancel();
343            }
344        }
345        let active = self.active.clone();
346        async move {
347            loop {
348                let settled = active.settled.notified();
349                tokio::pin!(settled);
350                settled.as_mut().enable();
351                if active
352                    .state
353                    .lock()
354                    .expect("Chat active turns lock")
355                    .turns
356                    .is_empty()
357                {
358                    return;
359                }
360                settled.await;
361            }
362        }
363    }
364
365    /// Reconcile exact turn ownership after a process dies without a final change hint.
366    /// Returns only sessions this observer actually reconciled.
367    pub async fn reconcile_interrupted(&self) -> Result<Vec<SessionId>, String> {
368        let mut changed = Vec::new();
369        for (session, owner) in store::chat::active_turns(&self.state, false).await? {
370            let receipts = Receipts::open(&self.state, &session.worktree).await?;
371            let settled = receipts
372                .finish_chat(&session.id, &owner, Some(&session))
373                .await;
374            let closed = receipts.close().await;
375            if settled.and_then(|settled| closed.map(|()| settled))? {
376                changed.push(session.id);
377            }
378        }
379        let publisher = crate::changes::Publisher::new(&self.state);
380        for session in &changed {
381            publisher.notify(crate::changes::Change::SessionInvalidated(session.clone()));
382        }
383        Ok(changed)
384    }
385
386    /// The starting model for a new session: the worktree's last available choice, or the first
387    /// listed model in Settings order after every provider has answered.
388    pub async fn default_model(&self, worktree: &Path) -> Result<Option<Model>, String> {
389        self.default_model_for(worktree, None).await
390    }
391
392    pub async fn default_model_for(
393        &self,
394        worktree: &Path,
395        branch: Option<&Place>,
396    ) -> Result<Option<Model>, String> {
397        let (worktree, identity) = checkout_for(worktree, branch).await?;
398        self.starting_model(&worktree, &identity).await
399    }
400
401    async fn starting_model(
402        &self,
403        worktree: &Path,
404        identity: &repository::Identity,
405    ) -> Result<Option<Model>, String> {
406        if let Some(model) = self.last_model(worktree, identity).await?
407            && let Ok(available) = self.resolve_model(worktree, model, None).await
408        {
409            return Ok(Some(available));
410        }
411        let providers = providers::list(Some(&self.state), Some(worktree))?;
412        let backends = Provider::ALL
413            .into_iter()
414            .map(Backend::from)
415            .chain(providers.custom.into_keys());
416        let listings = futures_util::future::join_all(
417            backends.map(|backend| llm::models::list(backend, Some(&self.state), Some(worktree))),
418        )
419        .await;
420        Ok(listings
421            .into_iter()
422            .filter_map(Result::ok)
423            .find_map(|listing| {
424                listing.models.into_iter().next().map(|model| Model {
425                    backend: listing.backend,
426                    model: model.slug,
427                    effort: model.default_effort,
428                })
429            }))
430    }
431
432    async fn last_model(
433        &self,
434        workspace: &Path,
435        checkout: &repository::Identity,
436    ) -> Result<Option<Model>, String> {
437        let branch = Place::for_checkout(workspace, checkout);
438        Ok(store::chat::for_branch(&self.state, &branch)
439            .await?
440            .into_iter()
441            .find_map(|session| session.model))
442    }
443
444    /// Persist an empty session, with no model unless one is explicitly selected.
445    pub async fn create(
446        &self,
447        worktree: &Path,
448        selection: Option<Model>,
449    ) -> Result<Session, String> {
450        self.create_for_branch(worktree, None, selection).await
451    }
452
453    /// Create only on the checkout the person selected, not a branch switched in meanwhile.
454    pub async fn create_for_branch(
455        &self,
456        workspace: &Path,
457        branch: Option<&Place>,
458        selection: Option<Model>,
459    ) -> Result<Session, String> {
460        let (workspace, repository) = checkout_for(workspace, branch).await?;
461        let worktree = workspace.as_path();
462        crate::config::read_workspace_config(worktree).map_err(|error| error.to_string())?;
463        let model = if let Some(selection) = selection {
464            let previous = if selection.effort.is_none() {
465                self.last_model(worktree, &repository).await?
466            } else {
467                None
468            };
469            Some(
470                self.resolve_model(worktree, selection, previous.as_ref())
471                    .await?,
472            )
473        } else {
474            None
475        };
476        let now = crate::broker::now();
477        let session = Session {
478            id: format!("chat-{}", agent::uuid()?).parse()?,
479            title: "New chat".into(),
480            worktree: worktree.into(),
481            repository: Some(repository),
482            model,
483            view: SessionView::default(),
484            created_at: now,
485            updated_at: now,
486            activity: None,
487            moved_from: None,
488            running: false,
489            unavailable: None,
490        };
491        let session = crate::task::blocking(move || session.with_checkout()).await?;
492        if let Some(reason) = &session.unavailable {
493            return Err(reason.clone());
494        }
495        let receipts = Receipts::open(&self.state, worktree).await?;
496        let result = receipts.create_chat(&session).await;
497        let closed = receipts.close().await;
498        result.and(closed)?;
499        Ok(session)
500    }
501
502    /// Discover the live choices used by the Chat branch picker, independently of Verify search.
503    pub async fn branches(&self, launch: Option<&Path>) -> Result<BranchListing, String> {
504        let runs = store::read_catalog(&self.state).await?;
505        let sessions = self.list(None, None).await?;
506        let launch = launch.map(Path::to_owned);
507        crate::task::blocking(move || {
508            let mut branches =
509                live::branches(&runs, launch.as_deref(), &mut live::Discovery::default()).branches;
510            for session in sessions
511                .iter()
512                .filter(|session| session.unavailable.is_none())
513            {
514                let place = session.branch();
515                if !branches.iter().any(|branch| branch.place == place) {
516                    let label = session.label();
517                    branches.push(Branch {
518                        place,
519                        project: label.project,
520                        name: label.branch,
521                        workspace: session.worktree.clone(),
522                        runs: Vec::new(),
523                    });
524                }
525            }
526            BranchListing { branches, sessions }
527        })
528        .await
529    }
530
531    /// Rebind the saved conversation to a live choice, excluding active turns in any process.
532    pub async fn set_worktree(
533        &self,
534        id: &SessionId,
535        worktree: &Path,
536        launch: Option<&Path>,
537    ) -> Result<Session, MoveError> {
538        let path = crate::platform::path_text(worktree);
539        let invalid = || MoveError::Invalid(path.clone());
540        let branch = self
541            .branches(launch)
542            .await
543            .map_err(MoveError::Failed)?
544            .branches
545            .into_iter()
546            .find(|branch| crate::platform::path_text(&branch.workspace) == path)
547            .ok_or_else(invalid)?;
548        let (workspace, repository) = checkout_for(&branch.workspace, Some(&branch.place))
549            .await
550            .map_err(|_| invalid())?;
551        let receipts = Receipts::open(&self.state, &workspace)
552            .await
553            .map_err(MoveError::Failed)?;
554        let result = receipts
555            .set_chat_worktree(&self.state, id, workspace, repository)
556            .await;
557        let closed = receipts.close().await;
558        let (saved, changed) = result
559            .and_then(|saved| closed.map(|()| saved))
560            .map_err(MoveError::Failed)?
561            .ok_or(MoveError::Busy)?;
562        if changed {
563            crate::changes::Publisher::new(&self.state)
564                .notify(crate::changes::Change::SessionInvalidated(id.clone()));
565        }
566        crate::task::blocking(move || saved.with_checkout())
567            .await
568            .map_err(MoveError::Failed)
569    }
570
571    /// Keep the catalog's activity order while matching every word across its displayed labels.
572    pub async fn list(
573        &self,
574        worktree: Option<&Path>,
575        query: Option<&str>,
576    ) -> Result<Vec<Session>, String> {
577        let words = query
578            .unwrap_or_default()
579            .split_whitespace()
580            .map(str::to_lowercase)
581            .collect::<Vec<_>>();
582        let sessions = store::chat::list(&self.state, worktree).await?;
583        crate::task::blocking(move || {
584            let mut identities = BTreeMap::new();
585            sessions
586                .into_iter()
587                .filter(|session| session.matches(&words))
588                .map(|mut session| {
589                    let checkout =
590                        identities
591                            .entry(session.worktree.clone())
592                            .or_insert_with(|| {
593                                session
594                                    .worktree
595                                    .is_dir()
596                                    .then(|| repository::identify(&session.worktree))
597                            });
598                    session.unavailable = match checkout {
599                        Some(current) => checkout_refusal(session.repository.as_ref(), current),
600                        None => Some("This Chat's worktree no longer exists.".into()),
601                    };
602                    session
603                })
604                .collect()
605        })
606        .await
607    }
608
609    /// Find a conversation by its former checkout, including a workspace within the worktree.
610    pub async fn latest_for_unavailable_checkout(
611        &self,
612        workspace: &Path,
613    ) -> Result<Option<Session>, String> {
614        let workspace = workspace.to_path_buf();
615        let workspace = crate::task::blocking(move || {
616            let workspace = crate::workspace::canonical_target(&workspace)
617                .map_err(|error| error.to_string())?;
618            Ok::<_, String>(
619                crate::repository::identify(&workspace)
620                    .worktree_path
621                    .is_none()
622                    .then_some(workspace),
623            )
624        })
625        .await??;
626        let Some(workspace) = workspace else {
627            return Ok(None);
628        };
629        let sessions = store::chat::list(&self.state, None).await?;
630        crate::task::blocking(move || {
631            sessions
632                .into_iter()
633                .filter(|session| {
634                    let recorded = session
635                        .repository
636                        .as_ref()
637                        .and_then(|repo| repo.worktree_path.as_deref())
638                        .unwrap_or(&session.worktree);
639                    crate::platform::paths::relative_beneath(&workspace, recorded).is_some()
640                        || crate::platform::paths_equal(&workspace, recorded)
641                })
642                .map(Session::with_checkout)
643                .find(|session| session.unavailable.is_some())
644        })
645        .await
646    }
647
648    /// The most recently active saved session on this branch, even if its checkout is gone.
649    pub async fn latest_for_branch(&self, branch: &Place) -> Result<Option<Session>, String> {
650        let mut sessions = store::chat::for_branch(&self.state, branch)
651            .await?
652            .into_iter();
653        crate::task::blocking(move || sessions.next().map(Session::with_checkout)).await
654    }
655
656    /// Prefer the newest usable session for branch navigation. If the checkout moved and none
657    /// can work on it, keep the newest saved conversation reachable with its diagnostic.
658    pub async fn latest_for_navigation(&self, branch: &Place) -> Result<Option<Session>, String> {
659        let sessions = store::chat::for_branch(&self.state, branch).await?;
660        crate::task::blocking(move || {
661            let mut fallback = None;
662            for session in sessions {
663                let session = session.with_checkout();
664                if session.unavailable.is_none() {
665                    return Some(session);
666                }
667                if fallback.is_none() {
668                    fallback = Some(session);
669                }
670            }
671            fallback
672        })
673        .await
674    }
675
676    /// The latest session whose exact checkout can be worked on now.
677    pub async fn latest_available_for_branch(
678        &self,
679        branch: &Place,
680    ) -> Result<Option<Session>, String> {
681        let sessions = store::chat::for_branch(&self.state, branch).await?;
682        crate::task::blocking(move || {
683            sessions
684                .into_iter()
685                .find(|session| session.check_checkout().is_ok())
686        })
687        .await
688    }
689
690    /// The oldest usable checkout anchors Current when there is no Verify workspace.
691    /// Activity in a newer session must not redirect scans, edits or tools.
692    pub async fn current_worktree(&self, branch: &Place) -> Result<Option<PathBuf>, String> {
693        let sessions = store::chat::for_branch(&self.state, branch).await?;
694        crate::task::blocking(move || {
695            sessions
696                .into_iter()
697                .filter(|session| session.check_checkout().is_ok())
698                .min_by(|a, b| (a.created_at, &a.id).cmp(&(b.created_at, &b.id)))
699                .map(|session| session.worktree)
700        })
701        .await
702    }
703
704    /// Save a view without changing the session's activity order or requiring a live checkout.
705    pub async fn set_view(&self, id: &SessionId, view: SessionView) -> Result<Session, String> {
706        let session = store::chat::load(&self.state, id).await?;
707        let receipts = Receipts::open(&self.state, &session.worktree).await?;
708        let result = receipts.set_chat_view(&self.state, id, view).await;
709        let closed = receipts.close().await;
710        let (saved, changed) = result.and_then(|saved| closed.map(|()| saved))?;
711        if changed {
712            crate::changes::Publisher::new(&self.state)
713                .notify(crate::changes::Change::SessionInvalidated(id.clone()));
714        }
715        crate::task::blocking(move || saved.with_checkout()).await
716    }
717
718    /// Acknowledge the latest settled outcome without changing the session's activity order.
719    /// A turn still running will become unseen when it settles, even if this is called now.
720    pub async fn mark_seen(&self, id: &SessionId) -> Result<(), String> {
721        let session = store::chat::load(&self.state, id).await?;
722        if !session.unseen() {
723            return Ok(());
724        }
725        let receipts = Receipts::open(&self.state, &session.worktree).await?;
726        let result = receipts.mark_chat_seen(&self.state, id).await;
727        let closed = receipts.close().await;
728        let changed = result.and_then(|changed| closed.map(|()| changed))?;
729        if changed {
730            crate::changes::Publisher::new(&self.state)
731                .notify(crate::changes::Change::SessionInvalidated(id.clone()));
732        }
733        Ok(())
734    }
735
736    /// Chat records are append-only. Readers can detect a missed hint without parsing a
737    /// transcript, with `None` covering a session that has not yet accepted a turn.
738    pub fn transcript_size(&self, id: &SessionId) -> Option<u64> {
739        crate::platform::open_regular(&path(&self.state, id))
740            .and_then(|file| file.metadata())
741            .ok()
742            .map(|file| file.len())
743    }
744
745    /// The model's streamed text, tools, and current state of each referenced Run.
746    pub async fn open(&self, id: &SessionId) -> Result<View, String> {
747        let session = store::chat::load(&self.state, id).await?;
748        let session = crate::task::blocking(move || session.with_checkout()).await?;
749        let running = session.running;
750        let conversation = Conversation::load(&path(&self.state, id))?;
751        let mut turns = transcript::turns(conversation.as_ref(), running);
752        transcript::update_runs(&self.state, id, &mut turns).await;
753        Ok(View {
754            session,
755            running,
756            turns,
757        })
758    }
759
760    /// Save a selection for the next turn without adding a message. An accepted turn keeps
761    /// the selection it started with, even if the user changes the model while it streams.
762    pub async fn set_model(&self, id: &SessionId, selection: Model) -> Result<Session, String> {
763        let session = self.available(id).await?;
764        let selection = self
765            .resolve_model(&session.worktree, selection, session.model.as_ref())
766            .await?;
767        let receipts = Receipts::open(&self.state, &session.worktree).await?;
768        let saved = receipts.set_chat_model(&self.state, id, selection).await;
769        let closed = receipts.close().await;
770        let saved = saved.and_then(|session| closed.map(|()| session))?;
771        crate::changes::Publisher::new(&self.state)
772            .notify(crate::changes::Change::SessionInvalidated(id.clone()));
773        Ok(saved)
774    }
775
776    async fn available(&self, id: &SessionId) -> Result<Session, String> {
777        let session = store::chat::load(&self.state, id).await?;
778        let mut session = crate::task::blocking(move || session.with_checkout()).await?;
779        match session.unavailable.take() {
780            Some(reason) => Err(reason),
781            None => Ok(session),
782        }
783    }
784
785    /// Start a durable turn and return as soon as it has an accepted user message. The recorder
786    /// notifies `SessionInvalidated(id)` as text, tool outcomes and Run references arrive.
787    pub async fn send(
788        &self,
789        id: &SessionId,
790        text: String,
791        selection: Option<Model>,
792    ) -> Result<(), SendError> {
793        if text.trim().is_empty() || text.len() > PROMPT_BYTES {
794            return Err(SendError::Failed(format!(
795                "Chat messages must have text and be at most {PROMPT_BYTES} bytes."
796            )));
797        }
798        let active = self.claim(id)?;
799        let chat = self.clone();
800        let id = id.clone();
801        let (accepted, acknowledgement) = tokio::sync::oneshot::channel();
802        // Once queued, the library owns preparation and cleanup independently of the IPC caller.
803        tokio::spawn(async move {
804            match chat.prepare(&id, &text, selection, &active.cancel).await {
805                Ok(prepared) => {
806                    let _ = accepted.send(Ok(()));
807                    chat.finish(prepared, text, active).await;
808                }
809                Err(error) => {
810                    drop(active);
811                    let _ = accepted.send(Err(error));
812                }
813            }
814        });
815        acknowledgement
816            .await
817            .map_err(|_| SendError::Failed("The queued Chat turn did not start.".into()))?
818    }
819
820    async fn prepare(
821        &self,
822        id: &SessionId,
823        text: &str,
824        selection: Option<Model>,
825        cancel: &CancellationToken,
826    ) -> Result<Prepared, SendError> {
827        let saved = store::chat::load(&self.state, id).await?;
828        let file = path(&self.state, id);
829        let owner = store::chat::Owner::current()?;
830        let receipts = Receipts::open(&self.state, &saved.worktree).await?;
831        let prepared = async {
832            // Claim and read the checkout in one transaction. If a move won the race, this
833            // turn starts on the newly saved workspace, never the stale path read above.
834            let session = receipts.claim_chat(&self.state, id, &owner).await?;
835            let prepared = async {
836                let mut session = crate::task::blocking(move || session.with_checkout()).await?;
837                if let Some(reason) = session.unavailable.take() {
838                    return Err(SendError::Failed(reason));
839                }
840                let current = session.model.as_ref().ok_or(SendError::NoModel)?;
841                let context = self.context(&session.worktree)?;
842                let selection = if let Some(selection) = selection {
843                    Some(tokio::select! {
844                        _ = cancel.cancelled() => return Err(SendError::Failed("Chat stopped before accepting the turn.".into())),
845                        resolved = self.resolve_model(context.repo(), selection, Some(current)) => resolved?,
846                    })
847                } else {
848                    None
849                };
850                let conversation = Conversation::load(&file)?;
851                let send = conversation.as_ref().map(Conversation::sends).unwrap_or(0) + 1;
852                let history = conversation
853                    .as_ref()
854                    .map(Conversation::history)
855                    .transpose()?
856                    .unwrap_or_default();
857                if send == 1 {
858                    session.title = text
859                        .lines()
860                        .find_map(|line| {
861                            let line = line.trim();
862                            (!line.is_empty()).then(|| line.chars().take(TITLE_CHARS).collect())
863                        })
864                        .expect("nonblank prompt contains a title");
865                }
866                let mut recorder = Recorder::chat(&self.state, &file, id, send)?;
867                recorder.event(Kind::Send(Send {
868                    text: Some(text.to_owned()),
869                    framing: None,
870                    files_changed: None,
871                    tools: None,
872                }));
873                let prompt = rig_core::message::Message::user(text.to_owned());
874                recorder.message(1, &prompt, false);
875                recorder.check_saved()?;
876                session.updated_at = crate::broker::now();
877                session.activity = Some(Activity {
878                    outcome: Outcome::Running,
879                    unseen: false,
880                });
881                let model = receipts.accept_chat(&session, selection).await?;
882                Ok::<_, SendError>((session, recorder, history, model, context))
883            }
884            .await;
885            if prepared.is_err() {
886                let _ = receipts.finish_chat(id, &owner, None).await;
887            }
888            prepared
889        }
890        .await;
891        let (session, recorder, history, model, context) = match prepared {
892            Ok(prepared) => prepared,
893            Err(error) => {
894                let _ = receipts.close().await;
895                return Err(error);
896            }
897        };
898        Ok(Prepared {
899            session,
900            model,
901            context,
902            receipts,
903            owner,
904            recorder,
905            history,
906        })
907    }
908
909    async fn finish(&self, prepared: Prepared, text: String, active: Active) {
910        let Prepared {
911            mut session,
912            model,
913            context,
914            receipts,
915            owner,
916            mut recorder,
917            history,
918        } = prepared;
919        let context = context.with_origin(runs::Origin::Chat {
920            session_id: session.id.clone(),
921            title: session.title.clone(),
922        });
923        let directory = self.state.join("chat-output");
924        let output = crate::workspace::prepare_directory(&directory, &session.worktree)
925            .map_err(|error| agent::error::Failure::from(error.to_string()))
926            .and_then(|directory| {
927                crate::platform::private_tempdir_in("turn-", &directory)
928                    .map_err(|error| agent::error::Failure::from(error.to_string()))
929            });
930        let result = match output {
931            Ok(output) => {
932                let tools = tools::Tools::new(&context, output.path())
933                    .guard_checkout(session.repository.as_ref());
934                let turn = agent::chat_turn(
935                    &model,
936                    &context,
937                    &tools,
938                    agent::ChatPrompt::new(
939                        history,
940                        text,
941                        session.moved_from.as_deref(),
942                        &session.worktree,
943                    ),
944                    &mut recorder,
945                    &active.cancel,
946                );
947                let requested = async {
948                    let mut check = tokio::time::interval(STOP_CHECK);
949                    check.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
950                    loop {
951                        check.tick().await;
952                        if receipts.chat_stop_requested(&session.id, &owner).await == Ok(true) {
953                            active.cancel.cancel();
954                            break;
955                        }
956                    }
957                };
958                tokio::pin!(turn);
959                tokio::select! {
960                    answer = &mut turn => answer,
961                    () = requested => turn.await,
962                }
963            }
964            Err(error) => Err(error),
965        };
966        let answer = match result {
967            Ok(text) => Answer::Completed(text),
968            Err(failure) => Answer::Failed {
969                code: Some(failure.code),
970                message: Some(failure.message),
971            },
972        };
973        session.activity = Some(Activity {
974            outcome: transcript::outcome(&answer),
975            unseen: true,
976        });
977        session.updated_at = crate::broker::now().max(session.updated_at);
978        recorder.event(Kind::Answer(answer));
979        // Publish the settled outcome and release ownership together.
980        let _ = receipts
981            .finish_chat(&session.id, &owner, Some(&session))
982            .await;
983        let _ = receipts.close().await;
984        drop(active);
985        recorder.notify();
986    }
987
988    /// Stop the active turn, even if another app owns it. Accepted Verify Runs are independent.
989    pub async fn stop(&self, id: &SessionId) -> Result<bool, String> {
990        let local = self
991            .active
992            .state
993            .lock()
994            .expect("Chat active turns lock")
995            .turns
996            .get(id)
997            .cloned();
998        if let Some(cancel) = local {
999            cancel.cancel();
1000            return Ok(true);
1001        }
1002        let Some(owner) = store::chat::turn_owner(&self.state, id).await? else {
1003            return Ok(false);
1004        };
1005        let session = store::chat::load(&self.state, id).await?;
1006        self.stop_exact(&session, owner).await
1007    }
1008
1009    /// The desktop's quit prompt names every running Chat. Deliver the same Stop to those
1010    /// turns even when another process owns them, before the desktop window closes.
1011    pub async fn stop_running(&self) -> Result<(), StopRunningError> {
1012        let local: std::collections::BTreeSet<_> = {
1013            let active = self.active.state.lock().expect("Chat active turns lock");
1014            active
1015                .turns
1016                .iter()
1017                .map(|(id, token)| {
1018                    token.cancel();
1019                    id.clone()
1020                })
1021                .collect()
1022        };
1023        let mut failed = Vec::new();
1024        let turns = store::chat::active_turns(&self.state, true)
1025            .await
1026            .map_err(StopRunningError::Unreadable)?;
1027        for (session, owner) in turns {
1028            if owner.in_current_process() && local.contains(&session.id) {
1029                continue;
1030            }
1031            if let Err(error) = self.stop_exact(&session, owner).await {
1032                failed.push(format!("{}: {error}", session.id));
1033            }
1034        }
1035        if failed.is_empty() {
1036            Ok(())
1037        } else {
1038            Err(StopRunningError::Turns(failed))
1039        }
1040    }
1041
1042    async fn stop_exact(
1043        &self,
1044        session: &Session,
1045        owner: store::chat::Owner,
1046    ) -> Result<bool, String> {
1047        let receipts = Receipts::open(&self.state, &session.worktree).await?;
1048        let stopped = receipts.stop_chat(&session.id, owner).await;
1049        let closed = receipts.close().await;
1050        stopped.and_then(|stopped| closed.map(|()| stopped))
1051    }
1052
1053    async fn resolve_model(
1054        &self,
1055        worktree: &Path,
1056        mut selection: Model,
1057        previous: Option<&Model>,
1058    ) -> Result<Model, String> {
1059        let listing =
1060            llm::models::list(selection.backend.clone(), Some(&self.state), Some(worktree)).await?;
1061        let model = listing
1062            .models
1063            .into_iter()
1064            .find(|model| model.slug == selection.model)
1065            .ok_or_else(|| {
1066                format!(
1067                    "{} does not list model {}.",
1068                    selection.backend, selection.model
1069                )
1070            })?;
1071        if let Some(effort) = &selection.effort {
1072            if !model.efforts.contains(effort) {
1073                let allowed = if model.efforts.is_empty() {
1074                    "none".to_owned()
1075                } else {
1076                    model.efforts.join(", ")
1077                };
1078                return Err(format!(
1079                    "{} model {} does not offer effort {effort:?}. Available efforts: {allowed}.",
1080                    selection.backend, selection.model
1081                ));
1082            }
1083        } else {
1084            selection.effort = previous
1085                .and_then(|previous| previous.effort.as_ref())
1086                .filter(|effort| model.efforts.contains(effort))
1087                .cloned()
1088                .or(model.default_effort);
1089        }
1090        Ok(selection)
1091    }
1092
1093    fn claim(&self, id: &SessionId) -> Result<Active, String> {
1094        let mut active = self.active.state.lock().expect("Chat active turns lock");
1095        if active.closed {
1096            return Err("Chat is closing.".into());
1097        }
1098        match active.turns.entry(id.clone()) {
1099            Slot::Occupied(_) => Err("This Chat session already has an active turn.".into()),
1100            Slot::Vacant(entry) => {
1101                let cancel = entry.insert(CancellationToken::new()).clone();
1102                Ok(Active {
1103                    chat: self.clone(),
1104                    id: id.clone(),
1105                    cancel,
1106                })
1107            }
1108        }
1109    }
1110}
1111
1112struct Prepared {
1113    session: Session,
1114    model: Model,
1115    context: runs::Context,
1116    receipts: Receipts,
1117    owner: store::chat::Owner,
1118    recorder: Recorder,
1119    history: Vec<rig_core::message::Message>,
1120}
1121
1122struct Active {
1123    chat: Chat,
1124    id: SessionId,
1125    cancel: CancellationToken,
1126}
1127impl Drop for Active {
1128    fn drop(&mut self) {
1129        self.chat
1130            .active
1131            .state
1132            .lock()
1133            .expect("Chat active turns lock")
1134            .turns
1135            .remove(&self.id);
1136        self.chat.active.settled.notify_waiters();
1137    }
1138}
1139
1140fn path(state: &Path, id: &SessionId) -> PathBuf {
1141    state.join("chat-sessions").join(format!("{id}.jsonl"))
1142}