Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
agent: Prepare shared receipt lifecycle support (#65504)
Ben Brandtc66312b200d1
diff --git a/crates/acp_thread/src/acp_thread.rs b/crates/acp_thread/src/acp_thread.rsindex 4acdf632a30..38a711270cf 100644--- a/crates/acp_thread/src/acp_thread.rs+++ b/crates/acp_thread/src/acp_thread.rs@@ -3441,6 +3441,7 @@ pub struct AcpThread {pending_terminal_output: HashMap<acp_v2::TerminalId, Vec<Vec<u8>>>,pending_terminal_exit: HashMap<acp_v2::TerminalId, acp_v1::TerminalExitStatus>,had_error: bool,+ local_execution_error: Option<Arc<anyhow::Error>>,/// The user's unsent prompt text, persisted so it can be restored when reloading the thread.draft_prompt: Option<Vec<acp_v2::ContentBlock>>,/// Lets observers detect draft changes without comparing prompts.@@ -3699,7 +3700,9 @@ impl AcpThread {| AcpThreadEvent::ToolAuthorizationReceived(_)| AcpThreadEvent::ElicitationRequested(_)| AcpThreadEvent::ElicitationResponded(_) => {- this.sync_legacy_action_state(cx);+ if !this.uses_reported_activity() {+ this.sync_local_action_state(cx);+ }this.update_idle_sleep_prevention(cx);}AcpThreadEvent::PromptUpdated@@ -3779,6 +3782,7 @@ impl AcpThread {pending_terminal_output: HashMap::default(),pending_terminal_exit: HashMap::default(),had_error: false,+ local_execution_error: None,draft_prompt: None,draft_prompt_revision: 0,ui_scroll_position: None,@@ -4001,6 +4005,36 @@ impl AcpThread {self.had_error}+ pub fn local_execution_error(&self) -> Option<&Arc<anyhow::Error>> {+ self.local_execution_error.as_ref()+ }++ pub fn report_local_execution_error(+ &mut self,+ error: Arc<anyhow::Error>,+ cx: &mut Context<Self>,+ ) -> Result<()> {+ anyhow::ensure!(+ self.uses_reported_activity(),+ "Session does not report foreground state"+ );+ let reported_error = error+ .downcast_ref::<acp_v2::Error>()+ .cloned()+ .unwrap_or_else(|| {+ let mut reported_error = acp_v2::Error::internal_error();+ reported_error.message = error.to_string();+ reported_error+ });+ self.local_execution_error = Some(error);+ self.update_session_state(+ acp_v2::StateUpdate::Idle(acp_v2::IdleStateUpdate::new().stop_reason(+ acp_v2::StopReason::Error(acp_v2::ErrorStopReason::new().error(reported_error)),+ )),+ cx,+ )+ }+pub fn is_waiting_for_confirmation(&self) -> bool {if self.uses_reported_activity() {return self.foreground_activity() == ForegroundActivity::RequiresAction;@@ -4121,6 +4155,10 @@ impl AcpThread {let (sender, receiver) = oneshot::channel();let task = cx.spawn(async move |this, cx| {let response = complete(this.clone(), cx).await;+ let response = match response {+ Err(error) if error.is::<SubmissionCancelled>() => Ok(None),+ response => response,+ };let update = this.update(cx, |this, cx| {let state = match &response {Ok(Some(SubmissionResponse::Accepted(receipt))) => {@@ -4165,12 +4203,13 @@ impl AcpThread {let current = self.foreground_activity();if previous == ForegroundActivity::Idle && current != ForegroundActivity::Idle {self.had_error = false;+ self.local_execution_error = None;}cx.notify();}- fn sync_legacy_action_state(&mut self, cx: &mut Context<Self>) {- if self.uses_reported_activity() || self.foreground_activity() == ForegroundActivity::Idle {+ pub fn sync_local_action_state(&mut self, cx: &mut Context<Self>) {+ if self.foreground_activity() == ForegroundActivity::Idle {return;}let desired = if self.has_pending_turn_action() {@@ -6303,23 +6342,111 @@ impl AcpThread {push_user_message: bool,cx: &mut Context<Self>,) -> Submission {- let id = self.register_submission(message.clone().into(), cx);if let Some(submissions) = self.submissions.receipt_transport() {- let response = submissions.prompt(message, cx);- self.track_submission(id, cx, async move |_, _| {- Ok(Some(SubmissionResponse::Accepted(response.await?)))- })+ let response = submissions.prompt(message.clone(), cx);+ self.submit_receipt(message, response, cx)} else {+ let id = self.register_submission(message.clone().into(), cx);self.send_inner(id, message, push_user_message, cx)}}- pub fn validate_prompt_content(&self, content: &[acp_v2::ContentBlock]) -> Result<()> {- if self.submissions.receipt_transport().is_some() {- Ok(())- } else {- self.connection.validate_prompt_content(content)+ pub fn submit_receipt(+ &mut self,+ content: Vec<acp_v2::ContentBlock>,+ response: Task<Result<acp_v2::PromptResponse>>,+ cx: &mut Context<Self>,+ ) -> Submission {+ let id = self.register_submission(content.into(), cx);+ self.track_submission(id, cx, async move |_, _| {+ Ok(Some(SubmissionResponse::Accepted(response.await?)))+ })+ }++ pub fn upsert_local_user_message(+ &mut self,+ id: ClientUserMessageId,+ content: Vec<acp_v2::ContentBlock>,+ cx: &mut Context<Self>,+ ) -> Result<()> {+ let previous_entry_count = self.entries.len();+ let location = self.keyed_message_location(MessageKind::User, id.message_id(), cx)?;+ let language_registry = self.project.read(cx).languages().clone();+ let path_style = self.project.read(cx).path_style(cx);+ let Some(AgentThreadEntry::UserMessage(message)) =+ self.entries.get_mut(location.entry_index())+ else {+ return Err(anyhow!("user message disappeared during preparation"));+ };+ message.client_id = Some(id);+ message.is_optimistic = false;+ message+ .content+ .replace_prompt(content, &language_registry, path_style, cx);+ self.emit_message_update(location, previous_entry_count, cx);+ cx.notify();+ Ok(())+ }++ pub fn prepare_local_prompt(+ &mut self,+ id: ClientUserMessageId,+ content: Vec<acp_v2::ContentBlock>,+ cx: &mut Context<Self>,+ ) -> Result<Task<()>> {+ let should_checkpoint = !content.is_empty() && self.can_rewind_to(Some(&id), cx);+ self.upsert_local_user_message(id.clone(), content, cx)?;+ if !should_checkpoint {+ return Ok(Task::ready(()));}++ let git_store = self.project.read(cx).git_store().clone();+ let checkpoint = git_store.update(cx, |git, cx| git.checkpoint(cx));+ Ok(cx.spawn(async move |this, cx| {+ let checkpoint = checkpoint+ .await+ .context("failed to get old checkpoint")+ .log_err();+ this.update(cx, |this, cx| {+ let identity = MessageIdentity::Keyed(id.message_id());+ if let Some((index, message)) =+ this.entries+ .iter_mut()+ .enumerate()+ .find_map(|(index, entry)| match entry {+ AgentThreadEntry::UserMessage(message)+ if message.identity == identity =>+ {+ Some((index, message))+ }+ _ => None,+ })+ {+ message.checkpoint = checkpoint.map(|git_checkpoint| Checkpoint {+ git_checkpoint,+ show: false,+ });+ cx.emit(AcpThreadEvent::EntryUpdated(index));+ }+ })+ .log_err();+ }))+ }++ pub fn finish_local_turn(+ &mut self,+ reason: acp_v2::StopReason,+ cx: &mut Context<Self>,+ ) -> Task<Result<()>> {+ // Capture the checkpoint target before refusal cleanup can remove its message.+ let checkpoint = self.update_last_checkpoint(cx);+ self.flush_streaming_text(cx);+ self.cleanup_local_turn(&reason, true, cx);+ checkpoint+ }++ pub fn validate_prompt_content(&self, content: &[acp_v2::ContentBlock]) -> Result<()> {+ self.connection.validate_prompt_content(content)}fn send_inner(@@ -6395,13 +6522,14 @@ impl AcpThread {}pub fn can_retry(&self, cx: &App) -> bool {- !self.uses_reported_activity()- && self.connection.retry(self.session_id(), cx).is_some()- && self- .submissions- .latest_id()- .and_then(|id| self.submissions.get(id))- .is_none_or(|submission| self.validate_prompt_content(&submission.content).is_ok())+ self.submissions.receipt_transport().map_or_else(+ || self.connection.retry(self.session_id(), cx).is_some(),+ |submissions| submissions.supports_retry(),+ ) && self+ .submissions+ .latest_id()+ .and_then(|id| self.submissions.get(id))+ .is_none_or(|submission| self.validate_prompt_content(&submission.content).is_ok())}pub fn retry(&mut self, cx: &mut Context<Self>) -> Submission {@@ -6412,14 +6540,15 @@ impl AcpThread {.map(|submission| submission.content.clone()).unwrap_or_default();let id = self.register_submission(content.clone(), cx);- if self.uses_reported_activity() {- return self.track_submission(id, cx, async move |_, _| {- Err(anyhow!("Receipt-driven retry is not supported"))- });- }if let Err(error) = self.validate_prompt_content(&content) {return self.track_submission(id, cx, async move |_, _| Err(error));}+ if let Some(submissions) = self.submissions.receipt_transport() {+ let response = submissions.retry(cx);+ return self.track_submission(id, cx, async move |_, _| {+ Ok(Some(SubmissionResponse::Accepted(response.await?)))+ });+ }self.run_turn(id, cx, async move |this, cx| {this.update(cx, |this, cx| {this.connection@@ -6439,6 +6568,7 @@ impl AcpThread {) -> Submission {self.clear_completed_plan_entries(cx);self.had_error = false;+ self.local_execution_error = None;let (tx, rx) = oneshot::channel();let cancel_task = self.cancel_inner(RequestPermissionOutcome::InterruptedByFollowUp, cx);@@ -6540,54 +6670,19 @@ impl AcpThread {} else {log::error!("Max tokens reached. Usage: {:?}", this.token_usage);}- if is_same_turn {- this.cancel_pending_turn_entries(cx);- }+ this.cleanup_local_turn(+ &acp_v2::StopReason::MaxTokens,+ is_same_turn,+ cx,+ );return Err(anyhow!(MaxOutputTokensError));}- let canceled = matches!(r.stop_reason, acp_v1::StopReason::Cancelled);- if canceled && is_same_turn {- this.cancel_pending_turn_entries(cx);+ if let Some(reason) = stop_reason_from_v1(&r.stop_reason) {+ this.cleanup_local_turn(&reason, is_same_turn, cx);}-- // Handle refusal - distinguish between user prompt and tool call refusals- if let acp_v1::StopReason::Refusal = r.stop_reason {- this.had_error = true;- if is_same_turn {- this.cancel_generic_permission_requests(cx);- }- if let Some((user_msg_ix, _)) = this.last_user_message() {- // Check if there's a completed tool call with results after the last user message- // This indicates the refusal is in response to tool output, not the user's prompt- let has_completed_tool_call_after_user_msg =- this.entries.iter().skip(user_msg_ix + 1).any(|entry| {- if let AgentThreadEntry::ToolCall(tool_call) = entry {- // Check if the tool call has completed and has output- matches!(tool_call.status(), ToolCallStatus::Completed)- && tool_call.raw_output.is_some()- } else {- false- }- });-- if has_completed_tool_call_after_user_msg {- // Refusal is due to tool output - don't truncate, just notify- // The model refused based on what the tool returned- cx.emit(AcpThreadEvent::Refusal);- } else {- // User prompt was refused - truncate back to before the user message- let range = user_msg_ix..this.entries.len();- if range.start < range.end {- this.truncate_entries(user_msg_ix, cx);- cx.emit(AcpThreadEvent::EntriesRemoved(range));- }- cx.emit(AcpThreadEvent::Refusal);- }- } else {- // No user message found, treat as general refusal- cx.emit(AcpThreadEvent::Refusal);- }+ if r.stop_reason == acp_v1::StopReason::Refusal {+ cx.emit(AcpThreadEvent::Refusal);}if cx.has_flag::<AcpBetaFeatureFlag>()@@ -6651,10 +6746,13 @@ impl AcpThread {self.flush_streaming_text(cx);if self.uses_reported_activity() {self.cancel_generic_permission_requests(cx);- let Some(receiver) = self.activity.wait_for_idle() else {+ let receiver = self.activity.wait_for_idle();+ if receiver.is_some() || self.has_unsettled_submissions() {+ self.connection.cancel(self.session_id(), cx);+ }+ let Some(receiver) = receiver else {return Task::ready(());};- 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");@@ -6714,11 +6812,63 @@ impl AcpThread {};}+ fn cleanup_local_turn(+ &mut self,+ reason: &acp_v2::StopReason,+ is_same_turn: bool,+ cx: &mut Context<Self>,+ ) {+ match reason {+ acp_v2::StopReason::Cancelled+ | acp_v2::StopReason::MaxTokens+ | acp_v2::StopReason::Error(_)+ if is_same_turn =>+ {+ self.cancel_pending_turn_entries(cx);+ }+ acp_v2::StopReason::Refusal => {+ self.had_error = true;+ if is_same_turn {+ self.cancel_generic_permission_requests(cx);+ }+ if let Some((user_message_index, _)) = self.last_user_message() {+ // Completed tool output makes this a tool-result refusal, not a+ // refusal of the user's prompt, so its history must be retained.+ let has_completed_tool_output = self.entries.iter()+ .skip(user_message_index + 1)+ .any(|entry| matches!(entry, AgentThreadEntry::ToolCall(call)+ if call.status() == ToolCallStatus::Completed && call.raw_output.is_some()));+ if !has_completed_tool_output {+ let range = user_message_index..self.entries.len();+ if range.start < range.end {+ self.truncate_entries(user_message_index, cx);+ cx.emit(AcpThreadEvent::EntriesRemoved(range));+ }+ }+ }+ }+ _ => {}+ }+ }+fn cancel_pending_turn_entries(&mut self, cx: &mut Context<Self>) {self.mark_pending_entries_as_canceled(RequestPermissionOutcome::Cancelled, cx);self.cancel_outstanding_elicitations(cx);}+ pub fn cancel_local_actions(+ &mut self,+ outcome: RequestPermissionOutcome,+ cx: &mut Context<Self>,+ ) {+ self.mark_pending_entries_as_canceled(outcome.clone(), cx);+ let request_ids = self.permission_requests.keys().copied().collect::<Vec<_>>();+ for id in request_ids {+ self.cancel_permission_request_with_outcome(id, outcome.clone(), cx);+ }+ self.cancel_outstanding_elicitations(cx);+ }+fn mark_pending_entries_as_canceled(&mut self,permission_outcome: RequestPermissionOutcome,@@ -6850,9 +7000,10 @@ impl AcpThread {}fn update_last_checkpoint_if_changed(&mut self, cx: &mut Context<Self>) -> Task<Result<()>> {- let Some(turn_id) = self.running_turn.as_ref().map(|turn| turn.id) else {+ if self.foreground_activity() == ForegroundActivity::Idle {return Task::ready(Ok(()));- };+ }+ let activity_generation = self.activity_generation();let git_store = self.project.read(cx).git_store().clone();@@ -6894,10 +7045,8 @@ impl AcpThread {}this.update(cx, |this, cx| {- if !this- .running_turn- .as_ref()- .is_some_and(|turn| turn.id == turn_id)+ if this.foreground_activity() == ForegroundActivity::Idle+ || this.activity_generation() != activity_generation{return;}@@ -10786,6 +10935,458 @@ mod tests {(thread, connection)}+ #[gpui::test]+ async fn test_local_prompt_preserves_keyed_identity_source_and_command_marker(+ cx: &mut TestAppContext,+ ) {+ init_test(cx);+ let (thread, _) = new_receipt_test_thread(cx).await;+ let id = ClientUserMessageId::new();+ let source = vec!["local prompt".into()];+ thread+ .update(cx, |thread, cx| {+ thread.prepare_local_prompt(id.clone(), vec!["initial".into()], cx)+ })+ .expect("synchronous local insertion")+ .await;+ thread.update(cx, |thread, cx| {+ thread+ .upsert_assistant_message(+ acp_v2::AgentMessage::new("assistant").content(vec!["reply".into()]),+ cx,+ )+ .expect("assistant entry after local message");+ });+ thread+ .update(cx, |thread, cx| {+ thread.prepare_local_prompt(ClientUserMessageId::new(), Vec::new(), cx)+ })+ .expect("empty command marker")+ .await;+ thread+ .update(cx, |thread, cx| {+ thread.prepare_local_prompt(id.clone(), source.clone(), cx)+ })+ .expect("replace exact keyed local message")+ .await;+ let submission = thread.update(cx, |thread, cx| {+ thread.submit_receipt(+ source.clone(),+ Task::ready(Ok(acp_v2::PromptResponse::new(id.message_id()))),+ cx,+ )+ });+ let submission_id = submission.id;+ assert!(matches!(+ submission.await.expect("receipt"),+ Some(SubmissionResponse::Accepted(_))+ ));+ thread.read_with(cx, |thread, _| {+ let [+ AgentThreadEntry::UserMessage(message),+ AgentThreadEntry::AssistantMessage(_),+ AgentThreadEntry::UserMessage(marker),+ ] = thread.entries()+ else {+ panic!("replacement must preserve entry order");+ };+ assert_eq!(message.identity, MessageIdentity::Keyed(id.message_id()));+ assert_eq!(message.client_id.as_ref(), Some(&id));+ assert!(!message.is_optimistic);+ assert_eq!(message.content.source_blocks(), source.as_slice());+ assert!(marker.content.source_blocks().is_empty());+ assert_eq!(thread.foreground_activity(), ForegroundActivity::Idle);+ assert!(matches!(+ thread+ .submission(submission_id)+ .expect("local receipt")+ .state,+ SubmissionState::Accepted { echoed: true, .. }+ ));+ });+ }++ #[gpui::test]+ async fn test_local_execution_error_preserves_type_and_reports_one_stop(+ cx: &mut TestAppContext,+ ) {+ init_test(cx);+ let (thread, _) = new_receipt_test_thread(cx).await;+ let stops = Rc::new(RefCell::new(Vec::new()));+ let errors = Rc::new(RefCell::new(0));+ let _subscription = cx.update(|cx| {+ let stops = stops.clone();+ let errors = errors.clone();+ cx.subscribe(&thread, move |thread, event, cx| match event {+ AcpThreadEvent::Stopped { stop_reason, .. } => {+ assert!(thread.read(cx).local_execution_error().is_some());+ stops.borrow_mut().push(stop_reason.clone());+ }+ AcpThreadEvent::Error => *errors.borrow_mut() += 1,+ _ => {}+ })+ });+ thread.update(cx, |thread, cx| {+ thread+ .update_session_state(+ acp_v2::StateUpdate::Running(acp_v2::RunningStateUpdate::new()),+ cx,+ )+ .expect("local running");+ });+ let permission = request_test_permission(&thread, "pending-local-tool".into(), cx);+ let (_, elicitation) = request_test_form_elicitation(&thread, cx);+ let (_, generic_permission) = thread.update(cx, |thread, cx| {+ thread+ .request_permission(test_generic_permission_request(thread, "generic"), cx)+ .expect("generic permission before local failure")+ });+ let original_error = Arc::new(anyhow!(MaxOutputTokensError));+ thread+ .update(cx, |thread, cx| {+ thread.finish_local_turn(+ acp_v2::StopReason::Error(acp_v2::ErrorStopReason::new()),+ cx,+ )+ })+ .await+ .expect("local cleanup");+ assert!(stops.borrow().is_empty());+ assert!(matches!(+ permission.await,+ RequestPermissionOutcome::Cancelled+ ));+ assert_eq!(elicitation.await.action, acp_v2::ElicitationAction::Cancel);+ assert_eq!(+ generic_permission.await,+ acp_v2::RequestPermissionOutcome::Cancelled+ );+ thread.update(cx, |thread, cx| {+ assert_eq!(thread.foreground_activity(), ForegroundActivity::Running);+ thread+ .report_local_execution_error(original_error.clone(), cx)+ .expect("local execution error");+ let retained = thread+ .local_execution_error()+ .expect("retained typed error");+ assert!(Arc::ptr_eq(retained, &original_error));+ assert!(retained.downcast_ref::<MaxOutputTokensError>().is_some());+ assert!(thread.had_error());+ });+ cx.run_until_parked();+ {+ let stops = stops.borrow();+ let [Some(acp_v2::StopReason::Error(reason))] = stops.as_slice() else {+ panic!("one error stop expected");+ };+ let error = reason.error.as_ref().expect("meaningful SDK error");+ assert_eq!(error.code, acp_v2::ErrorCode::InternalError);+ assert_eq!(error.message, original_error.to_string());+ }+ let sdk_error = acp_v2::Error::auth_required().data(json!({"provider": "typed"}));+ thread.update(cx, |thread, cx| {+ thread+ .update_session_state(+ acp_v2::StateUpdate::Running(acp_v2::RunningStateUpdate::new()),+ cx,+ )+ .expect("next generation");+ assert!(thread.local_execution_error().is_none());+ assert!(!thread.had_error());+ thread+ .report_local_execution_error(Arc::new(anyhow!(sdk_error.clone())), cx)+ .expect("SDK execution error");+ });+ cx.run_until_parked();+ let stops = stops.borrow();+ assert_eq!(stops.len(), 2);+ let Some(Some(acp_v2::StopReason::Error(reason))) = stops.last() else {+ panic!("SDK error stop");+ };+ assert_eq!(reason.error.as_deref(), Some(&sdk_error));+ assert_eq!(*errors.borrow(), 0);+ }++ #[gpui::test]+ async fn test_local_actions_require_explicit_sync_and_settle_follow_up(+ cx: &mut TestAppContext,+ ) {+ init_test(cx);+ let (thread, _) = new_receipt_test_thread(cx).await;+ thread.update(cx, |thread, cx| {+ thread+ .update_session_state(+ acp_v2::StateUpdate::Running(acp_v2::RunningStateUpdate::new()),+ cx,+ )+ .expect("local running");+ });+ let (_, generic_response) = thread+ .update(cx, |thread, cx| {+ thread.request_permission(test_generic_permission_request(thread, "choice"), cx)+ })+ .expect("generic pending owner");+ let local_response = request_test_permission(&thread, "local-tool".into(), cx);+ let (_, elicitation_response) = request_test_form_elicitation(&thread, cx);+ cx.run_until_parked();+ thread.update(cx, |thread, cx| {+ assert_eq!(thread.foreground_activity(), ForegroundActivity::Running);+ thread.sync_local_action_state(cx);+ assert_eq!(+ thread.foreground_activity(),+ ForegroundActivity::RequiresAction+ );+ thread.cancel_local_actions(RequestPermissionOutcome::InterruptedByFollowUp, cx);+ thread.sync_local_action_state(cx);+ assert_eq!(thread.foreground_activity(), ForegroundActivity::Running);+ assert_eq!(thread.pending_permission_requests().count(), 0);+ assert_eq!(+ thread+ .tool_call(&"local-tool".into())+ .expect("local tool")+ .1+ .status(),+ ToolCallStatus::Canceled+ );+ });+ assert_eq!(+ generic_response.await,+ acp_v2::RequestPermissionOutcome::Cancelled+ );+ assert!(matches!(+ local_response.await,+ RequestPermissionOutcome::InterruptedByFollowUp+ ));+ assert_eq!(+ elicitation_response.await.action,+ acp_v2::ElicitationAction::Cancel+ );+ thread.update(cx, |thread, cx| {+ thread+ .update_session_state(+ acp_v2::StateUpdate::Idle(acp_v2::IdleStateUpdate::new()),+ cx,+ )+ .expect("driver reports idle");+ thread.sync_local_action_state(cx);+ assert_eq!(thread.foreground_activity(), ForegroundActivity::Idle);+ });+ }++ #[gpui::test]+ async fn test_local_checkpoints_target_exact_message_and_activity_generation(+ cx: &mut TestAppContext,+ ) {+ init_test(cx);+ let fs = FakeFs::new(cx.executor());+ fs.insert_tree(path!("/test"), json!({".git": {}})).await;+ let project = Project::test(fs, [Path::new(path!("/test"))], cx).await;+ let connection = Rc::new(StubAgentConnection::new().with_receipt_submissions(true));+ let thread = cx+ .update(|cx| {+ connection.new_session(project, PathList::new(&[Path::new(path!("/test"))]), cx)+ })+ .await+ .expect("local checkpoint thread");+ cx.run_until_parked();+ let id = ClientUserMessageId::new();+ let marker_id = ClientUserMessageId::new();+ let preparation = thread+ .update(cx, |thread, cx| {+ thread.prepare_local_prompt(id.clone(), vec!["source".into()], cx)+ })+ .expect("prepare source");+ thread+ .update(cx, |thread, cx| {+ thread.prepare_local_prompt(marker_id.clone(), Vec::new(), cx)+ })+ .expect("interleaved hidden marker")+ .await;+ preparation.await;+ thread.update(cx, |thread, cx| {+ assert!(+ thread+ .user_message_mut(&id)+ .expect("source")+ .1+ .checkpoint+ .is_some()+ );+ assert!(+ thread+ .user_message_mut(&marker_id)+ .expect("marker")+ .1+ .checkpoint+ .is_none()+ );+ thread.truncate_entries(1, cx);+ thread+ .update_session_state(+ acp_v2::StateUpdate::Running(acp_v2::RunningStateUpdate::new()),+ cx,+ )+ .expect("reported running without legacy turn");+ assert!(thread.running_turn.is_none());+ });+ thread+ .update(cx, |thread, cx| {+ thread.write_text_file(PathBuf::from(path!("/test/file.txt")), "after".into(), cx)+ })+ .await+ .expect("local edit");+ cx.run_until_parked();+ let stale_checkpoint = thread.update(cx, |thread, cx| {+ let checkpoint = thread+ .user_message_mut(&id)+ .expect("source")+ .1+ .checkpoint+ .as_mut()+ .expect("checkpoint");+ assert!(checkpoint.show, "reported edit must reveal checkpoint");+ checkpoint.show = false;+ let stale_checkpoint = thread.update_last_checkpoint_if_changed(cx);+ thread+ .update_session_state(+ acp_v2::StateUpdate::Idle(acp_v2::IdleStateUpdate::new()),+ cx,+ )+ .expect("old activity ends");+ thread+ .update_session_state(+ acp_v2::StateUpdate::Running(acp_v2::RunningStateUpdate::new()),+ cx,+ )+ .expect("successor activity");+ stale_checkpoint+ });+ stale_checkpoint.await.expect("stale checkpoint completes");+ thread.update(cx, |thread, _| {+ assert!(+ !thread+ .user_message_mut(&id)+ .expect("source")+ .1+ .checkpoint+ .as_ref()+ .expect("checkpoint")+ .show+ );+ });+ thread+ .update(cx, |thread, cx| {+ thread.finish_local_turn(acp_v2::StopReason::EndTurn, cx)+ })+ .await+ .expect("local final checkpoint");+ thread.update(cx, |thread, cx| {+ assert!(+ thread+ .user_message_mut(&id)+ .expect("source")+ .1+ .checkpoint+ .as_ref()+ .expect("checkpoint")+ .show+ );+ assert_eq!(thread.foreground_activity(), ForegroundActivity::Running);+ thread+ .update_session_state(+ acp_v2::StateUpdate::Idle(acp_v2::IdleStateUpdate::new()),+ cx,+ )+ .expect("driver finishes");+ });+ }++ #[gpui::test]+ async fn test_local_refusal_reports_one_stop(cx: &mut TestAppContext) {+ init_test(cx);+ let (thread, _) = new_receipt_test_thread(cx).await;+ let events = Rc::new(RefCell::new(Vec::new()));+ let _subscription = cx.update(|cx| {+ cx.subscribe(&thread, {+ let events = events.clone();+ move |_, event, _| match event {+ AcpThreadEvent::Refusal => events.borrow_mut().push("legacy refusal"),+ AcpThreadEvent::Stopped {+ stop_reason: Some(acp_v2::StopReason::Refusal),+ ..+ } => events.borrow_mut().push("stopped"),+ _ => {}+ }+ })+ });+ let finish = thread.update(cx, |thread, cx| {+ thread+ .upsert_local_user_message(ClientUserMessageId::new(), vec!["prompt".into()], cx)+ .expect("accepted local message");+ thread+ .update_session_state(+ acp_v2::StateUpdate::Running(acp_v2::RunningStateUpdate::new()),+ cx,+ )+ .expect("running");+ thread.finish_local_turn(acp_v2::StopReason::Refusal, cx)+ });+ finish.await.expect("local cleanup");+ assert!(events.borrow().is_empty());+ thread.update(cx, |thread, cx| {+ assert!(thread.entries().is_empty());+ thread+ .update_session_state(+ acp_v2::StateUpdate::Idle(+ acp_v2::IdleStateUpdate::new().stop_reason(acp_v2::StopReason::Refusal),+ ),+ cx,+ )+ .expect("reported refusal");+ });+ cx.run_until_parked();+ assert_eq!(*events.borrow(), ["stopped"]);+ }++ #[gpui::test]+ async fn test_pending_receipt_cancellation_signals_without_completing_activity(+ cx: &mut TestAppContext,+ ) {+ init_test(cx);+ let (thread, connection) = new_receipt_test_thread(cx).await;+ let response = connection.defer_next_receipt_response();+ let submission = thread.update(cx, |thread, cx| thread.send(vec!["pending".into()], cx));+ let id = submission.id;+ thread.update(cx, |thread, cx| thread.cancel(cx)).await;+ assert_eq!(+ connection.take_cancel_calls(),+ [thread.read_with(cx, |thread, _| thread.session_id().clone())]+ );+ thread.read_with(cx, |thread, _| {+ assert_eq!(thread.foreground_activity(), ForegroundActivity::Idle);+ assert_eq!(thread.activity_generation(), 0);+ assert!(matches!(+ thread.submission(id).expect("still pending").state,+ SubmissionState::Pending+ ));+ });+ response+ .send(Err(anyhow!(SubmissionCancelled)))+ .expect("receipt observer");+ assert!(submission.await.expect("withdrawn acceptance").is_none());+ thread.read_with(cx, |thread, _| {+ assert!(matches!(+ thread.submission(id).expect("cancelled").state,+ SubmissionState::Cancelled+ ));+ assert!(!thread.has_unsettled_submissions());+ assert!(!thread.had_error());+ assert!(thread.entries().is_empty());+ });+ thread.update(cx, |thread, cx| thread.cancel(cx)).await;+ assert!(connection.take_cancel_calls().is_empty());+ }+#[gpui::test]async fn test_receipt_and_echo_correlate_by_id_without_owning_history_or_activity(cx: &mut TestAppContext,@@ -22658,9 +23259,17 @@ mod tests {"refusal","refusal without user","refusal after tool",+ "local refusal",+ "local refusal after tool","rewind",] {- let thread = if matches!(lifecycle, "reported cancel" | "reported idle cancel") {+ let thread = if matches!(+ lifecycle,+ "reported cancel"+ | "reported idle cancel"+ | "local refusal"+ | "local refusal after tool"+ ) {new_receipt_test_thread(cx).await.0} else {new_test_thread(cx).await@@ -22671,7 +23280,10 @@ mod tests {if lifecycle != "refusal without user" {thread.push_user_content_block(None, "retained".into(), cx);}- if lifecycle == "reported cancel" {+ if matches!(+ lifecycle,+ "reported cancel" | "local refusal" | "local refusal after tool"+ ) {thread.update_session_state(acp_v2::StateUpdate::Running(acp_v2::RunningStateUpdate::new()),@@ -22694,7 +23306,7 @@ mod tests {if lifecycle != "refusal without user" {thread.push_user_content_block(Some(client_id.clone()), "remove me".into(), cx);}- if lifecycle == "refusal after tool" {+ if matches!(lifecycle, "refusal after tool" | "local refusal after tool") {thread.upsert_tool_call(acp_v1::ToolCall::new("finished-tool", "Finished operation")@@ -22748,6 +23360,25 @@ mod tests {cancellation.await;}turn.await.expect("turn settles");+ } else if matches!(lifecycle, "local refusal" | "local refusal after tool") {+ thread+ .update(cx, |thread, cx| {+ thread.finish_local_turn(acp_v2::StopReason::Refusal, cx)+ })+ .await+ .expect("local refusal cleanup");+ thread.update(cx, |thread, cx| {+ assert_eq!(thread.foreground_activity(), ForegroundActivity::Running);+ thread+ .update_session_state(+ acp_v2::StateUpdate::Idle(+ acp_v2::IdleStateUpdate::new()+ .stop_reason(acp_v2::StopReason::Refusal),+ ),+ cx,+ )+ .expect("local driver reports refusal");+ });} else if lifecycle == "rewind" {thread.update(cx, |thread, cx| thread.rewind(client_id, cx))@@ -22774,9 +23405,9 @@ mod tests {0,"{lifecycle}");- if lifecycle == "refusal without user" {+ if matches!(lifecycle, "refusal without user" | "local refusal") {assert!(thread.entries().is_empty());- } else if lifecycle == "refusal after tool" {+ } else if matches!(lifecycle, "refusal after tool" | "local refusal after tool") {assert_eq!(thread.entries().len(), entry_count_before_stop);let (_, call) = thread.tool_call(&"finished-tool".into())diff --git a/crates/acp_thread/src/connection.rs b/crates/acp_thread/src/connection.rsindex c799611b99e..e11df7c07f5 100644--- a/crates/acp_thread/src/connection.rs+++ b/crates/acp_thread/src/connection.rs@@ -21,6 +21,10 @@ impl ClientUserMessageId {pub fn new() -> Self {Self(Uuid::new_v4().to_string().into())}++ pub fn message_id(&self) -> acp_v2::MessageId {+ acp_v2::MessageId::new(self.0.as_ref())+ }}#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Hash)]@@ -316,6 +320,16 @@ pub trait ReceiptSessionSubmissions {content: Vec<acp_v2::ContentBlock>,cx: &mut App,) -> Task<Result<acp_v2::PromptResponse>>;++ fn supports_retry(&self) -> bool {+ false+ }++ fn retry(&self, _cx: &mut App) -> Task<Result<acp_v2::PromptResponse>> {+ Task::ready(Err(anyhow::anyhow!(+ "Receipt-driven retry is not supported"+ )))+ }}pub trait AgentSessionRetry {@@ -863,6 +877,7 @@ mod test_support {receipt_prompt: Arc<Mutex<Option<Vec<acp_v2::ContentBlock>>>>,next_truncate: Arc<Mutex<Option<oneshot::Receiver<()>>>>,set_title_calls: Arc<Mutex<Vec<(acp_v2::SessionId, SharedString)>>>,+ cancel_calls: Arc<Mutex<Vec<acp_v2::SessionId>>>,supports_receipt_submissions: bool,supports_retry: bool,supports_load_session: bool,@@ -893,6 +908,7 @@ mod test_support {receipt_prompt: Default::default(),next_truncate: Default::default(),set_title_calls: Default::default(),+ cancel_calls: Default::default(),permission_requests: HashMap::default(),sessions: Arc::default(),supports_receipt_submissions: false,@@ -944,6 +960,10 @@ mod test_support {std::mem::take(&mut *self.set_title_calls.lock())}+ pub fn take_cancel_calls(&self) -> Vec<acp_v2::SessionId> {+ std::mem::take(&mut *self.cancel_calls.lock())+ }+pub fn defer_next_truncate(&self) -> oneshot::Sender<()> {let (sender, receiver) = oneshot::channel();assert!(self.next_truncate.lock().replace(receiver).is_none());@@ -1238,6 +1258,7 @@ mod test_support {}fn cancel(&self, session_id: &acp_v2::SessionId, _cx: &mut App) {+ self.cancel_calls.lock().push(session_id.clone());if let Some(end_turn_tx) = self.sessions.lock()diff --git a/crates/acp_thread/src/submission.rs b/crates/acp_thread/src/submission.rsindex d3f63a61072..fe85999fc51 100644--- a/crates/acp_thread/src/submission.rs+++ b/crates/acp_thread/src/submission.rs@@ -28,6 +28,18 @@ pub enum SubmissionResponse {Accepted(acp_v2::PromptResponse),}+/// A local receipt withdrawn by cancellation before the message was accepted.+#[derive(Debug)]+pub struct SubmissionCancelled;++impl fmt::Display for SubmissionCancelled {+ fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {+ formatter.write_str("Submission cancelled before acceptance")+ }+}++impl std::error::Error for SubmissionCancelled {}+pub struct Submission {pub id: SubmissionId,pub response: BoxFuture<'static, anyhow::Result<Option<SubmissionResponse>>>,diff --git a/crates/agent_ui/src/conversation_view.rs b/crates/agent_ui/src/conversation_view.rsindex ee908087699..e085489e3ee 100644--- a/crates/agent_ui/src/conversation_view.rs+++ b/crates/agent_ui/src/conversation_view.rs@@ -164,6 +164,12 @@ pub(crate) enum ThreadError {impl From<anyhow::Error> for ThreadError {fn from(error: anyhow::Error) -> Self {+ Self::from(&error)+ }+}++impl From<&anyhow::Error> for ThreadError {+ fn from(error: &anyhow::Error) -> Self {if error.is::<MaxOutputTokensError>() {Self::MaxOutputTokens} else if error.is::<NoModelConfiguredError>() {@@ -1926,6 +1932,9 @@ impl ConversationView {matches!(thread.read(cx).status(), ThreadStatus::Generating);active.update(cx, |active, cx| {if !is_generating {+ if thread.read(cx).uses_reported_activity() {+ active.sync_follow_agent_state(cx);+ }active.thread_retry_status.take();active.clear_auto_expand_tracking(cx);if active.list_state.is_following_tail() {@@ -1935,70 +1944,85 @@ impl ConversationView {active.sync_generating_indicator(cx);});}- if is_subagent {- if *stop_reason == Some(acp_v2::StopReason::EndTurn) {- thread.update(cx, |thread, cx| {- thread.mark_as_subagent_output(cx);- });- }- return;+ if is_subagent && *stop_reason == Some(acp_v2::StopReason::EndTurn) {+ thread.update(cx, |thread, cx| {+ thread.mark_as_subagent_output(cx);+ });}if *stop_reason == Some(acp_v2::StopReason::MaxTokens)&& thread.read(cx).uses_reported_activity(){- if let Some(active) = self.root_thread_view() {+ if let Some(active) = self.thread_view(&session_id) {active.update(cx, |active, cx| {active.message_queue.pause();active.handle_thread_error(anyhow::Error::new(MaxOutputTokensError), cx);});}- self.notify_with_sound(- "Agent stopped at the output token limit",- IconName::Warning,- window,- cx,- );+ if !is_subagent {+ self.notify_with_sound(+ "Agent stopped at the output token limit",+ IconName::Warning,+ window,+ cx,+ );+ }return;}if *stop_reason == Some(acp_v2::StopReason::Refusal)&& thread.read(cx).uses_reported_activity(){- if let Some(active) = self.root_thread_view() {+ if let Some(active) = self.thread_view(&session_id) {active.update(cx, |active, cx| {active.message_queue.pause();active.handle_thread_error(ThreadError::Refusal, cx);});}- self.notify_with_sound(- "Agent refused to respond to this request",- IconName::Warning,- window,- cx,- );+ if !is_subagent {+ self.notify_with_sound(+ "Agent refused to respond to this request",+ IconName::Warning,+ window,+ cx,+ );+ }return;}if let Some(acp_v2::StopReason::Error(details)) = stop_reason&& thread.read(cx).uses_reported_activity(){- if let Some(active) = self.root_thread_view() {- let error = details- .error- .as_deref()- .map(|error| anyhow::Error::new(error.clone()))- .unwrap_or_else(|| anyhow!("Agent stopped because of an error"));+ if let Some(active) = self.thread_view(&session_id) {+ let error = thread+ .read(cx)+ .local_execution_error()+ .map(|error| ThreadError::from(error.as_ref()))+ .unwrap_or_else(|| {+ let error = details+ .error+ .as_deref()+ .map(|error| anyhow::Error::new(error.clone()))+ .unwrap_or_else(|| {+ anyhow!("Agent stopped because of an error")+ });+ ThreadError::from(error)+ });active.update(cx, |active, cx| {active.message_queue.pause();active.handle_thread_error(error, cx);});}- self.notify_with_sound(- "Agent stopped because of an error",- IconName::Warning,- window,- cx,- );+ if !is_subagent {+ self.notify_with_sound(+ "Agent stopped because of an error",+ IconName::Warning,+ window,+ cx,+ );+ }+ return;+ }+ if is_subagent {return;}@@ -5006,6 +5030,47 @@ pub(crate) mod tests {assert!(cx.debug_bounds(second_copy).is_some());}+ #[gpui::test]+ async fn test_hidden_command_marker_keeps_empty_editor_mode(cx: &mut TestAppContext) {+ init_test(cx);+ let connection = StubAgentConnection::new().with_receipt_submissions(true);+ let (conversation_view, cx) =+ setup_conversation_view(StubAgentServer::new(connection), cx).await;+ add_to_workspace(conversation_view.clone(), cx);+ let thread_view = active_thread(&conversation_view, cx);+ let thread = thread_view.read_with(cx, |view, _| view.thread.clone());+ thread.update(cx, |thread, cx| {+ thread+ .upsert_local_user_message(acp_thread::ClientUserMessageId::new(), Vec::new(), cx)+ .expect("retained command marker");+ });+ cx.run_until_parked();+ thread_view.read_with(cx, |view, cx| {+ assert_eq!(view.thread.read(cx).entries().len(), 1);+ assert!(!view.can_edit_user_message(0, cx));+ assert!(matches!(+ view.message_editor.read(cx).editor().read(cx).mode(),+ editor::EditorMode::Full { .. }+ ));+ });+ thread.update(cx, |thread, cx| {+ thread+ .upsert_local_user_message(+ acp_thread::ClientUserMessageId::new(),+ vec!["visible prompt".into()],+ cx,+ )+ .expect("visible prompt");+ });+ cx.run_until_parked();+ thread_view.read_with(cx, |view, cx| {+ assert!(matches!(+ view.message_editor.read(cx).editor().read(cx).mode(),+ editor::EditorMode::AutoHeight { .. }+ ));+ });+ }+#[gpui::test]async fn test_reported_stale_stop_and_token_limit_do_not_send_queue(cx: &mut TestAppContext) {init_test(cx);@@ -5016,6 +5081,7 @@ pub(crate) mod tests {let thread_view = active_thread(&conversation_view, cx);let thread = thread_view.read_with(cx, |view, _| view.thread.clone());thread_view.update_in(cx, |view, window, cx| {+ view.should_be_following = true;view.add_to_queue(vec!["queued".into()], vec![], window, cx);});thread.update(cx, |thread, cx| {@@ -5043,7 +5109,10 @@ pub(crate) mod tests {.expect("running B");});cx.run_until_parked();- thread_view.read_with(cx, |view, _| assert_eq!(view.message_queue.len(), 1));+ thread_view.read_with(cx, |view, _| {+ assert_eq!(view.message_queue.len(), 1);+ assert!(view.should_be_following);+ });assert!(thread.read_with(cx, |thread, _| thread.activity_generation() > generation_a));thread.update(cx, |thread, cx| {thread@@ -5074,6 +5143,7 @@ pub(crate) mod tests {Some(ThreadError::MaxOutputTokens)));assert_eq!(view.message_queue.len(), 1);+ assert!(!view.should_be_following);assert!(view.turn_fields.turn_started_at.is_none());assert!(view.turn_fields._turn_timer_task.is_none());assert_eq!(@@ -5114,6 +5184,7 @@ pub(crate) mod tests {#[gpui::test]async fn test_reported_error_after_acceptance_pauses_queue(cx: &mut TestAppContext) {init_test(cx);+ cx.update(language_model::init);let connection = StubAgentConnection::new().with_receipt_submissions(true);let (conversation_view, cx) =setup_conversation_view(StubAgentServer::new(connection.clone()), cx).await;@@ -5135,6 +5206,31 @@ pub(crate) mod tests {thread_view.update_in(cx, |view, window, cx| {view.add_to_queue(vec!["follow-up".into()], vec![], window, cx);});+ thread.update(cx, |thread, cx| {+ thread+ .update_session_state(+ acp_v2::StateUpdate::Running(acp_v2::RunningStateUpdate::new()),+ cx,+ )+ .expect("running local work");+ thread+ .report_local_execution_error(+ Arc::new(anyhow!(LanguageModelCompletionError::NoApiKey {+ provider: ZED_CLOUD_PROVIDER_NAME,+ })),+ cx,+ )+ .expect("failed local work");+ });+ cx.run_until_parked();+ thread_view.read_with(cx, |view, _| {+ let Some(ThreadError::NoCredentials { provider }) = &view.thread_error else {+ panic!("local provider error classification should be retained");+ };+ assert_eq!(provider.to_string(), ZED_CLOUD_PROVIDER_NAME.to_string());+ assert_eq!(view.message_queue.len(), 1);+ assert!(view.message_queue.auto_send_candidate(false).is_none());+ });for (details, expected_message, expected_code) in [(Some(acp_v2::Error::new(@@ -5158,6 +5254,7 @@ pub(crate) mod tests {cx,).expect("running");+ assert!(thread.local_execution_error().is_none());thread.update_session_state(acp_v2::StateUpdate::Idle(acp_v2::IdleStateUpdate::new().stop_reason(@@ -5208,6 +5305,69 @@ pub(crate) mod tests {}}+ #[gpui::test]+ async fn test_reported_subagent_failure_is_scoped_to_its_view(cx: &mut TestAppContext) {+ init_test(cx);+ let connection = StubAgentConnection::new().with_receipt_submissions(true);+ let (conversation_view, cx) =+ setup_conversation_view(StubAgentServer::new(connection), cx).await;+ add_to_workspace(conversation_view.clone(), cx);+ let root_view = active_thread(&conversation_view, cx);+ let (root, conversation) = root_view.read_with(cx, |view, _| {+ (view.thread.clone(), view.conversation.clone())+ });+ let root_session_id = root.read_with(cx, |thread, _| thread.session_id().clone());+ let child_session_id = acp_v2::SessionId::new("reported-child");+ let child_view = conversation_view.update_in(cx, |view, window, cx| {+ let child = create_test_acp_thread(+ Some(root_session_id),+ child_session_id.0.as_ref(),+ Rc::new(StubAgentConnection::new().with_receipt_submissions(true)),+ view.project.clone(),+ cx,+ );+ conversation.update(cx, |conversation, cx| {+ conversation.register_thread(child.clone(), cx);+ });+ let child_view =+ view.new_thread_view(child, conversation.clone(), false, None, window, cx);+ view.as_connected_mut()+ .expect("connected")+ .threads+ .insert(child_session_id, child_view.clone());+ child_view+ });+ root_view.update_in(cx, |view, window, cx| {+ view.add_to_queue(vec!["root follow-up".into()], vec![], window, cx);+ });+ child_view.update_in(cx, |view, window, cx| {+ view.add_to_queue(vec!["child follow-up".into()], vec![], window, cx);+ view.thread.update(cx, |thread, cx| {+ thread+ .update_session_state(+ acp_v2::StateUpdate::Running(acp_v2::RunningStateUpdate::new()),+ cx,+ )+ .expect("child running");+ thread+ .report_local_execution_error(Arc::new(anyhow!(MaxOutputTokensError)), cx)+ .expect("child failure");+ });+ });+ cx.run_until_parked();+ child_view.read_with(cx, |view, _| {+ assert!(matches!(+ view.thread_error,+ Some(ThreadError::MaxOutputTokens)+ ));+ assert!(view.message_queue.auto_send_candidate(false).is_none());+ });+ root_view.read_with(cx, |view, _| {+ assert!(view.thread_error.is_none());+ assert!(view.message_queue.auto_send_candidate(false).is_some());+ });+ }+#[gpui::test]async fn test_stale_send_result_preserves_new_prompt(cx: &mut TestAppContext) {init_test(cx);diff --git a/crates/agent_ui/src/conversation_view/thread_view.rs b/crates/agent_ui/src/conversation_view/thread_view.rsindex 25607edf9fe..e0ce09bb64a 100644--- a/crates/agent_ui/src/conversation_view/thread_view.rs+++ b/crates/agent_ui/src/conversation_view/thread_view.rs@@ -1268,6 +1268,14 @@ impl ThreadView {self.parent_session_id.is_some()}+ fn has_visible_conversation(&self, cx: &App) -> bool {+ self.generating_indicator_in_list+ || self.thread.read(cx).entries().iter().any(|entry| {+ !matches!(entry, AgentThreadEntry::UserMessage(message)+ if message.content.source_blocks().is_empty())+ })+ }+pub(super) fn can_edit_user_message(&self, index: usize, cx: &App) -> bool {let thread = self.thread.read(cx);let Some(message) = thread@@ -1278,6 +1286,7 @@ impl ThreadView {return false;};thread.can_rewind_to(message.client_id.as_ref(), cx)+ && !message.content.source_blocks().is_empty()&& message.content.source_blocks()@@ -1498,6 +1507,15 @@ impl ThreadView {cx.notify();}+ pub(crate) fn sync_follow_agent_state(&mut self, cx: &mut Context<Self>) {+ self.should_be_following = self+ .workspace+ .update(cx, |workspace, _| {+ workspace.is_being_followed(CollaboratorId::Agent)+ })+ .unwrap_or_default();+ }+pub(crate) fn report_activity_completion(&self,stop_reason: &Option<acp_v2::StopReason>,@@ -2117,12 +2135,7 @@ impl ThreadView {match res {Ok(Some(SubmissionResponse::LegacyCompleted(_))) => {this.current_submission.take();- this.should_be_following = this- .workspace- .update(cx, |workspace, _| {- workspace.is_being_followed(CollaboratorId::Agent)- })- .unwrap_or_default();+ this.sync_follow_agent_state(cx);}Ok(Some(SubmissionResponse::Accepted(_))) => {}Ok(None) => {}@@ -2817,7 +2830,7 @@ impl ThreadView {_window: &mut Window,cx: &mut Context<Self>,) {- if self.list_state.item_count() == 0 {+ if !self.has_visible_conversation(cx) {return;}self.set_editor_is_expanded(!self.editor_expanded, cx);@@ -4947,7 +4960,7 @@ impl ThreadView {};let max_content_width = AgentSettings::get_global(cx).max_content_width;- let has_messages = self.list_state.item_count() > 0;+ let has_messages = self.has_visible_conversation(cx);let fills_container = !has_messages || editor_expanded;let composer_is_read_only = self.message_editor.read(cx).editor().read(cx).read_only(cx);let discard_draft_button = composer_is_read_only.then(|| {@@ -6759,6 +6772,9 @@ impl ThreadView {let primary = match &entry {AgentThreadEntry::UserMessage(message) => {+ if message.content.source_blocks().is_empty() {+ return Empty.into_any_element();+ }let Some(editor) = self.entry_view_state.read(cx)@@ -7902,7 +7918,7 @@ impl ThreadView {}pub(crate) fn sync_editor_mode(&mut self, cx: &mut Context<Self>) {- let has_messages = self.list_state.item_count() > 0;+ let has_messages = self.has_visible_conversation(cx);let v2_empty_state = !has_messages;if !has_messages {@@ -13013,7 +13029,7 @@ impl Render for ThreadView {// renders (settings, connection state, feature flags).self.sync_local_commands(cx);- let has_messages = self.list_state.item_count() > 0;+ let has_messages = self.has_visible_conversation(cx);let list_state = self.list_state.clone();let conversation = v_flex()