Skip to main content

artifactize_core/
chat.rs

1//! Artifactize's worktree-bound coding conversation.
2//!
3//! Unifies agentic CLI backends on ACP (`ChatTarget::Acp`) alongside direct HTTP API providers
4//! (`ChatTarget::Direct`), while preserving read-only historical access for retired
5//! `LegacyClaudeAgent` sessions (`C-CHAT-ACP-UNIFIED`, `C-TRUST-BEFORE-WORKTREE`,
6//! `C-ONE-TURN-OWNERSHIP`, `C-ACP-EDGE-ISOLATION`).
7
8mod details;
9#[cfg(test)]
10mod tests;
11pub(crate) mod tools;
12mod transcript;
13
14use std::{
15    collections::{BTreeMap, btree_map::Entry as Slot},
16    path::{Path, PathBuf},
17    sync::{Arc, Mutex},
18    time::Duration,
19};
20
21use serde::{Deserialize, Serialize};
22use tokio::sync::Notify;
23use tokio_util::sync::CancellationToken;
24
25use crate::{
26    acp::{
27        self, AcpBinding, AgentId, ConfigCategory, ConfigOption, ConfigSelection,
28        VerifyBridgeState, WarmOwner,
29        catalog::{self, AgentAvailability},
30        engine::{AcpTurnInput, VerifiedAcpLaunch},
31        pool::{IDLE_TTL, Pool},
32        trust::{TrustRecord, TrustRequirement, TrustScope},
33    },
34    agent::{
35        self,
36        session::{Answer, Conversation, Kind, Recorder, Send},
37    },
38    auth::providers,
39    config::{CustomBackendName, DirectBackend, HttpProvider, ModelId, Provider},
40    llm,
41    monitor::live::{self, Branch, Place},
42    repository, runs,
43    store::{self, Receipts},
44    types::{SessionId, Timestamp},
45};
46
47pub use crate::store::chat::ChatWatermark;
48pub use details::ToolKind;
49pub use transcript::{Block, RunCard, ToolResult, Turn, TurnState};
50
51pub(crate) fn recorded_outcome(state: &Path, id: &SessionId) -> Option<Outcome> {
52    Conversation::load(&path(state, id))
53        .ok()
54        .flatten()
55        .as_ref()
56        .and_then(transcript::last_outcome)
57}
58
59/// The Chat branch choices and the sessions observed while discovering them.
60pub struct BranchListing {
61    pub branches: Vec<Branch>,
62    pub sessions: Vec<Session>,
63}
64
65/// A description comes from the first nonempty prompt line, not another provider call.
66const TITLE_CHARS: usize = 72;
67/// Limit one prompt so a caller cannot overwhelm the transcript and model request at once.
68const PROMPT_BYTES: usize = 256 * 1024;
69/// A turn checks for a durable stop from another app even when the provider sends no data.
70const STOP_CHECK: Duration = Duration::from_millis(250);
71/// Extra slack after `IDLE_TTL` before the background warm-pool timer reaps an idle child.
72const IDLE_REAP_MARGIN: Duration = Duration::from_secs(1);
73
74/// Direct HTTP provider selection used by `ChatTarget::Direct` and `agent::chat::turn`.
75#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
76#[serde(rename_all = "camelCase")]
77pub struct DirectSelection {
78    pub backend: DirectBackend,
79    pub model: ModelId,
80    #[serde(default)]
81    pub effort: Option<String>,
82}
83
84/// The execution target chosen for a Chat session (`T-ILLEGAL-STATES`).
85#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
86#[serde(tag = "engine", rename_all = "camelCase")]
87pub enum ChatTarget {
88    /// Direct HTTP API provider (Codex OAuth, OpenAI, Anthropic, Gemini, or custom HTTP).
89    Direct {
90        backend: DirectBackend,
91        model: ModelId,
92        #[serde(default)]
93        effort: Option<String>,
94    },
95    /// Unified ACP agentic CLI backend (built-in preset, Registry-installed, or custom).
96    Acp {
97        agent: AgentId,
98        #[serde(default)]
99        config: Vec<ConfigSelection>,
100    },
101    /// Retired `claude-agent` Chat target kept readable for historical sessions; cannot run new turns.
102    LegacyClaudeAgent {
103        model: ModelId,
104        #[serde(default)]
105        effort: Option<String>,
106    },
107}
108
109impl ChatTarget {
110    pub fn direct(selection: DirectSelection) -> Self {
111        Self::Direct {
112            backend: selection.backend,
113            model: selection.model,
114            effort: selection.effort,
115        }
116    }
117
118    pub fn acp(agent: AgentId, config: Vec<ConfigSelection>) -> Self {
119        Self::Acp { agent, config }
120    }
121
122    pub fn is_legacy_claude_agent(&self) -> bool {
123        matches!(self, Self::LegacyClaudeAgent { .. })
124    }
125
126    pub fn acp_agent(&self) -> Option<&AgentId> {
127        match self {
128            Self::Acp { agent, .. } => Some(agent),
129            _ => None,
130        }
131    }
132
133    pub fn engine_label(&self) -> String {
134        match self {
135            Self::Direct { backend, model, .. } => format!("Direct ({backend} / {model})"),
136            Self::Acp { agent, .. } => format!("ACP ({agent})"),
137            Self::LegacyClaudeAgent { model, .. } => format!("Legacy Claude Agent ({model})"),
138        }
139    }
140}
141
142#[derive(Debug, PartialEq, Eq, thiserror::Error)]
143pub enum SendError {
144    #[error("Choose a Chat agent or model before sending a Chat message.")]
145    NoModel,
146    #[error("Workspace trust is required before launching {}.", .0.agent_name)]
147    TrustRequired(Box<TrustRequirement>),
148    #[error("{0}")]
149    LegacyRetired(String),
150    #[error("{0}")]
151    Failed(String),
152}
153
154impl From<String> for SendError {
155    fn from(message: String) -> Self {
156        Self::Failed(message)
157    }
158}
159
160#[derive(Debug, PartialEq, Eq, thiserror::Error)]
161pub enum MoveError {
162    #[error("Not an available Chat worktree: {0}")]
163    Invalid(String),
164    #[error("Stop the running turn first")]
165    Busy,
166    #[error("{0}")]
167    Failed(String),
168}
169
170/// Whether an accepted quit could read active ownership and deliver Stop to those turns.
171#[derive(Debug)]
172pub enum StopRunningError {
173    Unreadable(String),
174    Turns(Vec<String>),
175}
176
177/// The state of the latest accepted turn.
178#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
179#[serde(rename_all = "camelCase")]
180pub enum Outcome {
181    Running,
182    Completed,
183    Failed,
184    Stopped,
185    Interrupted,
186}
187
188/// The workspace view last used in this session, independent of its turn activity.
189#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
190#[serde(rename_all = "camelCase")]
191pub enum SessionView {
192    #[default]
193    Conversation,
194    Graph,
195}
196
197#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
198struct Activity {
199    outcome: Outcome,
200    unseen: bool,
201}
202
203/// Edge deserialization wire representation for `Session` (`T-PARSE-AT-EDGE`).
204///
205/// Decodes legacy `model` / `selection` fields as raw strings bypassing `Backend::from_str`
206/// so historical sessions pointing at `"antigravity"` or `"claude-agent"` always open cleanly.
207#[derive(Debug, Clone, Serialize, Deserialize)]
208#[serde(rename_all = "camelCase")]
209struct SessionWire {
210    id: SessionId,
211    title: String,
212    #[serde(with = "crate::platform::path_serde")]
213    worktree: PathBuf,
214    #[serde(default)]
215    repository: Option<repository::Identity>,
216    #[serde(default, skip_serializing_if = "Option::is_none")]
217    target: Option<ChatTarget>,
218    #[serde(default, alias = "selection", skip_serializing)]
219    model: Option<LegacyModelWire>,
220    #[serde(default)]
221    view: SessionView,
222    created_at: Timestamp,
223    updated_at: Timestamp,
224    #[serde(default)]
225    activity: Option<Activity>,
226    #[serde(
227        default,
228        skip_serializing_if = "Option::is_none",
229        with = "crate::platform::path_serde::option"
230    )]
231    moved_from: Option<PathBuf>,
232    #[serde(default, skip_serializing_if = "Option::is_none")]
233    acp_binding: Option<AcpBinding>,
234}
235
236#[derive(Debug, Clone, Deserialize)]
237#[serde(rename_all = "camelCase")]
238struct LegacyModelWire {
239    backend: String,
240    model: String,
241    #[serde(default)]
242    effort: Option<String>,
243}
244
245impl LegacyModelWire {
246    fn migrate(self) -> Option<ChatTarget> {
247        let backend = self.backend.trim();
248        let effort = self
249            .effort
250            .map(|value| value.trim().to_owned())
251            .filter(|value| !value.is_empty());
252        if backend == "antigravity" {
253            let mut config = Vec::new();
254            let model = self.model.trim();
255            if !model.is_empty() {
256                config.push(ConfigSelection {
257                    id: "model".into(),
258                    value: model.to_owned(),
259                    category: Some(ConfigCategory::Model),
260                });
261            }
262            if let Some(level) = effort {
263                config.push(ConfigSelection {
264                    id: "thought_level".into(),
265                    value: level,
266                    category: Some(ConfigCategory::ThoughtLevel),
267                });
268            }
269            return Some(ChatTarget::Acp {
270                agent: "antigravity"
271                    .parse()
272                    .expect("antigravity is a valid AgentId"),
273                config,
274            });
275        }
276        if backend == "claude-agent" {
277            let model: ModelId = self.model.parse().ok()?;
278            return Some(ChatTarget::LegacyClaudeAgent { model, effort });
279        }
280        if let Some(provider) = HttpProvider::named(backend) {
281            let model: ModelId = self.model.parse().ok()?;
282            return Some(ChatTarget::Direct {
283                backend: DirectBackend::Builtin { provider },
284                model,
285                effort,
286            });
287        }
288        if let Ok(name) = backend.parse::<CustomBackendName>() {
289            let model: ModelId = self.model.parse().ok()?;
290            return Some(ChatTarget::Direct {
291                backend: DirectBackend::Custom { name },
292                model,
293                effort,
294            });
295        }
296        None
297    }
298}
299
300#[derive(Debug, Clone, Serialize, Deserialize)]
301#[serde(from = "SessionWire", into = "SessionWire")]
302pub struct Session {
303    pub id: SessionId,
304    pub title: String,
305    pub worktree: PathBuf,
306    pub repository: Option<repository::Identity>,
307    pub target: Option<ChatTarget>,
308    pub view: SessionView,
309    pub created_at: Timestamp,
310    pub updated_at: Timestamp,
311    activity: Option<Activity>,
312    pub(crate) moved_from: Option<PathBuf>,
313    pub acp_binding: Option<AcpBinding>,
314    /// Live ownership of a turn, read separately from the saved session.
315    pub running: bool,
316    /// Derived live from `running && has_pending_permission`; never persisted in `Activity`.
317    pub waiting_permission: bool,
318    /// Live ACP `configOptions` snapshot while a turn is running.
319    pub live_config_options: Vec<ConfigOption>,
320    /// Live Verify MCP bridge state while an ACP turn is running.
321    pub verify_bridge_state: VerifyBridgeState,
322    /// True when this historical session was saved on a legacy engine (`claude-agent` or legacy
323    /// `antigravity`) so the UI and handoff surface the transition explicitly (`C-NO-SILENT-REGRESSION`).
324    pub legacy_migration_notice: bool,
325    pub unavailable: Option<String>,
326}
327
328impl From<SessionWire> for Session {
329    fn from(wire: SessionWire) -> Self {
330        let migrated_from_legacy_antigravity = wire.target.is_none()
331            && wire
332                .model
333                .as_ref()
334                .is_some_and(|legacy| legacy.backend.trim() == "antigravity");
335        let target = wire
336            .target
337            .or_else(|| wire.model.and_then(LegacyModelWire::migrate));
338        let legacy_migration_notice = target
339            .as_ref()
340            .is_some_and(ChatTarget::is_legacy_claude_agent)
341            || migrated_from_legacy_antigravity;
342        Self {
343            id: wire.id,
344            title: wire.title,
345            worktree: wire.worktree,
346            repository: wire.repository,
347            target,
348            view: wire.view,
349            created_at: wire.created_at,
350            updated_at: wire.updated_at,
351            activity: wire.activity,
352            moved_from: wire.moved_from,
353            acp_binding: wire.acp_binding,
354            running: false,
355            waiting_permission: false,
356            live_config_options: Vec::new(),
357            verify_bridge_state: VerifyBridgeState::NotConnected,
358            legacy_migration_notice,
359            unavailable: None,
360        }
361    }
362}
363
364impl From<Session> for SessionWire {
365    fn from(session: Session) -> Self {
366        Self {
367            id: session.id,
368            title: session.title,
369            worktree: session.worktree,
370            repository: session.repository,
371            target: session.target,
372            model: None,
373            view: session.view,
374            created_at: session.created_at,
375            updated_at: session.updated_at,
376            activity: session.activity,
377            moved_from: session.moved_from,
378            acp_binding: session.acp_binding,
379        }
380    }
381}
382
383impl Session {
384    /// Stable across branch switches or removal of the saved checkout.
385    pub fn branch(&self) -> Place {
386        Place::for_checkout(
387            &self.worktree,
388            self.repository
389                .as_ref()
390                .unwrap_or(&repository::Identity::default()),
391        )
392    }
393
394    pub fn label(&self) -> crate::monitor::live::Label {
395        crate::monitor::live::Label::for_identity(
396            &self.worktree,
397            &self.repository.clone().unwrap_or_default(),
398        )
399    }
400
401    pub fn outcome(&self) -> Option<Outcome> {
402        self.activity.map(|activity| activity.outcome)
403    }
404
405    pub fn unseen(&self) -> bool {
406        self.activity.is_some_and(|activity| activity.unseen)
407    }
408
409    pub(crate) fn needs_activity(&self) -> bool {
410        self.activity.is_none() || (self.outcome() == Some(Outcome::Running) && !self.running)
411    }
412
413    pub(crate) fn refresh_activity(&mut self, outcome: Option<Outcome>) {
414        let owner_gone = self.outcome() == Some(Outcome::Running) && !self.running;
415        if !self.needs_activity() {
416            return;
417        }
418        // Do not present legacy history as new. If an owner died after flushing its
419        // answer and before updating the catalog, prefer that answer over Interrupted.
420        self.activity = if owner_gone {
421            Some(Activity {
422                outcome: outcome.unwrap_or(Outcome::Interrupted),
423                unseen: true,
424            })
425        } else {
426            outcome.map(|outcome| Activity {
427                outcome: if self.running {
428                    Outcome::Running
429                } else {
430                    outcome
431                },
432                unseen: false,
433            })
434        };
435    }
436
437    pub(crate) fn settle_from(&mut self, turn: &Self) {
438        self.activity = turn.activity;
439        self.updated_at = self.updated_at.max(turn.updated_at);
440    }
441
442    pub(crate) fn mark_seen(&mut self) -> bool {
443        self.activity
444            .as_mut()
445            .is_some_and(|activity| std::mem::take(&mut activity.unseen))
446    }
447
448    fn matches(&self, words: &[String]) -> bool {
449        if words.is_empty() {
450            return true;
451        }
452        let label = self.label();
453        let fields = [
454            self.title.to_lowercase(),
455            label.project.to_lowercase(),
456            label.branch.to_lowercase(),
457        ];
458        words
459            .iter()
460            .all(|word| fields.iter().any(|field| field.contains(word)))
461    }
462
463    fn check_checkout(&self) -> Result<(), String> {
464        if !self.worktree.is_dir() {
465            return Err("This Chat's worktree no longer exists.".into());
466        }
467        verify_checkout(&self.worktree, self.repository.as_ref())
468    }
469
470    fn with_checkout(mut self) -> Self {
471        self.unavailable = self.check_checkout().err();
472        self.legacy_migration_notice = self.legacy_migration_notice
473            || self
474                .target
475                .as_ref()
476                .is_some_and(ChatTarget::is_legacy_claude_agent);
477        self
478    }
479}
480
481async fn checkout_for(
482    worktree: &Path,
483    expected: Option<&Place>,
484) -> Result<(PathBuf, repository::Identity), String> {
485    let worktree =
486        crate::workspace::canonical_target(worktree).map_err(|error| error.to_string())?;
487    let expected = expected.cloned();
488    crate::task::blocking(move || {
489        let identity = repository::identify(&worktree);
490        if expected.is_some_and(|expected| expected != Place::for_checkout(&worktree, &identity)) {
491            return Err("This branch is no longer checked out in the worktree.".into());
492        }
493        Ok((worktree, identity))
494    })
495    .await?
496}
497
498fn verify_checkout(worktree: &Path, saved: Option<&repository::Identity>) -> Result<(), String> {
499    checkout_refusal(saved, &repository::identify(worktree)).map_or(Ok(()), Err)
500}
501
502fn checkout_refusal(
503    saved: Option<&repository::Identity>,
504    current: &repository::Identity,
505) -> Option<String> {
506    match saved {
507        Some(saved) if saved == current => None,
508        Some(saved) => Some(match &saved.branch {
509            Some(branch) => format!("Check out {branch} in this worktree to continue this Chat."),
510            None => "Restore this Chat's original checkout to continue.".into(),
511        }),
512        None if *current == repository::Identity::default() => None,
513        None => {
514            Some("This Chat was saved without a branch. Start a new Chat for this checkout.".into())
515        }
516    }
517}
518
519#[derive(Debug, Clone)]
520pub struct View {
521    pub session: Session,
522    pub running: bool,
523    pub waiting_permission: bool,
524    pub turns: Vec<Turn>,
525    pub live_config_options: Vec<ConfigOption>,
526    pub verify_bridge_state: VerifyBridgeState,
527}
528
529#[derive(Clone)]
530pub struct Chat {
531    state: PathBuf,
532    executable: Option<PathBuf>,
533    active: Arc<ActiveTurns>,
534    pool: Arc<Pool>,
535    permission_notify: Arc<Notify>,
536}
537
538#[derive(Default)]
539struct ActiveTurns {
540    state: Mutex<Turns>,
541    settled: Notify,
542}
543
544#[derive(Default)]
545struct Turns {
546    closed: bool,
547    turns: BTreeMap<SessionId, ActiveEntry>,
548}
549
550#[derive(Clone)]
551struct ActiveEntry {
552    cancel: CancellationToken,
553    owner_token: Option<String>,
554    worktree: Option<PathBuf>,
555}
556
557/// Resolved execution engine for a single accepted Chat turn (`T-ILLEGAL-STATES`).
558enum ChatEngine {
559    Direct {
560        selection: DirectSelection,
561        engine_label: String,
562        previous_engine_label: Option<String>,
563        prior_turns_count: usize,
564    },
565    Acp {
566        config: Vec<ConfigSelection>,
567        launch: Box<VerifiedAcpLaunch>,
568        previous_engine_label: Option<String>,
569        prior_turns: Vec<Turn>,
570        last_outcome: Option<Outcome>,
571    },
572}
573
574impl Chat {
575    pub fn new(state: PathBuf, executable: PathBuf) -> Self {
576        Self {
577            state,
578            executable: Some(executable),
579            active: Arc::default(),
580            pool: Arc::new(Pool::default()),
581            permission_notify: Arc::new(Notify::new()),
582        }
583    }
584
585    /// Desktop discovers the packaged CLI when a session needs it, not at app startup.
586    pub fn discover(state: PathBuf) -> Self {
587        Self {
588            state,
589            executable: None,
590            active: Arc::default(),
591            pool: Arc::new(Pool::default()),
592            permission_notify: Arc::new(Notify::new()),
593        }
594    }
595
596    fn context(&self, worktree: &Path) -> Result<runs::Context, String> {
597        match &self.executable {
598            Some(executable) => runs::Context::new(worktree, Some(&self.state), executable),
599            None => runs::Context::discover(worktree, Some(&self.state)),
600        }
601    }
602
603    /// Stop accepting work, commit durable Stop in SQLite before cancelling owned turns, wait for
604    /// their saved outcomes and ownership release, and drain all warm ACP children.
605    /// Verify Runs already admitted remain independent of Chat.
606    pub fn close(&self) -> impl std::future::Future<Output = ()> + use<> {
607        let entries: Vec<(SessionId, ActiveEntry)> = {
608            let mut active = self.active.state.lock().expect("Chat active turns lock");
609            active.closed = true;
610            active
611                .turns
612                .iter()
613                .map(|(id, entry)| (id.clone(), entry.clone()))
614                .collect()
615        };
616        let state = self.state.clone();
617        let active = self.active.clone();
618        let pool = self.pool.clone();
619        let permission_notify = self.permission_notify.clone();
620        async move {
621            // Uniform Stop path (`C-ONE-TURN-OWNERSHIP`): commit SQLite stop_requested +
622            // permission cancellation FIRST, and only fire the in-memory CancellationToken for
623            // turns whose Stop transaction succeeded (or that have no SQLite active turn yet).
624            let mut stopped_ids = std::collections::BTreeSet::new();
625            for (id, entry) in &entries {
626                if let (Some(token), Some(worktree)) = (&entry.owner_token, &entry.worktree) {
627                    let mut committed = false;
628                    for attempt in 0..5 {
629                        if let Ok(receipts) = Receipts::open(&state, worktree).await {
630                            let stopped = receipts.stop_chat_by_token(id, token).await;
631                            let closed = receipts.close().await;
632                            if stopped.and(closed).is_ok() {
633                                committed = true;
634                                break;
635                            }
636                        }
637                        if attempt < 4 {
638                            tokio::time::sleep(Duration::from_millis(20)).await;
639                        }
640                    }
641                    if committed {
642                        stopped_ids.insert(id.clone());
643                        entry.cancel.cancel();
644                    }
645                } else {
646                    stopped_ids.insert(id.clone());
647                    entry.cancel.cancel();
648                }
649            }
650            permission_notify.notify_waiters();
651            loop {
652                let settled = active.settled.notified();
653                tokio::pin!(settled);
654                settled.as_mut().enable();
655                if active
656                    .state
657                    .lock()
658                    .expect("Chat active turns lock")
659                    .turns
660                    .keys()
661                    .all(|id| !stopped_ids.contains(id))
662                {
663                    break;
664                }
665                settled.await;
666            }
667            // Terminate all warm ACP children and clear their warm_owner references.
668            let drained = pool.drain_all();
669            let current_owner = WarmOwner::current().ok();
670            for child in drained {
671                let session_id = child.session_id.clone();
672                let generation = child.generation;
673                let _ = child.terminate().await;
674                if let Some(warm_owner) = current_owner
675                    && let Ok(session) = store::chat::load(&state, &session_id).await
676                    && let Ok(receipts) = Receipts::open(&state, &session.worktree).await
677                {
678                    let _ = receipts
679                        .clear_acp_warm_owner(&session_id, generation, warm_owner)
680                        .await;
681                    let _ = receipts.close().await;
682                }
683            }
684        }
685    }
686
687    /// Reconcile exact turn ownership after a process dies without a final change hint.
688    /// Returns only sessions this observer actually reconciled.
689    pub async fn reconcile_interrupted(&self) -> Result<Vec<SessionId>, String> {
690        let mut changed = Vec::new();
691        for (session, owner) in store::chat::active_turns(&self.state, false).await? {
692            let receipts = Receipts::open(&self.state, &session.worktree).await?;
693            let settled = receipts
694                .finish_chat(&session.id, &owner, Some(&session), None)
695                .await;
696            let closed = receipts.close().await;
697            if settled.and_then(|settled| closed.map(|()| settled))? {
698                changed.push(session.id);
699            }
700        }
701        let publisher = crate::changes::Publisher::new(&self.state);
702        for session in &changed {
703            publisher.notify(crate::changes::Change::SessionInvalidated(session.clone()));
704        }
705        Ok(changed)
706    }
707
708    /// The starting target for a new session: the worktree's last available choice, or the first
709    /// ready ACP Chat agent, or the first available direct HTTP provider model.
710    pub async fn default_target(&self, worktree: &Path) -> Result<Option<ChatTarget>, String> {
711        self.default_target_for(worktree, None).await
712    }
713
714    pub async fn default_target_for(
715        &self,
716        worktree: &Path,
717        branch: Option<&Place>,
718    ) -> Result<Option<ChatTarget>, String> {
719        let (worktree, identity) = checkout_for(worktree, branch).await?;
720        self.starting_target(&worktree, &identity).await
721    }
722
723    async fn starting_target(
724        &self,
725        worktree: &Path,
726        identity: &repository::Identity,
727    ) -> Result<Option<ChatTarget>, String> {
728        if let Some(target) = self.last_target(worktree, identity).await?
729            && !target.is_legacy_claude_agent()
730            && let Ok(resolved) = self.resolve_target(worktree, target, None).await
731        {
732            return Ok(Some(resolved));
733        }
734
735        // Prefer ready ACP Chat agents in catalog order.
736        if let Ok(entries) = catalog::list_catalog(Some(&self.state), Some(worktree)) {
737            let probes = futures_util::future::join_all(entries.iter().map(|entry| {
738                catalog::probe_agent(&entry.id, Some(&self.state), Some(worktree), false)
739            }))
740            .await;
741            for (entry, availability) in entries.into_iter().zip(probes) {
742                if let AgentAvailability::Ready { config_options, .. } = availability {
743                    let config = default_config_selections(&config_options);
744                    return Ok(Some(ChatTarget::Acp {
745                        agent: entry.id,
746                        config,
747                    }));
748                }
749            }
750        }
751
752        // Fall back to direct HTTP providers (Codex, OpenAI, Anthropic, Gemini + HTTP custom).
753        let providers = providers::list(Some(&self.state), Some(worktree))?;
754        let mut direct_backends: Vec<DirectBackend> = HttpProvider::ALL
755            .into_iter()
756            .map(|provider| DirectBackend::Builtin { provider })
757            .collect();
758        for (name, view) in providers.custom {
759            if matches!(
760                view,
761                providers::CustomView::Alias {
762                    provider: Provider::ClaudeAgent
763                }
764            ) {
765                continue;
766            }
767            if let Ok(custom) = name.as_str().parse::<CustomBackendName>() {
768                direct_backends.push(DirectBackend::Custom { name: custom });
769            }
770        }
771        let listings = futures_util::future::join_all(direct_backends.iter().map(|backend| {
772            llm::models::list(backend.to_backend(), Some(&self.state), Some(worktree))
773        }))
774        .await;
775        Ok(direct_backends
776            .into_iter()
777            .zip(listings)
778            .find_map(|(backend, listing)| {
779                let listing = listing.ok()?;
780                listing
781                    .models
782                    .into_iter()
783                    .next()
784                    .map(|model| ChatTarget::Direct {
785                        backend,
786                        model: model.slug,
787                        effort: model.default_effort,
788                    })
789            }))
790    }
791
792    async fn last_target(
793        &self,
794        workspace: &Path,
795        checkout: &repository::Identity,
796    ) -> Result<Option<ChatTarget>, String> {
797        let branch = Place::for_checkout(workspace, checkout);
798        Ok(store::chat::for_branch(&self.state, &branch)
799            .await?
800            .into_iter()
801            .find_map(|session| {
802                session
803                    .target
804                    .filter(|target| !target.is_legacy_claude_agent())
805            }))
806    }
807
808    /// Persist an empty session, with no target unless one is explicitly selected.
809    pub async fn create(
810        &self,
811        worktree: &Path,
812        selection: Option<ChatTarget>,
813    ) -> Result<Session, String> {
814        self.create_for_branch(worktree, None, selection).await
815    }
816
817    /// Create only on the checkout the person selected, not a branch switched in meanwhile.
818    pub async fn create_for_branch(
819        &self,
820        workspace: &Path,
821        branch: Option<&Place>,
822        selection: Option<ChatTarget>,
823    ) -> Result<Session, String> {
824        let (workspace, repository) = checkout_for(workspace, branch).await?;
825        let worktree = workspace.as_path();
826        crate::config::read_workspace_config(worktree).map_err(|error| error.to_string())?;
827        let target = if let Some(selection) = selection {
828            let previous = self.last_target(worktree, &repository).await?;
829            Some(
830                self.resolve_target(worktree, selection, previous.as_ref())
831                    .await?,
832            )
833        } else {
834            None
835        };
836        let now = crate::broker::now();
837        let legacy_migration_notice = target
838            .as_ref()
839            .is_some_and(ChatTarget::is_legacy_claude_agent);
840        let session = Session {
841            id: format!("chat-{}", agent::uuid()?).parse()?,
842            title: "New chat".into(),
843            worktree: worktree.into(),
844            repository: Some(repository),
845            target,
846            view: SessionView::default(),
847            created_at: now,
848            updated_at: now,
849            activity: None,
850            moved_from: None,
851            acp_binding: None,
852            running: false,
853            waiting_permission: false,
854            live_config_options: Vec::new(),
855            verify_bridge_state: VerifyBridgeState::NotConnected,
856            legacy_migration_notice,
857            unavailable: None,
858        };
859        let session = crate::task::blocking(move || session.with_checkout()).await?;
860        if let Some(reason) = &session.unavailable {
861            return Err(reason.clone());
862        }
863        let receipts = Receipts::open(&self.state, worktree).await?;
864        let result = receipts.create_chat(&session).await;
865        let closed = receipts.close().await;
866        result.and(closed)?;
867        Ok(session)
868    }
869
870    /// Discover the live choices used by the Chat branch picker, independently of Verify search.
871    pub async fn branches(&self, launch: Option<&Path>) -> Result<BranchListing, String> {
872        let runs = store::read_catalog(&self.state).await?;
873        let sessions = self.list(None, None).await?;
874        let launch = launch.map(Path::to_owned);
875        crate::task::blocking(move || {
876            let mut branches =
877                live::branches(&runs, launch.as_deref(), &mut live::Discovery::default()).branches;
878            for session in sessions
879                .iter()
880                .filter(|session| session.unavailable.is_none())
881            {
882                let place = session.branch();
883                if !branches.iter().any(|branch| branch.place == place) {
884                    let label = session.label();
885                    branches.push(Branch {
886                        place,
887                        project: label.project,
888                        name: label.branch,
889                        workspace: session.worktree.clone(),
890                        runs: Vec::new(),
891                    });
892                }
893            }
894            BranchListing { branches, sessions }
895        })
896        .await
897    }
898
899    /// Rebind the saved conversation to a live choice, excluding active turns in any process.
900    /// Evicts any warm ACP child owned by this process for the moved session.
901    pub async fn set_worktree(
902        &self,
903        id: &SessionId,
904        worktree: &Path,
905        launch: Option<&Path>,
906    ) -> Result<Session, MoveError> {
907        let path = crate::platform::path_text(worktree);
908        let invalid = || MoveError::Invalid(path.clone());
909        let branch = self
910            .branches(launch)
911            .await
912            .map_err(MoveError::Failed)?
913            .branches
914            .into_iter()
915            .find(|branch| crate::platform::path_text(&branch.workspace) == path)
916            .ok_or_else(invalid)?;
917        let (workspace, repository) = checkout_for(&branch.workspace, Some(&branch.place))
918            .await
919            .map_err(|_| invalid())?;
920        let receipts = Receipts::open(&self.state, &workspace)
921            .await
922            .map_err(MoveError::Failed)?;
923        let result = receipts
924            .set_chat_worktree(&self.state, id, workspace, repository)
925            .await;
926        let closed = receipts.close().await;
927        let (saved, changed) = result
928            .and_then(|saved| closed.map(|()| saved))
929            .map_err(MoveError::Failed)?
930            .ok_or(MoveError::Busy)?;
931        if changed {
932            if let Some(child) = self.pool.take_any(id) {
933                let _ = child.terminate().await;
934            }
935            crate::changes::Publisher::new(&self.state)
936                .notify(crate::changes::Change::SessionInvalidated(id.clone()));
937        }
938        crate::task::blocking(move || saved.with_checkout())
939            .await
940            .map_err(MoveError::Failed)
941    }
942
943    /// Keep the catalog's activity order while matching every word across its displayed labels.
944    pub async fn list(
945        &self,
946        worktree: Option<&Path>,
947        query: Option<&str>,
948    ) -> Result<Vec<Session>, String> {
949        let words = query
950            .unwrap_or_default()
951            .split_whitespace()
952            .map(str::to_lowercase)
953            .collect::<Vec<_>>();
954        let sessions = store::chat::list(&self.state, worktree).await?;
955        crate::task::blocking(move || {
956            let mut identities = BTreeMap::new();
957            sessions
958                .into_iter()
959                .filter(|session| session.matches(&words))
960                .map(|mut session| {
961                    let checkout =
962                        identities
963                            .entry(session.worktree.clone())
964                            .or_insert_with(|| {
965                                session
966                                    .worktree
967                                    .is_dir()
968                                    .then(|| repository::identify(&session.worktree))
969                            });
970                    session.unavailable = match checkout {
971                        Some(current) => checkout_refusal(session.repository.as_ref(), current),
972                        None => Some("This Chat's worktree no longer exists.".into()),
973                    };
974                    session.legacy_migration_notice = session.legacy_migration_notice
975                        || session
976                            .target
977                            .as_ref()
978                            .is_some_and(ChatTarget::is_legacy_claude_agent);
979                    session
980                })
981                .collect()
982        })
983        .await
984    }
985
986    /// Find a conversation by its former checkout, including a workspace within the worktree.
987    pub async fn latest_for_unavailable_checkout(
988        &self,
989        workspace: &Path,
990    ) -> Result<Option<Session>, String> {
991        let workspace = workspace.to_path_buf();
992        let workspace = crate::task::blocking(move || {
993            let workspace = crate::workspace::canonical_target(&workspace)
994                .map_err(|error| error.to_string())?;
995            Ok::<_, String>(
996                crate::repository::identify(&workspace)
997                    .worktree_path
998                    .is_none()
999                    .then_some(workspace),
1000            )
1001        })
1002        .await??;
1003        let Some(workspace) = workspace else {
1004            return Ok(None);
1005        };
1006        let sessions = store::chat::list(&self.state, None).await?;
1007        crate::task::blocking(move || {
1008            sessions
1009                .into_iter()
1010                .filter(|session| {
1011                    let recorded = session
1012                        .repository
1013                        .as_ref()
1014                        .and_then(|repo| repo.worktree_path.as_deref())
1015                        .unwrap_or(&session.worktree);
1016                    crate::platform::paths::relative_beneath(&workspace, recorded).is_some()
1017                        || crate::platform::paths_equal(&workspace, recorded)
1018                })
1019                .map(Session::with_checkout)
1020                .find(|session| session.unavailable.is_some())
1021        })
1022        .await
1023    }
1024
1025    /// The most recently active saved session on this branch, even if its checkout is gone.
1026    pub async fn latest_for_branch(&self, branch: &Place) -> Result<Option<Session>, String> {
1027        let mut sessions = store::chat::for_branch(&self.state, branch)
1028            .await?
1029            .into_iter();
1030        crate::task::blocking(move || sessions.next().map(Session::with_checkout)).await
1031    }
1032
1033    /// Prefer the newest usable session for branch navigation. If the checkout moved and none
1034    /// can work on it, keep the newest saved conversation reachable with its diagnostic.
1035    pub async fn latest_for_navigation(&self, branch: &Place) -> Result<Option<Session>, String> {
1036        let sessions = store::chat::for_branch(&self.state, branch).await?;
1037        crate::task::blocking(move || {
1038            let mut fallback = None;
1039            for session in sessions {
1040                let session = session.with_checkout();
1041                if session.unavailable.is_none() {
1042                    return Some(session);
1043                }
1044                if fallback.is_none() {
1045                    fallback = Some(session);
1046                }
1047            }
1048            fallback
1049        })
1050        .await
1051    }
1052
1053    /// The latest session whose exact checkout can be worked on now.
1054    pub async fn latest_available_for_branch(
1055        &self,
1056        branch: &Place,
1057    ) -> Result<Option<Session>, String> {
1058        let sessions = store::chat::for_branch(&self.state, branch).await?;
1059        crate::task::blocking(move || {
1060            sessions
1061                .into_iter()
1062                .find(|session| session.check_checkout().is_ok())
1063        })
1064        .await
1065    }
1066
1067    /// The oldest usable checkout anchors Current when there is no Verify workspace.
1068    /// Activity in a newer session must not redirect scans, edits or tools.
1069    pub async fn current_worktree(&self, branch: &Place) -> Result<Option<PathBuf>, String> {
1070        let sessions = store::chat::for_branch(&self.state, branch).await?;
1071        crate::task::blocking(move || {
1072            sessions
1073                .into_iter()
1074                .filter(|session| session.check_checkout().is_ok())
1075                .min_by(|a, b| (a.created_at, &a.id).cmp(&(b.created_at, &b.id)))
1076                .map(|session| session.worktree)
1077        })
1078        .await
1079    }
1080
1081    /// Save a view without changing the session's activity order or requiring a live checkout.
1082    pub async fn set_view(&self, id: &SessionId, view: SessionView) -> Result<Session, String> {
1083        let session = store::chat::load(&self.state, id).await?;
1084        let receipts = Receipts::open(&self.state, &session.worktree).await?;
1085        let result = receipts.set_chat_view(&self.state, id, view).await;
1086        let closed = receipts.close().await;
1087        let (saved, changed) = result.and_then(|saved| closed.map(|()| saved))?;
1088        if changed {
1089            crate::changes::Publisher::new(&self.state)
1090                .notify(crate::changes::Change::SessionInvalidated(id.clone()));
1091        }
1092        crate::task::blocking(move || saved.with_checkout()).await
1093    }
1094
1095    /// Acknowledge the latest settled outcome without changing the session's activity order.
1096    /// A turn still running will become unseen when it settles, even if this is called now.
1097    pub async fn mark_seen(&self, id: &SessionId) -> Result<(), String> {
1098        let session = store::chat::load(&self.state, id).await?;
1099        if !session.unseen() {
1100            return Ok(());
1101        }
1102        let receipts = Receipts::open(&self.state, &session.worktree).await?;
1103        let result = receipts.mark_chat_seen(&self.state, id).await;
1104        let closed = receipts.close().await;
1105        let changed = result.and_then(|changed| closed.map(|()| changed))?;
1106        if changed {
1107            crate::changes::Publisher::new(&self.state)
1108                .notify(crate::changes::Change::SessionInvalidated(id.clone()));
1109        }
1110        Ok(())
1111    }
1112
1113    /// Chat records are append-only. Readers can detect a missed hint without parsing a
1114    /// transcript, with `None` covering a session that has not yet accepted a turn.
1115    pub fn transcript_size(&self, id: &SessionId) -> Option<u64> {
1116        crate::platform::open_regular(&path(&self.state, id))
1117            .and_then(|file| file.metadata())
1118            .ok()
1119            .map(|file| file.len())
1120    }
1121
1122    /// Lightweight SQLite watermark across `(chat_sessions, chat_active_turns,
1123    /// chat_pending_permissions)` tracked by Desktop `watch.rs` alongside `transcript_size`.
1124    pub async fn watermark(&self, id: &SessionId) -> Result<Option<ChatWatermark>, String> {
1125        store::chat::watermark(&self.state, id).await
1126    }
1127
1128    /// Evict any local warm ACP child whose committed `acp_binding.generation` has advanced
1129    /// (called on `Change::SessionInvalidated` so another process's move/switch terminates stale
1130    /// local children promptly).
1131    pub async fn evict_warm_if_stale(&self, id: &SessionId) {
1132        let committed_gen = store::chat::load(&self.state, id)
1133            .await
1134            .ok()
1135            .and_then(|session| session.acp_binding)
1136            .map(|binding| binding.generation);
1137        if let Some(child) = self.pool.take_if_generation_stale(id, committed_gen) {
1138            let _ = child.terminate().await;
1139        }
1140    }
1141
1142    /// The model/agent's streamed text, rich ACP blocks, live permissions, and Run cards.
1143    pub async fn open(&self, id: &SessionId) -> Result<View, String> {
1144        let session = store::chat::load(&self.state, id).await?;
1145        let session = crate::task::blocking(move || session.with_checkout()).await?;
1146        let running = session.running;
1147        let waiting_permission = session.waiting_permission;
1148        let live_config_options = session.live_config_options.clone();
1149        let verify_bridge_state = session.verify_bridge_state;
1150        let live_permissions = store::chat::list_permissions(&self.state, id).await?;
1151        let conversation = Conversation::load(&path(&self.state, id))?;
1152        let mut turns = transcript::turns(conversation.as_ref(), running, &live_permissions);
1153        transcript::update_runs(&self.state, &session.worktree, id, &mut turns).await;
1154        Ok(View {
1155            session,
1156            running,
1157            waiting_permission,
1158            turns,
1159            live_config_options,
1160            verify_bridge_state,
1161        })
1162    }
1163
1164    /// Save a Chat target for the next turn without adding a message. An accepted turn keeps
1165    /// the target it started with, even if the user changes the picker while it streams.
1166    pub async fn set_target(
1167        &self,
1168        id: &SessionId,
1169        selection: ChatTarget,
1170    ) -> Result<Session, String> {
1171        let session = self.available(id).await?;
1172        let selection = self
1173            .resolve_target(&session.worktree, selection, session.target.as_ref())
1174            .await?;
1175        let receipts = Receipts::open(&self.state, &session.worktree).await?;
1176        let saved = receipts.set_chat_target(&self.state, id, selection).await;
1177        let closed = receipts.close().await;
1178        let (saved, agent_changed) = saved.and_then(|result| closed.map(|()| result))?;
1179        if agent_changed && let Some(child) = self.pool.take_any(id) {
1180            let _ = child.terminate().await;
1181        }
1182        crate::changes::Publisher::new(&self.state)
1183            .notify(crate::changes::Change::SessionInvalidated(id.clone()));
1184        crate::task::blocking(move || saved.with_checkout()).await
1185    }
1186
1187    /// Respond to a pending ACP permission card (`PENDING -> SELECTED` in one `IMMEDIATE`
1188    /// SQLite transaction) and wake any local owning turn immediately.
1189    pub async fn respond_permission(
1190        &self,
1191        id: &SessionId,
1192        permission_id: &str,
1193        option_id: &str,
1194    ) -> Result<bool, String> {
1195        let session = store::chat::load(&self.state, id).await?;
1196        let receipts = Receipts::open(&self.state, &session.worktree).await?;
1197        let updated = receipts
1198            .respond_chat_permission(id, permission_id, option_id)
1199            .await;
1200        let closed = receipts.close().await;
1201        let updated = updated.and_then(|changed| closed.map(|()| changed))?;
1202        if updated {
1203            self.permission_notify.notify_waiters();
1204            crate::changes::Publisher::new(&self.state)
1205                .notify(crate::changes::Change::SessionInvalidated(id.clone()));
1206        }
1207        Ok(updated)
1208    }
1209
1210    /// Record explicit machine-local Workspace Trust for an ACP agent on a worktree/repo scope.
1211    pub async fn trust_workspace(
1212        &self,
1213        worktree: &Path,
1214        agent_id: &AgentId,
1215    ) -> Result<TrustRecord, String> {
1216        let worktree =
1217            crate::workspace::canonical_target(worktree).map_err(|error| error.to_string())?;
1218        let state = self.state.clone();
1219        let agent_id = agent_id.clone();
1220        let (spec, scope, fingerprint) = crate::task::blocking(move || {
1221            let identity = repository::identify(&worktree);
1222            let spec = catalog::resolve_spec(&agent_id, Some(&state), Some(&worktree))?;
1223            let resolved = acp::trust::resolve_executable(
1224                &spec.program,
1225                Some(&worktree),
1226                spec.reject_worktree_executable,
1227            )?;
1228            let fingerprint = acp::trust::LauncherFingerprint::compute(&resolved, &spec.args)?;
1229            let scope = TrustScope::for_worktree(&worktree, &identity)?;
1230            Ok::<_, String>((spec, scope, fingerprint))
1231        })
1232        .await??;
1233        acp::trust::grant_trust(Some(&self.state), None, spec.id, scope, fingerprint).await
1234    }
1235
1236    /// List all saved machine-local ACP Workspace Trust records.
1237    pub fn list_trust(&self) -> Result<Vec<TrustRecord>, String> {
1238        acp::trust::list_trust(Some(&self.state), None)
1239    }
1240
1241    /// Revoke a saved Workspace Trust record and terminate any matching warm ACP children.
1242    pub async fn revoke_trust(
1243        &self,
1244        agent_id: &AgentId,
1245        scope: &TrustScope,
1246    ) -> Result<bool, String> {
1247        let removed = acp::trust::revoke_trust(Some(&self.state), None, agent_id, scope).await?;
1248        if removed {
1249            let drained = self.pool.drain_all();
1250            let current_owner = WarmOwner::current().ok();
1251            for child in drained {
1252                if &child.agent_id == agent_id {
1253                    let session_id = child.session_id.clone();
1254                    let generation = child.generation;
1255                    let _ = child.terminate().await;
1256                    if let Some(warm_owner) = current_owner
1257                        && let Ok(session) = store::chat::load(&self.state, &session_id).await
1258                        && let Ok(receipts) = Receipts::open(&self.state, &session.worktree).await
1259                    {
1260                        let _ = receipts
1261                            .clear_acp_warm_owner(&session_id, generation, warm_owner)
1262                            .await;
1263                        let _ = receipts.close().await;
1264                    }
1265                } else {
1266                    self.pool.park(child);
1267                }
1268            }
1269        }
1270        Ok(removed)
1271    }
1272
1273    async fn available(&self, id: &SessionId) -> Result<Session, String> {
1274        let session = store::chat::load(&self.state, id).await?;
1275        let mut session = crate::task::blocking(move || session.with_checkout()).await?;
1276        match session.unavailable.take() {
1277            Some(reason) => Err(reason),
1278            None => Ok(session),
1279        }
1280    }
1281
1282    /// Start a durable turn and return as soon as it has an accepted user message. The recorder
1283    /// notifies `SessionInvalidated(id)` as text, tool outcomes, permissions and Run references arrive.
1284    pub async fn send(
1285        &self,
1286        id: &SessionId,
1287        text: String,
1288        selection: Option<ChatTarget>,
1289    ) -> Result<(), SendError> {
1290        if text.trim().is_empty() || text.len() > PROMPT_BYTES {
1291            return Err(SendError::Failed(format!(
1292                "Chat messages must have text and be at most {PROMPT_BYTES} bytes."
1293            )));
1294        }
1295        let active = self.claim(id)?;
1296        let chat = self.clone();
1297        let id = id.clone();
1298        let (accepted, acknowledgement) = tokio::sync::oneshot::channel();
1299        // Once queued, the library owns preparation and cleanup independently of the IPC caller.
1300        tokio::spawn(async move {
1301            match chat.prepare(&id, &text, selection, &active.cancel).await {
1302                Ok(prepared) => {
1303                    let _ = accepted.send(Ok(()));
1304                    chat.finish(prepared, text, active).await;
1305                }
1306                Err(error) => {
1307                    drop(active);
1308                    let _ = accepted.send(Err(error));
1309                }
1310            }
1311        });
1312        acknowledgement
1313            .await
1314            .map_err(|_| SendError::Failed("The queued Chat turn did not start.".into()))?
1315    }
1316
1317    async fn prepare(
1318        &self,
1319        id: &SessionId,
1320        text: &str,
1321        selection: Option<ChatTarget>,
1322        cancel: &CancellationToken,
1323    ) -> Result<Prepared, SendError> {
1324        let saved = store::chat::load(&self.state, id).await?;
1325        let file = path(&self.state, id);
1326        let owner = store::chat::Owner::current()?;
1327        let receipts = Receipts::open(&self.state, &saved.worktree).await?;
1328        let prepared = async {
1329            // Claim and read the checkout in one transaction. If a move won the race, this
1330            // turn starts on the newly saved workspace, never the stale path read above.
1331            let session = receipts.claim_chat(&self.state, id, &owner).await?;
1332            self.record_owner(id, owner.token.clone(), session.worktree.clone());
1333            let prepared = async {
1334                let mut session = crate::task::blocking(move || session.with_checkout()).await?;
1335                if let Some(reason) = session.unavailable.take() {
1336                    return Err(SendError::Failed(reason));
1337                }
1338                let previous_target = session.target.clone();
1339                let context = self.context(&session.worktree)?;
1340                let explicit_selection = if let Some(selection) = selection {
1341                    Some(tokio::select! {
1342                        _ = cancel.cancelled() => return Err(SendError::Failed("Chat stopped before accepting the turn.".into())),
1343                        resolved = self.resolve_target(context.repo(), selection, previous_target.as_ref()) => resolved?,
1344                    })
1345                } else {
1346                    None
1347                };
1348                let effective_target = explicit_selection
1349                    .clone()
1350                    .or(previous_target.clone())
1351                    .ok_or(SendError::NoModel)?;
1352
1353                // Validate target and enforce Workspace Trust BEFORE recording Kind::Send into JSONL.
1354                let conversation = Conversation::load(&file)?;
1355                let send = conversation.as_ref().map(Conversation::sends).unwrap_or(0) + 1;
1356                let history = conversation
1357                    .as_ref()
1358                    .map(Conversation::history)
1359                    .transpose()?
1360                    .unwrap_or_default();
1361
1362                let engine = match &effective_target {
1363                    ChatTarget::LegacyClaudeAgent { .. } => {
1364                        return Err(SendError::LegacyRetired(
1365                            "Legacy claude-agent Chat execution has been retired. Switch this session to Claude ACP or a direct API provider to continue."
1366                                .into(),
1367                        ));
1368                    }
1369                    ChatTarget::Direct {
1370                        backend,
1371                        model,
1372                        effort,
1373                    } => {
1374                        let engine_label = effective_target.engine_label();
1375                        let previous_label = previous_target
1376                            .as_ref()
1377                            .map(ChatTarget::engine_label)
1378                            .filter(|prev| prev != &engine_label)
1379                            .or_else(|| {
1380                                session
1381                                    .acp_binding
1382                                    .as_ref()
1383                                    .map(|b| format!("ACP ({})", b.agent_id))
1384                            });
1385                        let prior_turns_count =
1386                            conversation.as_ref().map(Conversation::sends).unwrap_or(0);
1387                        ChatEngine::Direct {
1388                            selection: DirectSelection {
1389                                backend: backend.clone(),
1390                                model: model.clone(),
1391                                effort: effort.clone(),
1392                            },
1393                            engine_label,
1394                            previous_engine_label: previous_label,
1395                            prior_turns_count,
1396                        }
1397                    }
1398                    ChatTarget::Acp { agent, config } => {
1399                        let state = self.state.clone();
1400                        let worktree = session.worktree.clone();
1401                        let identity = session.repository.clone().unwrap_or_default();
1402                        let agent_id = agent.clone();
1403                        let trust_result = crate::task::blocking(move || {
1404                            acp::engine::verify_launch(&state, &worktree, &identity, &agent_id)
1405                        })
1406                        .await
1407                        .map_err(SendError::Failed)?
1408                        .map_err(SendError::Failed)?;
1409                        let launch = match trust_result {
1410                            Ok(launch) => launch,
1411                            Err(requirement) => {
1412                                return Err(SendError::TrustRequired(Box::new(requirement)));
1413                            }
1414                        };
1415                        let prior_turns = transcript::turns(conversation.as_ref(), false, &[]);
1416                        let last_outcome = conversation.as_ref().and_then(transcript::last_outcome);
1417                        let previous_engine_label = previous_engine_label(
1418                            previous_target.as_ref(),
1419                            session.acp_binding.as_ref(),
1420                            session.legacy_migration_notice,
1421                            agent,
1422                        );
1423                        ChatEngine::Acp {
1424                            config: config.clone(),
1425                            launch: Box::new(launch),
1426                            previous_engine_label,
1427                            prior_turns,
1428                            last_outcome,
1429                        }
1430                    }
1431                };
1432
1433                if cancel.is_cancelled() {
1434                    return Err(SendError::Failed(
1435                        "Chat stopped before accepting the turn.".into(),
1436                    ));
1437                }
1438
1439                if send == 1 {
1440                    session.title = text
1441                        .lines()
1442                        .find_map(|line| {
1443                            let line = line.trim();
1444                            (!line.is_empty()).then(|| line.chars().take(TITLE_CHARS).collect())
1445                        })
1446                        .expect("nonblank prompt contains a title");
1447                }
1448                let mut recorder = Recorder::chat(&self.state, &file, id, send)?;
1449                recorder.event(Kind::Send(Send {
1450                    text: Some(text.to_owned()),
1451                    framing: None,
1452                    files_changed: None,
1453                    tools: None,
1454                }));
1455                let prompt = rig_core::message::Message::user(text.to_owned());
1456                recorder.message(1, &prompt, false);
1457                recorder.check_saved()?;
1458                session.updated_at = crate::broker::now();
1459                session.activity = Some(Activity {
1460                    outcome: Outcome::Running,
1461                    unseen: false,
1462                });
1463                let (_target, acp_binding) = receipts
1464                    .accept_chat(&session, Some(effective_target))
1465                    .await?;
1466                Ok::<_, SendError>((session, recorder, send, history, engine, acp_binding, context))
1467            }
1468            .await;
1469            if prepared.is_err() {
1470                let _ = receipts.finish_chat(id, &owner, None, None).await;
1471            }
1472            prepared
1473        }
1474        .await;
1475        let (session, recorder, send, history, engine, acp_binding, context) = match prepared {
1476            Ok(prepared) => prepared,
1477            Err(error) => {
1478                let _ = receipts.close().await;
1479                return Err(error);
1480            }
1481        };
1482        Ok(Prepared {
1483            session,
1484            send,
1485            engine,
1486            acp_binding,
1487            context,
1488            receipts,
1489            owner,
1490            recorder,
1491            history,
1492        })
1493    }
1494
1495    async fn finish(&self, prepared: Prepared, text: String, active: Active) {
1496        let Prepared {
1497            mut session,
1498            send,
1499            engine,
1500            acp_binding,
1501            context,
1502            receipts,
1503            owner,
1504            mut recorder,
1505            history,
1506        } = prepared;
1507        let context = context.with_origin(runs::Origin::Chat {
1508            session_id: session.id.clone(),
1509            title: session.title.clone(),
1510            send: Some(send),
1511        });
1512        let directory = self.state.join("chat-output");
1513        let output = crate::workspace::prepare_directory(&directory, &session.worktree)
1514            .map_err(|error| agent::error::Failure::from(error.to_string()))
1515            .and_then(|directory| {
1516                crate::platform::private_tempdir_in("turn-", &directory)
1517                    .map_err(|error| agent::error::Failure::from(error.to_string()))
1518            });
1519        let mut settled_acp: Option<(u64, Option<usize>, Option<WarmOwner>)> = None;
1520        let mut park_reaper = false;
1521        let result = match output {
1522            Ok(output) => {
1523                let tools = tools::Tools::new(&context, output.path())
1524                    .guard_checkout(session.repository.as_ref());
1525                match engine {
1526                    ChatEngine::Direct {
1527                        selection,
1528                        engine_label,
1529                        previous_engine_label,
1530                        prior_turns_count,
1531                    } => {
1532                        if let Some(prev_label) = previous_engine_label
1533                            && prior_turns_count > 0
1534                        {
1535                            recorder.event(Kind::Handoff(crate::agent::session::HandoffEvent {
1536                                from: prev_label,
1537                                to: engine_label.clone(),
1538                                summary: format!(
1539                                    "Continued conversation in {engine_label} carrying {prior_turns_count} prior turn(s)."
1540                                ),
1541                            }));
1542                        }
1543                        let turn = agent::chat_turn(
1544                            &selection,
1545                            &context,
1546                            &tools,
1547                            agent::ChatPrompt::new(
1548                                history,
1549                                text,
1550                                session.moved_from.as_deref(),
1551                                &session.worktree,
1552                            ),
1553                            &mut recorder,
1554                            &active.cancel,
1555                        );
1556                        let requested = async {
1557                            let mut check = tokio::time::interval(STOP_CHECK);
1558                            check.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
1559                            loop {
1560                                check.tick().await;
1561                                if receipts.chat_stop_requested(&session.id, &owner).await
1562                                    == Ok(true)
1563                                {
1564                                    active.cancel.cancel();
1565                                    break;
1566                                }
1567                            }
1568                        };
1569                        tokio::pin!(turn);
1570                        tokio::select! {
1571                            answer = &mut turn => answer,
1572                            () = requested => turn.await,
1573                        }
1574                    }
1575                    ChatEngine::Acp {
1576                        config,
1577                        launch,
1578                        previous_engine_label,
1579                        prior_turns,
1580                        last_outcome,
1581                    } => {
1582                        let identity = session.repository.clone().unwrap_or_default();
1583                        let outcome = acp::engine::run_turn(
1584                            AcpTurnInput {
1585                                session_id: &session.id,
1586                                worktree: &session.worktree,
1587                                identity: &identity,
1588                                moved_from: session.moved_from.as_deref(),
1589                                send,
1590                                prior_turns: &prior_turns,
1591                                last_outcome,
1592                                previous_engine_label: previous_engine_label.as_deref(),
1593                                user_text: &text,
1594                                requested_config: &config,
1595                                binding: acp_binding,
1596                                launch: *launch,
1597                                context: &context,
1598                                tools: &tools,
1599                                receipts: &receipts,
1600                                owner: &owner,
1601                                pool: &self.pool,
1602                                permission_notify: &self.permission_notify,
1603                                turn_cancel: &active.cancel,
1604                            },
1605                            &mut recorder,
1606                        )
1607                        .await;
1608                        let completed_send = outcome.result.is_ok().then_some(send);
1609                        if outcome.warm_owner.is_some() {
1610                            park_reaper = true;
1611                        }
1612                        settled_acp =
1613                            Some((outcome.generation, completed_send, outcome.warm_owner));
1614                        outcome.result
1615                    }
1616                }
1617            }
1618            Err(error) => Err(error),
1619        };
1620        let answer = match result {
1621            Ok(text) => Answer::Completed(text),
1622            Err(failure) => Answer::Failed {
1623                code: Some(failure.code),
1624                message: Some(failure.message),
1625            },
1626        };
1627        session.activity = Some(Activity {
1628            outcome: transcript::outcome(&answer),
1629            unseen: true,
1630        });
1631        session.updated_at = crate::broker::now().max(session.updated_at);
1632        recorder.event(Kind::Answer(answer));
1633        let flushed = recorder.check_saved().is_ok();
1634        let settled_acp = if flushed {
1635            settled_acp
1636        } else {
1637            settled_acp.map(|(generation, _, warm_owner)| (generation, None, warm_owner))
1638        };
1639        // Publish the settled outcome, release ownership, and advance ACP settled_send together.
1640        let _ = receipts
1641            .finish_chat(&session.id, &owner, Some(&session), settled_acp)
1642            .await;
1643        let _ = receipts.close().await;
1644        if park_reaper {
1645            self.schedule_idle_reaper();
1646        }
1647        drop(active);
1648        recorder.notify();
1649    }
1650
1651    fn schedule_idle_reaper(&self) {
1652        let pool = self.pool.clone();
1653        let state = self.state.clone();
1654        tokio::spawn(async move {
1655            tokio::time::sleep(IDLE_TTL + IDLE_REAP_MARGIN).await;
1656            let expired = pool.take_expired();
1657            let current_owner = WarmOwner::current().ok();
1658            for child in expired {
1659                let session_id = child.session_id.clone();
1660                let generation = child.generation;
1661                let _ = child.terminate().await;
1662                if let Some(warm_owner) = current_owner
1663                    && let Ok(session) = store::chat::load(&state, &session_id).await
1664                    && let Ok(receipts) = Receipts::open(&state, &session.worktree).await
1665                {
1666                    let _ = receipts
1667                        .clear_acp_warm_owner(&session_id, generation, warm_owner)
1668                        .await;
1669                    let _ = receipts.close().await;
1670                }
1671            }
1672        });
1673    }
1674
1675    /// Stop the active turn, even if another app owns it. Accepted Verify Runs are independent.
1676    /// Always commits the SQLite Stop transaction (`stop_requested = true` + permission
1677    /// cancellation) BEFORE firing the in-memory CancellationToken.
1678    pub async fn stop(&self, id: &SessionId) -> Result<bool, String> {
1679        let local = self
1680            .active
1681            .state
1682            .lock()
1683            .expect("Chat active turns lock")
1684            .turns
1685            .get(id)
1686            .cloned();
1687        if let Some(entry) = local {
1688            if let (Some(token), Some(worktree)) = (&entry.owner_token, &entry.worktree) {
1689                let receipts = Receipts::open(&self.state, worktree).await?;
1690                let stopped = receipts.stop_chat_by_token(id, token).await;
1691                let closed = receipts.close().await;
1692                let _ = stopped.and_then(|value| closed.map(|()| value))?;
1693            }
1694            self.permission_notify.notify_waiters();
1695            entry.cancel.cancel();
1696            crate::changes::Publisher::new(&self.state)
1697                .notify(crate::changes::Change::SessionInvalidated(id.clone()));
1698            return Ok(true);
1699        }
1700        let Some(owner) = store::chat::turn_owner(&self.state, id).await? else {
1701            return Ok(false);
1702        };
1703        let session = store::chat::load(&self.state, id).await?;
1704        let stopped = self.stop_exact(&session, owner).await?;
1705        if stopped {
1706            crate::changes::Publisher::new(&self.state)
1707                .notify(crate::changes::Change::SessionInvalidated(id.clone()));
1708        }
1709        Ok(stopped)
1710    }
1711
1712    /// The desktop's quit prompt names every running Chat. Deliver the same Stop to those
1713    /// turns even when another process owns them, before the desktop window closes.
1714    pub async fn stop_running(&self) -> Result<(), StopRunningError> {
1715        let local: Vec<(SessionId, ActiveEntry)> = {
1716            let active = self.active.state.lock().expect("Chat active turns lock");
1717            active
1718                .turns
1719                .iter()
1720                .map(|(id, entry)| (id.clone(), entry.clone()))
1721                .collect()
1722        };
1723        let mut failed = Vec::new();
1724        let mut local_ids = std::collections::BTreeSet::new();
1725        for (id, entry) in local {
1726            local_ids.insert(id.clone());
1727            if let (Some(token), Some(worktree)) = (&entry.owner_token, &entry.worktree) {
1728                match Receipts::open(&self.state, worktree).await {
1729                    Ok(receipts) => {
1730                        let stopped = receipts.stop_chat_by_token(&id, token).await;
1731                        let closed = receipts.close().await;
1732                        match stopped.and(closed) {
1733                            Ok(()) => entry.cancel.cancel(),
1734                            Err(error) => failed.push(format!("{id}: {error}")),
1735                        }
1736                    }
1737                    Err(error) => failed.push(format!("{id}: {error}")),
1738                }
1739            } else {
1740                entry.cancel.cancel();
1741            }
1742        }
1743        self.permission_notify.notify_waiters();
1744        let turns = store::chat::active_turns(&self.state, true)
1745            .await
1746            .map_err(StopRunningError::Unreadable)?;
1747        for (session, owner) in turns {
1748            if owner.in_current_process() && local_ids.contains(&session.id) {
1749                continue;
1750            }
1751            if let Err(error) = self.stop_exact(&session, owner).await {
1752                failed.push(format!("{}: {error}", session.id));
1753            }
1754        }
1755        if failed.is_empty() {
1756            Ok(())
1757        } else {
1758            Err(StopRunningError::Turns(failed))
1759        }
1760    }
1761
1762    async fn stop_exact(
1763        &self,
1764        session: &Session,
1765        owner: store::chat::Owner,
1766    ) -> Result<bool, String> {
1767        let receipts = Receipts::open(&self.state, &session.worktree).await?;
1768        let stopped = receipts.stop_chat(&session.id, owner).await;
1769        let closed = receipts.close().await;
1770        stopped.and_then(|stopped| closed.map(|()| stopped))
1771    }
1772
1773    async fn resolve_target(
1774        &self,
1775        worktree: &Path,
1776        selection: ChatTarget,
1777        previous: Option<&ChatTarget>,
1778    ) -> Result<ChatTarget, String> {
1779        match selection {
1780            ChatTarget::LegacyClaudeAgent { .. } => Err(
1781                "Legacy claude-agent Chat execution has been retired. Choose an ACP Chat agent or a direct API provider."
1782                    .into(),
1783            ),
1784            ChatTarget::Direct {
1785                backend,
1786                model,
1787                effort,
1788            } => {
1789                let prev = match previous {
1790                    Some(ChatTarget::Direct {
1791                        backend,
1792                        model,
1793                        effort,
1794                    }) => Some(DirectSelection {
1795                        backend: backend.clone(),
1796                        model: model.clone(),
1797                        effort: effort.clone(),
1798                    }),
1799                    _ => None,
1800                };
1801                let resolved = self
1802                    .resolve_direct(
1803                        worktree,
1804                        DirectSelection {
1805                            backend,
1806                            model,
1807                            effort,
1808                        },
1809                        prev.as_ref(),
1810                    )
1811                    .await?;
1812                Ok(ChatTarget::direct(resolved))
1813            }
1814            ChatTarget::Acp { agent, config } => {
1815                let _spec = catalog::resolve_spec(&agent, Some(&self.state), Some(worktree))?;
1816                Ok(ChatTarget::Acp { agent, config })
1817            }
1818        }
1819    }
1820
1821    async fn resolve_direct(
1822        &self,
1823        worktree: &Path,
1824        mut selection: DirectSelection,
1825        previous: Option<&DirectSelection>,
1826    ) -> Result<DirectSelection, String> {
1827        let backend = selection.backend.to_backend();
1828        let route = llm::route(
1829            &backend,
1830            Some(&self.state),
1831            Some(worktree),
1832            "for this Chat model",
1833        )
1834        .map_err(|failure| failure.message)?;
1835        if !matches!(route, llm::Route::Http(_)) {
1836            return Err(format!(
1837                "{} is not a direct HTTP provider for Chat.",
1838                selection.backend
1839            ));
1840        }
1841        let listing = llm::models::list(backend, Some(&self.state), Some(worktree)).await?;
1842        let model = listing
1843            .models
1844            .into_iter()
1845            .find(|model| model.slug == selection.model)
1846            .ok_or_else(|| {
1847                format!(
1848                    "{} does not list model {}.",
1849                    selection.backend, selection.model
1850                )
1851            })?;
1852        if let Some(effort) = &selection.effort {
1853            if !model.efforts.contains(effort) {
1854                let allowed = if model.efforts.is_empty() {
1855                    "none".to_owned()
1856                } else {
1857                    model.efforts.join(", ")
1858                };
1859                return Err(format!(
1860                    "{} model {} does not offer effort {effort:?}. Available efforts: {allowed}.",
1861                    selection.backend, selection.model
1862                ));
1863            }
1864        } else {
1865            selection.effort = previous
1866                .and_then(|previous| previous.effort.as_ref())
1867                .filter(|effort| model.efforts.contains(effort))
1868                .cloned()
1869                .or(model.default_effort);
1870        }
1871        Ok(selection)
1872    }
1873
1874    fn claim(&self, id: &SessionId) -> Result<Active, String> {
1875        let mut active = self.active.state.lock().expect("Chat active turns lock");
1876        if active.closed {
1877            return Err("Chat is closing.".into());
1878        }
1879        match active.turns.entry(id.clone()) {
1880            Slot::Occupied(_) => Err("This Chat session already has an active turn.".into()),
1881            Slot::Vacant(entry) => {
1882                let cancel = CancellationToken::new();
1883                entry.insert(ActiveEntry {
1884                    cancel: cancel.clone(),
1885                    owner_token: None,
1886                    worktree: None,
1887                });
1888                Ok(Active {
1889                    chat: self.clone(),
1890                    id: id.clone(),
1891                    cancel,
1892                })
1893            }
1894        }
1895    }
1896
1897    fn record_owner(&self, id: &SessionId, token: String, worktree: PathBuf) {
1898        if let Some(entry) = self
1899            .active
1900            .state
1901            .lock()
1902            .expect("Chat active turns lock")
1903            .turns
1904            .get_mut(id)
1905        {
1906            entry.owner_token = Some(token);
1907            entry.worktree = Some(worktree);
1908        }
1909    }
1910}
1911
1912fn default_config_selections(options: &[ConfigOption]) -> Vec<ConfigSelection> {
1913    options
1914        .iter()
1915        .filter(|opt| !opt.current_value.is_empty())
1916        .map(|opt| ConfigSelection {
1917            id: opt.id.clone(),
1918            value: opt.current_value.clone(),
1919            category: Some(opt.category),
1920        })
1921        .collect()
1922}
1923
1924fn previous_engine_label(
1925    previous_target: Option<&ChatTarget>,
1926    binding: Option<&AcpBinding>,
1927    legacy_migration_notice: bool,
1928    next_agent: &AgentId,
1929) -> Option<String> {
1930    if let Some(prev) = previous_target {
1931        match prev {
1932            ChatTarget::Acp { agent, .. } if agent == next_agent => {
1933                if legacy_migration_notice && binding.is_none() {
1934                    return Some("Legacy Antigravity".into());
1935                }
1936            }
1937            other => return Some(other.engine_label()),
1938        }
1939    }
1940    if let Some(binding) = binding
1941        && &binding.agent_id != next_agent
1942    {
1943        return Some(format!("ACP ({})", binding.agent_id));
1944    }
1945    None
1946}
1947
1948struct Prepared {
1949    session: Session,
1950    send: usize,
1951    engine: ChatEngine,
1952    acp_binding: Option<AcpBinding>,
1953    context: runs::Context,
1954    receipts: Receipts,
1955    owner: store::chat::Owner,
1956    recorder: Recorder,
1957    history: Vec<rig_core::message::Message>,
1958}
1959
1960struct Active {
1961    chat: Chat,
1962    id: SessionId,
1963    cancel: CancellationToken,
1964}
1965
1966impl Drop for Active {
1967    fn drop(&mut self) {
1968        self.chat
1969            .active
1970            .state
1971            .lock()
1972            .expect("Chat active turns lock")
1973            .turns
1974            .remove(&self.id);
1975        self.chat.active.settled.notify_waiters();
1976    }
1977}
1978
1979fn path(state: &Path, id: &SessionId) -> PathBuf {
1980    state.join("chat-sessions").join(format!("{id}.jsonl"))
1981}