Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
acp_thread: Share v2 session information (#65195)
Ben Brandt9df33dea42c3
diff --git a/Cargo.lock b/Cargo.lockindex 96910ded6e1..a52d074abdb 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -476,6 +476,7 @@ dependencies = ["buffer_diff","chrono","client",+ "clock","cloud_api_types","collections","command_palette_hooks",diff --git a/crates/acp_thread/src/acp_thread.rs b/crates/acp_thread/src/acp_thread.rsindex 593caf6f45c..4ae022157c9 100644--- a/crates/acp_thread/src/acp_thread.rs+++ b/crates/acp_thread/src/acp_thread.rs@@ -3361,10 +3361,8 @@ fn stop_reason_from_v1(reason: &acp_v1::StopReason) -> Option<acp_v2::StopReason}pub struct AcpThread {- session_id: acp_v1::SessionId,- work_dirs: Option<PathList>,+ session_info: AgentSessionInfo,parent_session_id: Option<acp_v1::SessionId>,- title: Option<SharedString>,provisional_title: Option<SharedString>,entries: Vec<AgentThreadEntry>,// Notices stay with the live session, but never enter conversation history or exports.@@ -3495,7 +3493,7 @@ impl From<&AcpThread> for ActionLogTelemetry {fn from(value: &AcpThread) -> Self {Self {agent_telemetry_id: value.connection().telemetry_id(),- session_id: value.session_id.0.clone(),+ session_id: value.session_id().0.clone(),}}}@@ -3691,7 +3689,14 @@ impl AcpThread {let receipt_submissions = connection.receipt_submissions(&session_id, cx);Self {parent_session_id,- work_dirs,+ session_info: AgentSessionInfo {+ session_id,+ work_dirs,+ title,+ updated_at: None,+ created_at: None,+ meta: None,+ },action_log,_git_store_subscription,update_last_checkpoint_if_changed_task: None,@@ -3703,7 +3708,6 @@ impl AcpThread {permission_requests: IndexMap::default(),plans: HashMap::default(),visible_plan: None,- title,provisional_title: None,project,running_turn: None,@@ -3711,7 +3715,6 @@ impl AcpThread {submissions: SessionSubmissions::new(receipt_submissions),activity: SessionActivity::default(),connection,- session_id,token_usage: None,cost: None,prompt_capabilities,@@ -3791,7 +3794,8 @@ impl AcpThread {}pub fn title(&self) -> Option<SharedString> {- self.title+ self.session_info+ .title.clone().or_else(|| self.provisional_title.clone())}@@ -3847,19 +3851,23 @@ impl AcpThread {}pub fn session_id(&self) -> &acp_v1::SessionId {- &self.session_id+ &self.session_info.session_id+ }++ pub fn session_info(&self) -> &AgentSessionInfo {+ &self.session_info}pub fn supports_truncate(&self, cx: &App) -> bool {- self.connection.truncate(&self.session_id, cx).is_some()+ self.connection.truncate(self.session_id(), cx).is_some()}pub fn work_dirs(&self) -> Option<&PathList> {- self.work_dirs.as_ref()+ self.session_info.work_dirs.as_ref()}pub fn set_work_dirs(&mut self, work_dirs: PathList, cx: &mut Context<Self>) {- self.work_dirs = Some(work_dirs);+ self.session_info.work_dirs = Some(work_dirs);cx.emit(AcpThreadEvent::WorkingDirectoriesUpdated)}@@ -4284,16 +4292,7 @@ impl AcpThread {cx.notify();}acp_v1::SessionUpdate::SessionInfoUpdate(info_update) => {- if let MaybeUndefined::Value(title) = info_update.title {- let had_provisional = self.provisional_title.take().is_some();- let title: SharedString = title.into();- if self.title.as_ref() != Some(&title) {- self.title = Some(title);- cx.emit(AcpThreadEvent::TitleUpdated);- } else if had_provisional {- cx.emit(AcpThreadEvent::TitleUpdated);- }- }+ self.update_session_info(session_info_update_from_v1(info_update), cx);}acp_v1::SessionUpdate::AvailableCommandsUpdate(acp_v1::AvailableCommandsUpdate {available_commands,@@ -5107,16 +5106,33 @@ impl AcpThread {cx.emit(AcpThreadEvent::EntryUpdated(ix));}+ pub fn update_session_info(+ &mut self,+ update: acp_v2::SessionInfoUpdate,+ cx: &mut Context<Self>,+ ) {+ let previous_title = self.session_info.title.clone();+ let had_provisional =+ !update.title.is_undefined() && self.provisional_title.take().is_some();+ let changed = self.session_info.apply_update(update);+ if self.session_info.title != previous_title || had_provisional {+ cx.emit(AcpThreadEvent::TitleUpdated);+ }+ if changed || had_provisional {+ cx.notify();+ }+ }+pub fn can_set_title(&mut self, cx: &mut Context<Self>) -> bool {- self.connection.set_title(&self.session_id, cx).is_some()+ self.connection.set_title(self.session_id(), cx).is_some()}pub fn set_title(&mut self, title: SharedString, cx: &mut Context<Self>) -> Task<Result<()>> {let had_provisional = self.provisional_title.take().is_some();- if self.title.as_ref() != Some(&title) {- self.title = Some(title.clone());+ if self.session_info.title.as_ref() != Some(&title) {+ self.session_info.title = Some(title.clone());cx.emit(AcpThreadEvent::TitleUpdated);- if let Some(set_title) = self.connection.set_title(&self.session_id, cx) {+ if let Some(set_title) = self.connection.set_title(self.session_id(), cx) {return set_title.run(title, cx);}} else if had_provisional {@@ -5543,7 +5559,7 @@ impl AcpThread {cx: &mut Context<Self>,) -> Result<(PermissionRequestId, Task<acp_v2::RequestPermissionOutcome>)> {anyhow::ensure!(- acp_v1::SessionId::new(request.session_id.0.clone()) == self.session_id,+ acp_v1::SessionId::new(request.session_id.0.clone()) == self.session_info.session_id,"Permission request belongs to a different session");anyhow::ensure!(@@ -6073,8 +6089,10 @@ impl AcpThread {push_user_message: bool,cx: &mut Context<Self>,) -> Submission {- let request =- acp_v2::PromptRequest::new(acp_v2::SessionId::new(self.session_id.0.clone()), message);+ let request = acp_v2::PromptRequest::new(+ acp_v2::SessionId::new(self.session_id().0.clone()),+ message,+ );if let Err(error) = self.validate_prompt_content(&request.prompt) {return self.track_submission(id, cx, async move |_, _| Err(error));}@@ -6138,7 +6156,7 @@ impl AcpThread {pub fn can_retry(&self, cx: &App) -> bool {!self.uses_reported_activity()- && self.connection.retry(&self.session_id, cx).is_some()+ && self.connection.retry(self.session_id(), cx).is_some()&& self.submissions.latest_id()@@ -6165,7 +6183,7 @@ impl AcpThread {self.run_turn(id, cx, async move |this, cx| {this.update(cx, |this, cx| {this.connection- .retry(&this.session_id, cx)+ .retry(this.session_id(), cx).map(|retry| retry.run(cx))})?.context("retrying a session is not supported")?@@ -6396,7 +6414,7 @@ impl AcpThread {let Some(receiver) = self.activity.wait_for_idle() else {return Task::ready(());};- self.connection.cancel(&self.session_id, cx);+ self.connection.cancel(self.session_id(), cx);return cx.spawn(async move |_, _| {if receiver.await.is_err() {log::debug!("Session released before foreground cancellation completed");@@ -6414,7 +6432,7 @@ impl AcpThread {};self.shrink_message_source_capacity(turn.first_entry_index);self.mark_pending_entries_as_canceled(permission_outcome, cx);- self.connection.cancel(&self.session_id, cx);+ self.connection.cancel(self.session_id(), cx);self.set_foreground_state(acp_v2::StateUpdate::Idle(acp_v2::IdleStateUpdate::new()),cx,@@ -6551,7 +6569,7 @@ impl AcpThread {client_id: ClientUserMessageId,cx: &mut Context<Self>,) -> Task<Result<()>> {- let Some(truncate) = self.connection.truncate(&self.session_id, cx) else {+ let Some(truncate) = self.connection.truncate(self.session_id(), cx) else {return Task::ready(Err(anyhow!("not supported")));};@@ -18290,6 +18308,123 @@ mod tests {2,"session info title update should emit TitleUpdated");++ cx.run_until_parked();+ let observer_notifications = Rc::new(RefCell::new(0));+ let _observer = thread.update(cx, |_, cx| {+ cx.observe_self({+ let observer_notifications = observer_notifications.clone();+ move |_, _| *observer_notifications.borrow_mut() += 1+ })+ });+ thread.update(cx, |thread, cx| {+ thread.update_session_info(+ acp_v2::SessionInfoUpdate::new().updated_at("2026-03-04T05:06:07+02:30"),+ cx,+ );+ assert_eq!(thread.title(), Some("Helping with Rust question".into()));+ assert!(thread.session_info().updated_at.is_some());+ assert_eq!(thread.session_info().meta, None);+ });+ cx.run_until_parked();+ assert_eq!(*observer_notifications.borrow(), 1);+ assert_eq!(*title_updated_events.borrow(), 2);++ thread.update(cx, |thread, cx| {+ thread.update_session_info(+ acp_v2::SessionInfoUpdate::new().meta(acp_v2::Meta::from_iter([(+ "session".into(),+ serde_json::json!({"value": []}),+ )])),+ cx,+ );+ assert_eq!(thread.title(), Some("Helping with Rust question".into()));+ assert_eq!(+ thread.session_info().meta,+ Some(acp_v2::Meta::from_iter([(+ "session".into(),+ serde_json::json!({"value": []}),+ )]))+ );+ });+ cx.run_until_parked();+ assert_eq!(*observer_notifications.borrow(), 2);+ assert_eq!(*title_updated_events.borrow(), 2);++ thread.update(cx, |thread, cx| {+ thread.set_provisional_title("Hidden provisional title".into(), cx);+ thread.update_session_info(+ acp_v2::SessionInfoUpdate::new().title("Helping with Rust question"),+ cx,+ );+ assert!(!thread.has_provisional_title());+ });+ assert_eq!(*title_updated_events.borrow(), 4);++ thread.update(cx, |thread, cx| {+ thread.update_session_info(acp_v2::SessionInfoUpdate::new().title(None::<String>), cx);+ assert_eq!(thread.title(), None);+ assert_eq!(thread.session_info().title, None);+ assert!(thread.session_info().updated_at.is_some());+ assert!(thread.session_info().meta.is_some());+ });+ assert_eq!(*title_updated_events.borrow(), 5);++ thread.update(cx, |thread, cx| {+ thread.update_session_info(+ acp_v2::SessionInfoUpdate::new()+ .title(None::<String>)+ .updated_at(None::<String>)+ .meta(None::<acp_v2::Meta>),+ cx,+ );+ assert_eq!(thread.session_info().updated_at, None);+ assert_eq!(thread.session_info().meta, None);+ });+ assert_eq!(*title_updated_events.borrow(), 5);++ thread.update(cx, |thread, cx| {+ thread.set_provisional_title("Visible provisional title".into(), cx);+ thread.update_session_info(acp_v2::SessionInfoUpdate::new(), cx);+ assert_eq!(thread.title(), Some("Visible provisional title".into()));+ thread.update_session_info(acp_v2::SessionInfoUpdate::new().title(None::<String>), cx);+ assert_eq!(thread.title(), None);+ assert!(!thread.has_provisional_title());+ });+ assert_eq!(*title_updated_events.borrow(), 7);++ thread.update(cx, |thread, cx| {+ thread+ .handle_session_update(+ acp_v1::SessionUpdate::SessionInfoUpdate(+ acp_v1::SessionInfoUpdate::new()+ .title("Legacy title")+ .meta(acp_v1::Meta::new()),+ ),+ cx,+ )+ .expect("legacy title patch");+ thread+ .handle_session_update(+ acp_v1::SessionUpdate::SessionInfoUpdate(acp_v1::SessionInfoUpdate::new()),+ cx,+ )+ .expect("omitted legacy patch");+ assert_eq!(thread.title(), Some("Legacy title".into()));+ assert_eq!(thread.session_info().meta, Some(acp_v2::Meta::new()));+ thread+ .handle_session_update(+ acp_v1::SessionUpdate::SessionInfoUpdate(+ acp_v1::SessionInfoUpdate::new().title(None::<String>),+ ),+ cx,+ )+ .expect("legacy title clear");+ assert_eq!(thread.title(), None);+ assert_eq!(thread.session_info().meta, Some(acp_v2::Meta::new()));+ });+ assert_eq!(*title_updated_events.borrow(), 9);+assert!(connection.set_title_calls.borrow().is_empty(),"session info title update should not propagate back to the connection"diff --git a/crates/acp_thread/src/connection.rs b/crates/acp_thread/src/connection.rsindex 39d648982de..be204b5d3c5 100644--- a/crates/acp_thread/src/connection.rs+++ b/crates/acp_thread/src/connection.rs@@ -1,5 +1,5 @@use crate::{AcpThread, ElicitationStore};-use agent_client_protocol::schema::{v1 as acp_v1, v2 as acp_v2};+use agent_client_protocol::schema::{MaybeUndefined, v1 as acp_v1, v2 as acp_v2};use anyhow::Result;use chrono::{DateTime, Utc};use collections::{HashMap, HashSet, IndexMap};@@ -395,7 +395,7 @@ pub struct AgentSessionInfo {pub title: Option<SharedString>,pub updated_at: Option<DateTime<Utc>>,pub created_at: Option<DateTime<Utc>>,- pub meta: Option<acp_v1::Meta>,+ pub meta: Option<acp_v2::Meta>,}impl AgentSessionInfo {@@ -409,6 +409,48 @@ impl AgentSessionInfo {meta: None,}}++ pub fn apply_update(&mut self, update: acp_v2::SessionInfoUpdate) -> bool {+ let mut changed = false;+ if !update.title.is_undefined() {+ let title = update.title.take().map(SharedString::from);+ changed |= self.title != title;+ self.title = title;+ }++ let updated_at = match update.updated_at {+ MaybeUndefined::Undefined => None,+ MaybeUndefined::Null => Some(None),+ MaybeUndefined::Value(updated_at) => match DateTime::parse_from_rfc3339(&updated_at) {+ Ok(updated_at) => Some(Some(updated_at.with_timezone(&Utc))),+ Err(_) => {+ log::warn!("Ignoring invalid session information timestamp");+ None+ }+ },+ };+ if let Some(updated_at) = updated_at {+ changed |= self.updated_at != updated_at;+ self.updated_at = updated_at;+ }++ if !update.meta.is_undefined() {+ let meta = update.meta.take();+ changed |= self.meta != meta;+ self.meta = meta;+ }+ changed+ }+}++pub fn session_info_update_from_v1(update: acp_v1::SessionInfoUpdate) -> acp_v2::SessionInfoUpdate {+ let mut converted = acp_v2::SessionInfoUpdate::new()+ .title(update.title)+ .updated_at(update.updated_at);+ if let Some(meta) = update.meta {+ converted = converted.meta(meta);+ }+ converted}#[derive(Debug, Clone)]@@ -416,7 +458,7 @@ pub enum SessionListUpdate {Refresh,SessionInfo {session_id: acp_v1::SessionId,- update: acp_v1::SessionInfoUpdate,+ update: acp_v2::SessionInfoUpdate,},}@@ -818,6 +860,7 @@ mod test_support {Arc<Mutex<Option<oneshot::Receiver<Result<acp_v2::PromptResponse>>>>>,receipt_prompt: Arc<Mutex<Option<Vec<acp_v2::ContentBlock>>>>,next_truncate: Arc<Mutex<Option<oneshot::Receiver<()>>>>,+ set_title_calls: Arc<Mutex<Vec<(acp_v1::SessionId, SharedString)>>>,supports_receipt_submissions: bool,supports_retry: bool,supports_load_session: bool,@@ -846,6 +889,7 @@ mod test_support {next_receipt_response: Default::default(),receipt_prompt: Default::default(),next_truncate: Default::default(),+ set_title_calls: Default::default(),permission_requests: HashMap::default(),sessions: Arc::default(),supports_receipt_submissions: false,@@ -887,6 +931,10 @@ mod test_support {self.receipt_prompt.lock().take()}+ pub fn take_set_title_calls(&self) -> Vec<(acp_v1::SessionId, SharedString)> {+ std::mem::take(&mut *self.set_title_calls.lock())+ }+pub fn defer_next_truncate(&self) -> oneshot::Sender<()> {let (sender, receiver) = oneshot::channel();assert!(self.next_truncate.lock().replace(receiver).is_none());@@ -1190,11 +1238,15 @@ mod test_support {fn set_title(&self,- _session_id: &acp_v1::SessionId,+ session_id: &acp_v1::SessionId,_cx: &App,) -> Option<Rc<dyn AgentSessionSetTitle>> {- self.supports_set_title- .then(|| Rc::new(StubAgentSessionSetTitle) as _)+ self.supports_set_title.then(|| {+ Rc::new(StubAgentSessionSetTitle {+ session_id: session_id.clone(),+ calls: self.set_title_calls.clone(),+ }) as _+ })}fn truncate(@@ -1213,10 +1265,14 @@ mod test_support {}}- struct StubAgentSessionSetTitle;+ struct StubAgentSessionSetTitle {+ session_id: acp_v1::SessionId,+ calls: Arc<Mutex<Vec<(acp_v1::SessionId, SharedString)>>>,+ }impl AgentSessionSetTitle for StubAgentSessionSetTitle {- fn run(&self, _title: SharedString, _cx: &mut App) -> Task<Result<()>> {+ fn run(&self, title: SharedString, _cx: &mut App) -> Task<Result<()>> {+ self.calls.lock().push((self.session_id.clone(), title));Task::ready(Ok(()))}}@@ -1333,3 +1389,122 @@ mod test_support {#[cfg(any(test, feature = "test-support"))]pub use test_support::*;++#[cfg(test)]+mod tests {+ use super::*;+ use serde_json::json;++ #[test]+ fn session_info_patches_preserve_legacy_fields_and_apply_tristate_updates() {+ let timestamp = "2026-03-04T05:06:07+02:30";+ let updated_at = DateTime::parse_from_rfc3339(timestamp)+ .expect("valid timestamp")+ .with_timezone(&Utc);+ let original_meta = acp_v2::Meta::from_iter([(+ "original".into(),+ json!({"nested": [1, {"value": "retained"}]}),+ )]);+ let original = AgentSessionInfo {+ session_id: acp_v1::SessionId::new("opaque/session"),+ work_dirs: Some(PathList::new(&[std::path::Path::new("/workspace")])),+ title: Some("Original title".into()),+ updated_at: Some(updated_at),+ created_at: Some(updated_at),+ meta: Some(original_meta),+ };++ for (wire, title, expected_updated_at, meta, changed) in [+ (+ json!({}),+ original.title.clone(),+ original.updated_at,+ original.meta.clone(),+ false,+ ),+ (+ json!({"title": null, "updatedAt": null}),+ None,+ None,+ original.meta.clone(),+ true,+ ),+ (+ json!({"title": "", "updatedAt": timestamp, "_meta": {}}),+ Some("".into()),+ Some(updated_at),+ Some(acp_v2::Meta::new()),+ true,+ ),+ (+ json!({"_meta": {"replacement": {"value": []}}}),+ original.title.clone(),+ original.updated_at,+ Some(acp_v2::Meta::from_iter([(+ "replacement".into(),+ json!({"value": []}),+ )])),+ true,+ ),+ (+ json!({"_meta": null}),+ original.title.clone(),+ original.updated_at,+ original.meta.clone(),+ false,+ ),+ ] {+ let legacy: acp_v1::SessionInfoUpdate =+ serde_json::from_value(wire).expect("legacy patch");+ let converted = session_info_update_from_v1(legacy.clone());+ assert_eq!(+ serde_json::to_value(&converted).expect("shared patch wire"),+ serde_json::to_value(&legacy).expect("normalized legacy patch wire")+ );++ let mut info = original.clone();+ assert_eq!(info.apply_update(converted.clone()), changed);+ assert_eq!(+ info,+ AgentSessionInfo {+ title,+ updated_at: expected_updated_at,+ meta,+ ..original.clone()+ }+ );+ assert!(!info.apply_update(converted), "identical patch is a no-op");+ }++ let mut info = original.clone();+ assert!(info.apply_update(acp_v2::SessionInfoUpdate::new().meta(None::<acp_v2::Meta>)));+ assert_eq!(+ info,+ AgentSessionInfo {+ meta: None,+ ..original.clone()+ }+ );+ assert!(info.apply_update(acp_v2::SessionInfoUpdate::new().meta(acp_v2::Meta::new())));+ assert_eq!(info.meta, Some(acp_v2::Meta::new()));++ let mut info = original.clone();+ assert!(+ info.apply_update(+ acp_v2::SessionInfoUpdate::new()+ .title("New title")+ .updated_at("invalid private timestamp")+ )+ );+ assert_eq!(+ info,+ AgentSessionInfo {+ title: Some("New title".into()),+ ..original+ }+ );+ assert!(!info.apply_update(+ acp_v2::SessionInfoUpdate::new().updated_at("invalid private timestamp")+ ));+ }+}diff --git a/crates/agent_servers/src/acp.rs b/crates/agent_servers/src/acp.rsindex ed3870bde8f..7eca700a1bc 100644--- a/crates/agent_servers/src/acp.rs+++ b/crates/agent_servers/src/acp.rs@@ -427,7 +427,10 @@ impl AcpSessionList {fn send_info_update(&self, session_id: acp::SessionId, update: acp::SessionInfoUpdate) {self.updates_tx- .try_send(acp_thread::SessionListUpdate::SessionInfo { session_id, update })+ .try_send(acp_thread::SessionListUpdate::SessionInfo {+ session_id,+ update: acp_thread::session_info_update_from_v1(update),+ }).log_err();}}diff --git a/crates/agent_ui/Cargo.toml b/crates/agent_ui/Cargo.tomlindex 3c22a95cadf..2ff94340087 100644--- a/crates/agent_ui/Cargo.toml+++ b/crates/agent_ui/Cargo.toml@@ -42,6 +42,7 @@ base64.workspace = truebuffer_diff.workspace = truechrono.workspace = trueclient.workspace = true+clock.workspace = truecloud_api_types.workspace = truecollections.workspace = truecommand_palette_hooks.workspace = truediff --git a/crates/agent_ui/src/conversation_view.rs b/crates/agent_ui/src/conversation_view.rsindex 33efb1db20d..090d449128e 100644--- a/crates/agent_ui/src/conversation_view.rs+++ b/crates/agent_ui/src/conversation_view.rs@@ -2058,15 +2058,13 @@ impl ConversationView {);}AcpThreadEvent::TitleUpdated => {- let title = self.title_override(cx).or_else(|| thread.read(cx).title());- if let Some(title) = title- && let Some(active_thread) = self.thread_view(&session_id)- {- let title_editor = active_thread.read(cx).title_editor.clone();- title_editor.update(cx, |editor, cx| {- if editor.text(cx) != title {- editor.set_text(title, window, cx);- }+ let title = self+ .title_override(cx)+ .or_else(|| thread.read(cx).title())+ .unwrap_or_else(|| DEFAULT_THREAD_TITLE.into());+ if let Some(active_thread) = self.thread_view(&session_id) {+ active_thread.update(cx, |active_thread, cx| {+ active_thread.sync_title_editor(title, window, cx);});}cx.notify();@@ -5678,8 +5676,11 @@ pub(crate) mod tests {});}- #[derive(Clone)]- struct RestoredAvailableCommandsConnection;+ #[derive(Clone, Default)]+ struct RestoredAvailableCommandsConnection {+ session_info_update: Option<acp_v1::SessionInfoUpdate>,+ load_response: Arc<Mutex<Option<futures::channel::oneshot::Receiver<()>>>>,+ }impl AgentConnection for RestoredAvailableCommandsConnection {fn agent_id(&self) -> AgentId {@@ -5715,9 +5716,11 @@ pub(crate) mod tests {session_id: acp_v1::SessionId,project: Entity<Project>,_work_dirs: PathList,- _title: Option<SharedString>,+ title: Option<SharedString>,cx: &mut App,) -> Task<gpui::Result<Entity<AcpThread>>> {+ let session_info_update = self.session_info_update.clone();+ let load_response = self.load_response.lock().take();let thread = build_test_thread(self,project,@@ -5739,7 +5742,28 @@ pub(crate) mod tests {}).expect("available commands update should succeed");- Task::ready(Ok(thread))+ thread.update(cx, |thread, cx| {+ if let Some(title) = title {+ thread.update_session_info(+ acp_v2::SessionInfoUpdate::new().title(title.to_string()),+ cx,+ );+ }+ if let Some(update) = session_info_update {+ thread+ .handle_session_update(acp_v1::SessionUpdate::SessionInfoUpdate(update), cx)+ .expect("session info update should succeed");+ }+ });++ if let Some(load_response) = load_response {+ cx.spawn(async move |_| {+ load_response.await?;+ Ok(thread)+ })+ } else {+ Task::ready(Ok(thread))+ }}fn auth_methods(&self) -> &[acp_v1::AuthMethod] {@@ -5786,7 +5810,9 @@ pub(crate) mod tests {let conversation_view = cx.update(|window, cx| {cx.new(|cx| {ConversationView::new(- Rc::new(StubAgentServer::new(RestoredAvailableCommandsConnection)),+ Rc::new(StubAgentServer::new(+ RestoredAvailableCommandsConnection::default(),+ )),connection_store,Agent::Custom { id: "Test".into() },Some(acp_v1::SessionId::new("restored-session")),@@ -5910,6 +5936,124 @@ pub(crate) mod tests {);}+ #[gpui::test]+ async fn test_restored_title_uses_updates_received_before_load_completes(+ cx: &mut TestAppContext,+ ) {+ use crate::thread_metadata_store::ThreadMetadata;+ use chrono::Utc;+ use project::WorktreePaths;++ init_test(cx);+ for (index, (title, title_override)) in [+ (None, None),+ (Some("Current agent title"), None),+ (None, Some("User title")),+ ]+ .into_iter()+ .enumerate()+ {+ let fs = FakeFs::new(cx.executor());+ let project = Project::test(fs, [], cx).await;+ let (multi_workspace, cx) = cx.add_window_view(|window, cx| {+ MultiWorkspace::test_new(project.clone(), window, cx)+ });+ let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());+ let thread_id = ThreadId::new();+ let session_id = acp_v1::SessionId::new(format!("early-title-{index}"));+ cx.update(|_, cx| {+ ThreadMetadataStore::global(cx).update(cx, |store, cx| {+ store.save(+ ThreadMetadata {+ thread_id,+ session_id: Some(session_id.clone()),+ agent_id: AgentId::new("Test"),+ title: Some("Old cached title".into()),+ title_override: title_override.map(SharedString::from),+ updated_at: Utc::now(),+ created_at: Some(Utc::now()),+ interacted_at: None,+ worktree_paths: WorktreePaths::from_folder_paths(&PathList::default()),+ remote_connection: None,+ archived: false,+ },+ cx,+ );+ });+ });++ let (finish_load, load_response) = futures::channel::oneshot::channel();+ let load_response = Arc::new(Mutex::new(Some(load_response)));+ let connection = RestoredAvailableCommandsConnection {+ session_info_update: Some(+ acp_v1::SessionInfoUpdate::new().title(title.map(str::to_owned)),+ ),+ load_response: load_response.clone(),+ };+ let thread_store = cx.update(|_, cx| cx.new(|cx| ThreadStore::new(cx)));+ let connection_store =+ cx.update(|_, cx| cx.new(|cx| AgentConnectionStore::new(project.clone(), cx)));+ let conversation_view = cx.update(|window, cx| {+ cx.new(|cx| {+ ConversationView::new(+ Rc::new(StubAgentServer::new(connection)),+ connection_store,+ Agent::Custom { id: "Test".into() },+ Some(session_id),+ Some(thread_id),+ None,+ Some("Old cached title".into()),+ None,+ workspace.downgrade(),+ project,+ Some(thread_store),+ AgentThreadSource::AgentPanel,+ window,+ cx,+ )+ })+ });+ add_to_workspace(conversation_view.clone(), cx);+ cx.run_until_parked();+ assert!(+ load_response.lock().is_none(),+ "load operation should have started"+ );+ conversation_view.read_with(cx, |view, _| {+ assert!(view.is_loading());+ assert!(view.root_thread_view().is_none());+ });+ cx.read(|cx| {+ assert_eq!(+ ThreadMetadataStore::global(cx)+ .read(cx)+ .entry(thread_id)+ .expect("cached metadata")+ .title+ .as_deref(),+ Some("Old cached title")+ );+ });++ finish_load.send(()).expect("load should still be pending");+ cx.run_until_parked();+ let active = active_thread(&conversation_view, cx);+ active.read_with(cx, |view, cx| {+ assert_eq!(view.thread.read(cx).title().as_deref(), title);+ assert_eq!(+ view.title_editor.read(cx).text(cx),+ title_override.or(title).unwrap_or(DEFAULT_THREAD_TITLE)+ );+ });+ cx.read(|cx| {+ let store = ThreadMetadataStore::global(cx);+ let metadata = store.read(cx).entry(thread_id).expect("live metadata");+ assert_eq!(metadata.title.as_deref(), title);+ assert_eq!(metadata.title_override.as_deref(), title_override);+ });+ }+ }+#[gpui::test]async fn test_resume_thread_uses_session_cwd_when_inside_project(cx: &mut TestAppContext) {init_test(cx);@@ -6866,7 +7010,9 @@ pub(crate) mod tests {panel.update_in(cx, |panel, window, cx| {panel.open_external_thread_with_server(- Rc::new(StubAgentServer::new(RestoredAvailableCommandsConnection)),+ Rc::new(StubAgentServer::new(+ RestoredAvailableCommandsConnection::default(),+ )),window,cx,);@@ -6889,7 +7035,9 @@ pub(crate) mod tests {let conversation_view = cx.update(|window, cx| {cx.new(|cx| {ConversationView::new(- Rc::new(StubAgentServer::new(RestoredAvailableCommandsConnection)),+ Rc::new(StubAgentServer::new(+ RestoredAvailableCommandsConnection::default(),+ )),connection_store,Agent::Custom { id: "Test".into() },None,@@ -14104,15 +14252,113 @@ pub(crate) mod tests {#[gpui::test]async fn test_manually_editing_title_updates_acp_thread_title(cx: &mut TestAppContext) {+ use agent_client_protocol::schema::MaybeUndefined;+init_test(cx);+ let connection = StubAgentConnection::new();let (conversation_view, cx) =- setup_conversation_view(StubAgentServer::default_response(), cx).await;+ setup_conversation_view(StubAgentServer::new(connection.clone()), cx).await;add_to_workspace(conversation_view.clone(), cx);let active = active_thread(&conversation_view, cx);let title_editor = cx.read(|cx| active.read(cx).title_editor.clone());let thread = cx.read(|cx| active.read(cx).thread.clone());+ let session_id = thread.read_with(cx, |thread, _| thread.session_id().clone());++ let thread_id = conversation_view.read_with(cx, |view, _cx| view.thread_id);+ let assert_title =+ |title: Option<&str>, title_override: Option<&str>, cx: &VisualTestContext| {+ let display_title = title_override.or(title).unwrap_or(DEFAULT_THREAD_TITLE);+ title_editor.read_with(cx, |editor, cx| {+ assert_eq!(editor.text(cx), display_title);+ });+ thread.read_with(cx, |thread, _cx| {+ assert_eq!(thread.title().as_deref(), title);+ });+ cx.read(|cx| {+ let store = ThreadMetadataStore::global(cx);+ let metadata = store+ .read(cx)+ .entry(thread_id)+ .expect("RootThreadUpdated should save the thread metadata");+ assert_eq!(metadata.title.as_deref(), title);+ assert_eq!(metadata.title_override.as_deref(), title_override);+ assert_eq!(metadata.display_title().as_ref(), display_title);+ let session_info = acp_thread::AgentSessionInfo::from(metadata);+ assert_eq!(session_info.title.as_deref(), title_override.or(title));+ });+ };++ cx.focus(&title_editor);+ for title in [Some("Agent Title"), Some("Replacement Title"), None] {+ thread.update(cx, |thread, cx| {+ let title = title+ .map(|title| MaybeUndefined::Value(title.into()))+ .unwrap_or(MaybeUndefined::Null);+ thread.update_session_info(acp_v2::SessionInfoUpdate::new().title(title), cx);+ });+ cx.run_until_parked();+ assert_title(title, None, cx);+ assert!(connection.take_set_title_calls().is_empty());+ }++ cx.dispatch_action(editor::actions::DeleteLine);+ cx.run_until_parked();+ cx.write_to_clipboard(ClipboardItem::new_string(DEFAULT_THREAD_TITLE.into()));+ cx.dispatch_action(Paste);+ cx.run_until_parked();+ assert_title(Some(DEFAULT_THREAD_TITLE), Some(DEFAULT_THREAD_TITLE), cx);+ assert_eq!(+ connection.take_set_title_calls(),+ vec![(session_id.clone(), DEFAULT_THREAD_TITLE.into())]+ );+ for title in [Some("Agent replacement after chosen default"), None] {+ thread.update(cx, |thread, cx| {+ let title = title+ .map(|title| MaybeUndefined::Value(title.into()))+ .unwrap_or(MaybeUndefined::Null);+ thread.update_session_info(acp_v2::SessionInfoUpdate::new().title(title), cx);+ });+ cx.run_until_parked();+ assert_title(title, Some(DEFAULT_THREAD_TITLE), cx);+ assert!(connection.take_set_title_calls().is_empty());+ }++ cx.update(|_, cx| {+ ThreadMetadataStore::global(cx).update(cx, |store, cx| {+ let mut metadata = store.entry(thread_id).expect("thread metadata").clone();+ metadata.title_override = None;+ store.save(metadata, cx);+ });+ });+ thread.update(cx, |thread, cx| {+ thread.update_session_info(+ acp_v2::SessionInfoUpdate::new().title("Agent title to keep"),+ cx,+ );+ });+ cx.run_until_parked();+ assert_title(Some("Agent title to keep"), None, cx);+ assert!(connection.take_set_title_calls().is_empty());+ cx.dispatch_action(editor::actions::DeleteLine);+ cx.run_until_parked();+ cx.write_to_clipboard(ClipboardItem::new_string("Agent title to keep".into()));+ cx.dispatch_action(Paste);+ cx.run_until_parked();+ assert_title(Some("Agent title to keep"), Some("Agent title to keep"), cx);+ assert!(connection.take_set_title_calls().is_empty());+ for title in [Some("Agent replacement after explicit choice"), None] {+ thread.update(cx, |thread, cx| {+ let title = title+ .map(|title| MaybeUndefined::Value(title.into()))+ .unwrap_or(MaybeUndefined::Null);+ thread.update_session_info(acp_v2::SessionInfoUpdate::new().title(title), cx);+ });+ cx.run_until_parked();+ assert_title(title, Some("Agent title to keep"), cx);+ assert!(connection.take_set_title_calls().is_empty());+ }title_editor.read_with(cx, |editor, cx| {assert!(!editor.read_only(cx));@@ -14132,6 +14378,28 @@ pub(crate) mod tests {thread.read_with(cx, |thread, _cx| {assert_eq!(thread.title(), Some("My Custom Title".into()));});+ assert_title(Some("My Custom Title"), Some("My Custom Title"), cx);+ let title_calls = connection.take_set_title_calls();+ assert_eq!(+ title_calls.last(),+ Some(&(session_id.clone(), "My Custom Title".into()))+ );+ assert!(title_calls.iter().all(|(id, title)| {+ id == &session_id && "My Custom Title".starts_with(title.as_ref())+ }));++ cx.focus(&conversation_view);+ for title in [Some("Subsequent Agent Title"), None] {+ thread.update(cx, |thread, cx| {+ let title = title+ .map(|title| MaybeUndefined::Value(title.into()))+ .unwrap_or(MaybeUndefined::Null);+ thread.update_session_info(acp_v2::SessionInfoUpdate::new().title(title), cx);+ });+ cx.run_until_parked();+ assert_title(title, Some("My Custom Title"), cx);+ assert!(connection.take_set_title_calls().is_empty());+ }}#[gpui::test]diff --git a/crates/agent_ui/src/conversation_view/thread_view.rs b/crates/agent_ui/src/conversation_view/thread_view.rsindex 63033df5bef..143e7f37233 100644--- a/crates/agent_ui/src/conversation_view/thread_view.rs+++ b/crates/agent_ui/src/conversation_view/thread_view.rs@@ -579,6 +579,7 @@ pub struct ThreadView {pub workspace: WeakEntity<Workspace>,pub entry_view_state: Entity<EntryViewState>,pub title_editor: Entity<Editor>,+ title_editor_sync_version: Option<(gpui::EntityId, clock::Global)>,pub config_options_view: Option<Entity<ConfigOptionsView>>,pub mode_selector: Option<Entity<ModeSelector>>,pub model_selector: Option<Entity<ModelSelectorPopover>>,@@ -888,22 +889,26 @@ impl ThreadView {}));}- let title_editor = {+ let (title_editor, title_editor_sync_version) = {let metadata = ThreadMetadataStore::try_global(cx).and_then(|store| store.read(cx).entry(root_thread_id).cloned());let initial_title = if parent_session_id.is_none() {- metadata.as_ref().and_then(|m| m.title())+ metadata+ .as_ref()+ .and_then(|metadata| metadata.title_override.clone())} else {- thread.read(cx).title()+ None}+ .or_else(|| thread.read(cx).title()).unwrap_or_else(|| DEFAULT_THREAD_TITLE.into());let editor = cx.new(|cx| {let mut editor = Editor::single_line(window, cx);editor.set_text(initial_title, window, cx);editor});+ let version = Self::title_editor_version(editor.read(cx), cx);subscriptions.push(cx.subscribe_in(&editor, window, Self::handle_title_editor_event));- editor+ (editor, version)};subscriptions.push(cx.subscribe_in(@@ -1015,6 +1020,7 @@ impl ThreadView {workspace,entry_view_state,title_editor,+ title_editor_sync_version,config_options_view,mode_selector,model_selector,@@ -2821,6 +2827,29 @@ impl ThreadView {cx.notify();}+ fn title_editor_version(editor: &Editor, cx: &App) -> Option<(gpui::EntityId, clock::Global)> {+ editor+ .buffer()+ .read(cx)+ .as_singleton()+ .map(|buffer| (buffer.entity_id(), buffer.read(cx).version()))+ }++ pub(super) fn sync_title_editor(+ &mut self,+ title: SharedString,+ window: &mut Window,+ cx: &mut Context<Self>,+ ) {+ if self.title_editor.read(cx).text(cx) == title {+ return;+ }+ self.title_editor_sync_version = self.title_editor.update(cx, |editor, cx| {+ editor.set_text(title, window, cx);+ Self::title_editor_version(editor, cx)+ });+ }+pub fn handle_title_editor_event(&mut self,title_editor: &Entity<Editor>,@@ -2830,13 +2859,15 @@ impl ThreadView {) {match event {EditorEvent::BufferEdited => {- // We only want to set the title if the user has actively edited- // it. If the title editor is not focused, we programmatically- // changed the text, so we don't want to set the title again.if !title_editor.read(cx).is_focused(window) {return;}+ // BufferEdited has no origin; equal text can still be an explicit user rename.+ let version = Self::title_editor_version(title_editor.read(cx), cx);+ if version.is_some() && version == self.title_editor_sync_version {+ return;+ }let new_title = title_editor.read(cx).text(cx);if new_title.is_empty() {return;@@ -2845,9 +2876,7 @@ impl ThreadView {}EditorEvent::Blurred => {if title_editor.read(cx).text(cx).is_empty() {- title_editor.update(cx, |editor, cx| {- editor.set_text(DEFAULT_THREAD_TITLE, window, cx);- });+ self.sync_title_editor(DEFAULT_THREAD_TITLE.into(), window, cx);}}_ => {}@@ -2859,11 +2888,7 @@ impl ThreadView {/// inline rename) so that they go through the same persistence path as/// the in-thread title editor.pub fn rename(&mut self, title: SharedString, window: &mut Window, cx: &mut Context<Self>) {- if self.title_editor.read(cx).text(cx) != title.as_ref() {- self.title_editor.update(cx, |editor, cx| {- editor.set_text(title.clone(), window, cx);- });- }+ self.sync_title_editor(title.clone(), window, cx);self.apply_renamed_title(title, cx);}