Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
acp_thread: Separate submission receipts from session activity (#64930)
Ben Brandt39b5329322f4
diff --git a/crates/acp_thread/src/acp_thread.rs b/crates/acp_thread/src/acp_thread.rsindex 7a15c0cb20c..d5aa15ee6a6 100644--- a/crates/acp_thread/src/acp_thread.rs+++ b/crates/acp_thread/src/acp_thread.rs@@ -2,6 +2,7 @@ mod connection;pub mod content;mod diff;mod mention;+mod submission;mod terminal;pub use ::terminal::HeadlessTerminal;use action_log::{ActionLog, ActionLogTelemetry};@@ -12,7 +13,9 @@ use collections::HashSet;pub use connection::*;pub use diff::*;use feature_flags::{AcpBetaFeatureFlag, FeatureFlagAppExt as _};-use futures::{FutureExt, channel::oneshot, future::BoxFuture};+#[cfg(any(test, feature = "test-support"))]+use futures::future::BoxFuture;+use futures::{FutureExt, channel::oneshot};use gpui::{ActivityGuard, AppContext, AsyncApp, Context, Entity, EventEmitter, SharedString, Subscription,Task, WeakEntity,@@ -41,6 +44,7 @@ use std::process::ExitStatus;use std::rc::Rc;use std::time::{Duration, Instant};use std::{fmt::Display, mem, path::PathBuf, sync::Arc};+pub use submission::*;use task::{Shell, ShellBuilder};pub use terminal::*;use text::Bias;@@ -3273,6 +3277,17 @@ struct RunningTurn {send_task: Task<()>,}+fn stop_reason_from_v1(reason: &acp_v1::StopReason) -> Option<acp_v2::StopReason> {+ Some(match reason {+ acp_v1::StopReason::EndTurn => acp_v2::StopReason::EndTurn,+ acp_v1::StopReason::MaxTokens => acp_v2::StopReason::MaxTokens,+ acp_v1::StopReason::MaxTurnRequests => acp_v2::StopReason::MaxTurnRequests,+ acp_v1::StopReason::Refusal => acp_v2::StopReason::Refusal,+ acp_v1::StopReason::Cancelled => acp_v2::StopReason::Cancelled,+ _ => return None,+ })+}+pub struct AcpThread {session_id: acp_v1::SessionId,work_dirs: Option<PathList>,@@ -3294,6 +3309,8 @@ pub struct AcpThread {turn_id: u32,running_turn: Option<RunningTurn>,connection: Rc<dyn AgentConnection>,+ submissions: SessionSubmissions,+ activity: SessionActivity,token_usage: Option<TokenUsage>,cost: Option<SessionCost>,prompt_capabilities: acp_v1::PromptCapabilities,@@ -3413,6 +3430,7 @@ impl From<&AcpThread> for ActionLogTelemetry {#[derive(Debug)]pub enum AcpThreadEvent {StatusChanged,+ SubmissionUpdated(SubmissionId),PromptUpdated,NewEntry,TitleUpdated,@@ -3427,7 +3445,11 @@ pub enum AcpThreadEvent {ElicitationResponded(ElicitationEntryId),Retry(RetryStatus),SubagentSpawned(acp_v1::SessionId),- Stopped(acp_v1::StopReason),+ Stopped {+ activity_generation: u64,+ activity_duration: Option<Duration>,+ stop_reason: Option<acp_v2::StopReason>,+ },Error,LoadError(LoadError),PromptCapabilitiesUpdated,@@ -3554,8 +3576,12 @@ impl AcpThread {| AcpThreadEvent::ToolAuthorizationRequested(_)| AcpThreadEvent::ToolAuthorizationReceived(_)| AcpThreadEvent::ElicitationRequested(_)- | AcpThreadEvent::ElicitationResponded(_) => this.update_idle_sleep_prevention(cx),+ | AcpThreadEvent::ElicitationResponded(_) => {+ this.sync_legacy_action_state(cx);+ this.update_idle_sleep_prevention(cx);+ }AcpThreadEvent::PromptUpdated+ | AcpThreadEvent::SubmissionUpdated(_)| AcpThreadEvent::NewEntry| AcpThreadEvent::TitleUpdated| AcpThreadEvent::NoticesUpdated@@ -3563,7 +3589,7 @@ impl AcpThread {| AcpThreadEvent::EntryUpdated(_)| AcpThreadEvent::Retry(_)| AcpThreadEvent::SubagentSpawned(_)- | AcpThreadEvent::Stopped(_)+ | AcpThreadEvent::Stopped { .. }| AcpThreadEvent::Error| AcpThreadEvent::LoadError(_)| AcpThreadEvent::PromptCapabilitiesUpdated@@ -3589,6 +3615,7 @@ impl AcpThread {}});+ let receipt_submissions = connection.receipt_submissions(&session_id, cx);Self {parent_session_id,work_dirs,@@ -3607,6 +3634,8 @@ impl AcpThread {project,running_turn: None,turn_id: 0,+ submissions: SessionSubmissions::new(receipt_submissions),+ activity: SessionActivity::default(),connection,session_id,token_usage: None,@@ -3752,18 +3781,48 @@ impl AcpThread {}pub fn status(&self) -> ThreadStatus {- if self.running_turn.is_some() {- ThreadStatus::Generating- } else {- ThreadStatus::Idle+ match self.foreground_activity() {+ ForegroundActivity::Idle => ThreadStatus::Idle,+ _ => ThreadStatus::Generating,}}+ pub fn uses_reported_activity(&self) -> bool {+ self.submissions.receipt_transport().is_some()+ }++ pub fn foreground_state(&self) -> &acp_v2::StateUpdate {+ self.activity.state()+ }++ pub fn foreground_activity(&self) -> ForegroundActivity {+ self.activity.phase()+ }++ pub fn activity_generation(&self) -> u64 {+ self.activity.generation()+ }++ pub fn activity_started_at(&self) -> Option<Instant> {+ self.activity.started_at()+ }++ pub fn activity_duration(&self) -> Option<Duration> {+ self.activity.duration()+ }+pub fn had_error(&self) -> bool {self.had_error}pub fn is_waiting_for_confirmation(&self) -> bool {+ if self.uses_reported_activity() {+ return self.foreground_activity() == ForegroundActivity::RequiresAction;+ }+ self.has_pending_turn_action()+ }++ fn has_pending_turn_action(&self) -> bool {for entry in self.entries.iter().rev() {match entry {AgentThreadEntry::UserMessage(_) => return false,@@ -3790,6 +3849,194 @@ impl AcpThread {self.token_usage.as_ref()}+ pub fn submission(&self, id: SubmissionId) -> Option<&SubmissionRecord> {+ self.submissions.get(id)+ }++ pub fn latest_submission_id(&self) -> Option<SubmissionId> {+ self.submissions.latest_id()+ }++ pub fn has_unsettled_submissions(&self) -> bool {+ self.submissions.has_unsettled()+ }++ pub fn recoverable_submissions(+ &self,+ ) -> impl Iterator<Item = (SubmissionId, &SubmissionRecord)> {+ self.submissions.recoverable()+ }++ pub fn is_idle_for_retention(&self) -> bool {+ self.status() == ThreadStatus::Idle+ && !self.has_unsettled_submissions()+ && self.recoverable_submissions().next().is_none()+ && !self.entries.iter().any(|entry| match entry {+ AgentThreadEntry::ToolCall(call) => call.authorization().is_some(),+ AgentThreadEntry::Elicitation(id) => {+ self.elicitations+ .elicitation(id)+ .is_some_and(|(_, elicitation)| {+ matches!(elicitation.status, ElicitationStatus::Pending { .. })+ })+ }+ _ => false,+ })+ }++ pub fn forget_submission(&mut self, id: SubmissionId, cx: &mut Context<Self>) {+ if self.submissions.forget(id) {+ cx.emit(AcpThreadEvent::SubmissionUpdated(id));+ cx.notify();+ }+ }++ fn register_submission(+ &mut self,+ content: Arc<[acp_v1::ContentBlock]>,+ cx: &mut Context<Self>,+ ) -> SubmissionId {+ let id = self.submissions.register(content);+ cx.emit(AcpThreadEvent::SubmissionUpdated(id));+ cx.notify();+ id+ }++ fn observe_submission_echo(&mut self, message_id: &acp_v2::MessageId, cx: &mut Context<Self>) {+ for id in self.submissions.observe_echo(message_id) {+ cx.emit(AcpThreadEvent::SubmissionUpdated(id));+ }+ cx.notify();+ }++ fn track_submission(+ &mut self,+ id: SubmissionId,+ cx: &mut Context<Self>,+ complete: impl 'static+ + AsyncFnOnce(+ WeakEntity<Self>,+ &mut AsyncApp,+ ) -> Result<Option<SubmissionResponse>>,+ ) -> Submission {+ let (sender, receiver) = oneshot::channel();+ let task = cx.spawn(async move |this, cx| {+ let response = complete(this.clone(), cx).await;+ let update = this.update(cx, |this, cx| {+ let state = match &response {+ Ok(Some(SubmissionResponse::Accepted(receipt))) => {+ let echoed = this.entries.iter().any(|entry| {+ matches!(entry, AgentThreadEntry::UserMessage(message)+ if matches!(&message.identity, MessageIdentity::Keyed(id) if id == &receipt.message_id))+ });+ SubmissionState::Accepted { receipt: receipt.clone(), echoed }+ }+ Ok(Some(SubmissionResponse::LegacyCompleted(_))) => SubmissionState::Completed,+ Ok(None) => SubmissionState::Cancelled,+ Err(error) => SubmissionState::Failed(format!("{error:#}").into()),+ };+ this.submissions.settle(id, state);+ // The thread owns settlement even when the response observer has gone away.+ if let Err(Err(error)) = sender.send(response) {+ log::debug!("Submission observer was dropped: {error:#}");+ }+ cx.emit(AcpThreadEvent::SubmissionUpdated(id));+ cx.notify();+ });+ if let Err(error) = update {+ log::debug!("Submission thread was released: {error:#}");+ }+ });+ self.submissions.track(id, task);+ Submission::new(+ id,+ async move {+ receiver+ .await+ .context("Submission ended before its response was delivered")?+ }+ .boxed(),+ )+ }++ fn set_foreground_state(&mut self, state: acp_v2::StateUpdate, cx: &mut Context<Self>) {+ let previous = self.foreground_activity();+ self.activity+ .update(state, self.entries.len().saturating_sub(1));+ let current = self.foreground_activity();+ if previous == ForegroundActivity::Idle && current != ForegroundActivity::Idle {+ self.had_error = false;+ }+ cx.notify();+ }++ fn sync_legacy_action_state(&mut self, cx: &mut Context<Self>) {+ if self.uses_reported_activity() || self.foreground_activity() == ForegroundActivity::Idle {+ return;+ }+ let desired = if self.has_pending_turn_action() {+ ForegroundActivity::RequiresAction+ } else {+ ForegroundActivity::Running+ };+ if desired != self.foreground_activity() {+ self.set_foreground_state(+ if desired == ForegroundActivity::RequiresAction {+ acp_v2::StateUpdate::RequiresAction(acp_v2::RequiresActionStateUpdate::new())+ } else {+ acp_v2::StateUpdate::Running(acp_v2::RunningStateUpdate::new())+ },+ cx,+ );+ cx.emit(AcpThreadEvent::StatusChanged);+ }+ }++ pub fn update_session_state(+ &mut self,+ state: acp_v2::StateUpdate,+ cx: &mut Context<Self>,+ ) -> Result<()> {+ anyhow::ensure!(+ self.uses_reported_activity(),+ "Session does not report foreground state"+ );+ let previous = self.foreground_activity();+ let was_active = previous != ForegroundActivity::Idle;+ self.set_foreground_state(state, cx);+ if let acp_v2::StateUpdate::Idle(idle) = self.activity.state() {+ let stop_reason = idle.stop_reason.clone();+ if let Some(usage) = &idle.usage {+ let stored = self.token_usage.get_or_insert_with(Default::default);+ stored.input_tokens = usage.input_tokens;+ stored.output_tokens = usage.output_tokens;+ cx.emit(AcpThreadEvent::TokenUsageUpdated);+ }+ if was_active {+ self.flush_streaming_text(cx);+ self.shrink_message_source_capacity(self.activity.first_entry_index());+ if self.parent_session_id.is_none() {+ self.project+ .update(cx, |project, cx| project.set_agent_location(None, cx));+ }+ self.had_error = matches!(+ stop_reason,+ Some(acp_v2::StopReason::MaxTokens | acp_v2::StopReason::Refusal)+ );+ // Reported refusal does not authorize deleting agent-owned history.+ cx.emit(AcpThreadEvent::Stopped {+ activity_generation: self.activity.generation(),+ activity_duration: self.activity.duration(),+ stop_reason,+ });+ }+ }+ if previous != self.foreground_activity() {+ cx.emit(AcpThreadEvent::StatusChanged);+ }+ Ok(())+ }+pub fn cost(&self) -> Option<&SessionCost> {self.cost.as_ref()}@@ -4236,11 +4483,19 @@ impl AcpThread {}fn emit_message_update(- &self,+ &mut self,location: MessageLocation,previous_entry_count: usize,cx: &mut Context<Self>,) {+ if self.uses_reported_activity()+ && let Some(AgentThreadEntry::UserMessage(message)) =+ self.entries.get(location.entry_index())+ && let MessageIdentity::Keyed(id) = &message.identity+ {+ let id = id.clone();+ self.observe_submission_echo(&id, cx);+ }if self.entries.len() > previous_entry_count {cx.emit(AcpThreadEvent::NewEntry);} else {@@ -5359,15 +5614,25 @@ impl AcpThread {message: &str,cx: &mut Context<Self>,) -> BoxFuture<'static, Result<Option<acp_v1::PromptResponse>>> {- self.send(vec![message.into()], cx)+ let submission = self.send(vec![message.into()], cx);+ async move {+ match submission.await? {+ Some(SubmissionResponse::LegacyCompleted(response)) => Ok(Some(response)),+ None => Ok(None),+ Some(SubmissionResponse::Accepted(_)) => {+ Err(anyhow!("Use send to observe receipt-driven submissions"))+ }+ }+ }+ .boxed()}pub fn send(&mut self,message: Vec<acp_v1::ContentBlock>,cx: &mut Context<Self>,- ) -> BoxFuture<'static, Result<Option<acp_v1::PromptResponse>>> {- self.send_inner(message, true, cx)+ ) -> Submission {+ self.submit(message, true, cx)}/// Sends a prompt without displaying a user-message bubble for it.@@ -5378,23 +5643,43 @@ impl AcpThread {&mut self,message: Vec<acp_v1::ContentBlock>,cx: &mut Context<Self>,- ) -> BoxFuture<'static, Result<Option<acp_v1::PromptResponse>>> {- self.send_inner(message, false, cx)+ ) -> Submission {+ self.submit(message, false, cx)+ }++ fn submit(+ &mut self,+ message: Vec<acp_v1::ContentBlock>,+ 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?)))+ })+ } else {+ self.send_inner(id, message, push_user_message, cx)+ }}fn send_inner(&mut self,+ id: SubmissionId,message: Vec<acp_v1::ContentBlock>,push_user_message: bool,cx: &mut Context<Self>,- ) -> BoxFuture<'static, Result<Option<acp_v1::PromptResponse>>> {+ ) -> Submission {let language_registry = self.project.read(cx).languages().clone();let path_style = self.project.read(cx).path_style(cx);let mut block = MessageContent::default();for chunk in &message {let chunk = match content::from_v1(chunk.clone()) {Ok(chunk) => chunk,- Err(error) => return futures::future::ready(Err(error)).boxed(),+ Err(error) => {+ return self.track_submission(id, cx, async move |_, _| Err(error));+ }};block.append_prompt(chunk, &language_registry, path_style, cx);}@@ -5406,7 +5691,7 @@ impl AcpThread {.as_ref().map(|client_user_message_ids| client_user_message_ids.new_id());- self.run_turn(cx, async move |this, cx| {+ self.run_turn(id, cx, async move |this, cx| {if push_user_message {this.update(cx, |this, cx| {this.push_entry(@@ -5452,14 +5737,23 @@ impl AcpThread {}pub fn can_retry(&self, cx: &App) -> bool {- self.connection.retry(&self.session_id, cx).is_some()- }-- pub fn retry(- &mut self,- cx: &mut Context<Self>,- ) -> BoxFuture<'static, Result<Option<acp_v1::PromptResponse>>> {- self.run_turn(cx, async move |this, cx| {+ !self.uses_reported_activity() && self.connection.retry(&self.session_id, cx).is_some()+ }++ pub fn retry(&mut self, cx: &mut Context<Self>) -> Submission {+ let content = self+ .submissions+ .latest_id()+ .and_then(|id| self.submissions.get(id))+ .map(|submission| submission.content.clone())+ .unwrap_or_default();+ let id = self.register_submission(content, cx);+ if self.uses_reported_activity() {+ return self.track_submission(id, cx, async move |_, _| {+ Err(anyhow!("Receipt-driven retry is not supported"))+ });+ }+ self.run_turn(id, cx, async move |this, cx| {this.update(cx, |this, cx| {this.connection.retry(&this.session_id, cx)@@ -5472,9 +5766,10 @@ impl AcpThread {fn run_turn(&mut self,+ id: SubmissionId,cx: &mut Context<Self>,f: impl 'static + AsyncFnOnce(WeakEntity<Self>, &mut AsyncApp) -> Result<acp_v1::PromptResponse>,- ) -> BoxFuture<'static, Result<Option<acp_v1::PromptResponse>>> {+ ) -> Submission {self.clear_completed_plan_entries(cx);self.had_error = false;@@ -5493,6 +5788,10 @@ impl AcpThread {tx.send(f(this, cx).await).ok();}),});+ self.set_foreground_state(+ acp_v2::StateUpdate::Running(acp_v2::RunningStateUpdate::new()),+ cx,+ );cx.emit(AcpThreadEvent::StatusChanged);let completion = async move |thread: WeakEntity<Self>, cx: &mut AsyncApp| {@@ -5526,6 +5825,10 @@ impl AcpThread {// state even when the send_task is cancelled before tx.send().if is_same_turn {this.running_turn.take();+ this.set_foreground_state(+ acp_v2::StateUpdate::Idle(acp_v2::IdleStateUpdate::new()),+ cx,+ );}if this.turn_id == turn_id {@@ -5629,7 +5932,18 @@ impl AcpThread {if is_same_turn {cx.emit(AcpThreadEvent::StatusChanged);}- cx.emit(AcpThreadEvent::Stopped(r.stop_reason));+ let stop_reason = stop_reason_from_v1(&r.stop_reason);+ this.set_foreground_state(+ acp_v2::StateUpdate::Idle(+ acp_v2::IdleStateUpdate::new().stop_reason(stop_reason.clone()),+ ),+ cx,+ );+ cx.emit(AcpThreadEvent::Stopped {+ activity_generation: this.activity.generation(),+ activity_duration: this.activity.duration(),+ stop_reason,+ });Ok(Some(r))}Err(e) => {@@ -5648,12 +5962,11 @@ impl AcpThread {}})?};- let (completion_tx, completion_rx) = oneshot::channel();- cx.spawn(async move |thread, cx| {- completion_tx.send(completion(thread, cx).await).ok();+ self.track_submission(id, cx, async move |thread, cx| {+ Ok(completion(thread, cx)+ .await?+ .map(SubmissionResponse::LegacyCompleted))})- .detach();- async move { completion_rx.await? }.boxed()}pub fn cancel(&mut self, cx: &mut Context<Self>) -> Task<()> {@@ -5666,6 +5979,17 @@ impl AcpThread {cx: &mut Context<Self>,) -> Task<()> {self.flush_streaming_text(cx);+ if self.uses_reported_activity() {+ let Some(receiver) = self.activity.wait_for_idle() 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");+ }+ });+ }self.cancel_outstanding_elicitations(cx);let Some(turn) = self.running_turn.take() else {@@ -5674,6 +5998,10 @@ 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.set_foreground_state(+ acp_v2::StateUpdate::Idle(acp_v2::IdleStateUpdate::new()),+ cx,+ );cx.emit(AcpThreadEvent::StatusChanged);// Wait for the send task to complete@@ -5682,8 +6010,7 @@ impl AcpThread {fn update_idle_sleep_prevention(&mut self, cx: &mut Context<Self>) {if !AgentSettings::get_global(cx).prevent_idle_sleep- || self.running_turn.is_none()- || self.is_waiting_for_confirmation()+ || self.foreground_activity() != ForegroundActivity::Running{self.idle_sleep_prevention = IdleSleepPrevention::Inactive;return;@@ -9054,6 +9381,521 @@ mod tests {}}+ async fn new_receipt_test_thread(+ cx: &mut TestAppContext,+ ) -> (Entity<AcpThread>, Rc<StubAgentConnection>) {+ let project = Project::test(FakeFs::new(cx.executor()), [], cx).await;+ let connection = Rc::new(StubAgentConnection::new().with_receipt_submissions(true));+ let thread = cx+ .update(|cx| {+ connection.clone().new_session(+ project,+ PathList::new(&[Path::new(path!("/test"))]),+ cx,+ )+ })+ .await+ .expect("receipt session should be created");+ (thread, connection)+ }++ #[gpui::test]+ async fn test_receipt_and_echo_correlate_by_id_without_owning_history_or_activity(+ cx: &mut TestAppContext,+ ) {+ init_test(cx);+ let (thread, connection) = new_receipt_test_thread(cx).await;+ let stopped = Rc::new(RefCell::new(Vec::new()));+ let legacy_errors = Rc::new(RefCell::new(0));+ let _subscription = cx.update(|cx| {+ cx.subscribe(&thread, {+ let stopped = stopped.clone();+ let legacy_errors = legacy_errors.clone();+ move |_, event, _| match event {+ AcpThreadEvent::Stopped {+ activity_generation,+ stop_reason,+ ..+ } => {+ stopped+ .borrow_mut()+ .push((*activity_generation, stop_reason.clone()));+ }+ AcpThreadEvent::Refusal | AcpThreadEvent::Error => {+ *legacy_errors.borrow_mut() += 1;+ }+ _ => {}+ }+ })+ });++ let first_sender = connection.defer_next_receipt_response();+ let first = thread.update(cx, |thread, cx| thread.send(vec!["outgoing".into()], cx));+ let first_id = first.id;+ thread.read_with(cx, |thread, _| {+ assert_eq!(thread.latest_submission_id(), Some(first_id));+ assert!(matches!(+ thread.submission(first_id).expect("first").state,+ SubmissionState::Pending+ ));+ assert_eq!(+ thread.submission(first_id).expect("first").content.as_ref(),+ &["outgoing".into()]+ );+ assert!(thread.entries().is_empty());+ assert!(thread.has_unsettled_submissions());+ assert!(!thread.is_idle_for_retention());+ assert_eq!(thread.foreground_activity(), ForegroundActivity::Idle);+ assert_eq!(thread.activity_generation(), 0);+ });+ thread.update(cx, |thread, cx| {+ thread+ .upsert_user_message(+ acp_v2::UserMessage::new("first-id").content(vec!["normalized".into()]),+ cx,+ )+ .expect("echo before receipt");+ });+ let receipt_meta = acp_v2::Meta::from_iter([("receipt".into(), json!("opaque"))]);+ first_sender+ .send(Ok(+ acp_v2::PromptResponse::new("first-id").meta(receipt_meta.clone())+ ))+ .expect("first receipt receiver");+ assert!(matches!(+ first.await.expect("first response"),+ Some(SubmissionResponse::Accepted(_))+ ));+ thread.read_with(cx, |thread, cx| {+ let (identity, content, meta) = only_keyed_message(thread);+ assert_eq!(*identity, MessageIdentity::Keyed("first-id".into()));+ assert_eq!(content.to_markdown(cx), "normalized");+ assert_ne!(meta.as_ref(), Some(&receipt_meta));+ assert!(matches!(+ &thread.submission(first_id).expect("first").state,+ SubmissionState::Accepted { receipt, echoed: true }+ if receipt.message_id == "first-id".into() && receipt.meta.as_ref() == Some(&receipt_meta)+ ));+ assert!(!thread.has_unsettled_submissions());+ assert_eq!(thread.foreground_activity(), ForegroundActivity::Idle);+ });++ let second_sender = connection.defer_next_receipt_response();+ let second = thread.update(cx, |thread, cx| thread.send(vec!["normalized".into()], cx));+ let second_id = second.id;+ second_sender+ .send(Ok(acp_v2::PromptResponse::new("second-id")))+ .expect("second receipt receiver");+ assert!(matches!(+ second.await.expect("second response"),+ Some(SubmissionResponse::Accepted(_))+ ));+ thread.read_with(cx, |thread, _| {+ assert!(matches!(+ thread.submission(second_id).expect("second").state,+ SubmissionState::Accepted { echoed: false, .. }+ ));+ assert_eq!(thread.entries().len(), 1);+ assert!(thread.has_unsettled_submissions());+ });+ thread.update(cx, |thread, cx| {+ thread+ .update_session_state(+ acp_v2::StateUpdate::Running(+ acp_v2::RunningStateUpdate::new()+ .meta(acp_v2::Meta::from_iter([("future".into(), json!(42))])),+ ),+ cx,+ )+ .expect("running");+ });+ thread.read_with(cx, |thread, _| {+ assert_eq!(thread.activity_generation(), 1);+ assert!(thread.activity_started_at().is_some());+ assert!(thread.activity_duration().is_some());+ assert!(+ matches!(thread.foreground_state(), acp_v2::StateUpdate::Running(running)+ if running.meta.as_ref().and_then(|meta| meta.get("future")) == Some(&json!(42)))+ );+ });+ let late_sender = connection.defer_next_receipt_response();+ let late = thread.update(cx, |thread, cx| {+ thread.send(vec!["late receipt".into()], cx)+ });+ let late_id = late.id;+ thread.update(cx, |thread, cx| {+ thread.forget_submission(late_id, cx);+ assert!(+ thread.submission(late_id).is_some(),+ "pending receipt cannot be forgotten"+ );+ });+ thread.update(cx, |thread, cx| {+ 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();+ thread.read_with(cx, |thread, _| {+ assert!(thread.had_error());+ assert_eq!(thread.entries().len(), 1);+ assert_eq!(thread.foreground_activity(), ForegroundActivity::Idle);+ assert!(thread.activity_duration().is_some());+ assert!(!thread.is_idle_for_retention());+ assert!(matches!(+ thread.submission(late_id).expect("late").state,+ SubmissionState::Pending+ ));+ assert!(+ matches!(thread.foreground_state(), acp_v2::StateUpdate::Idle(idle)+ if idle.stop_reason == Some(acp_v2::StopReason::Refusal))+ );+ });+ assert_eq!(*stopped.borrow(), [(1, Some(acp_v2::StopReason::Refusal))]);+ assert_eq!(*legacy_errors.borrow(), 0);+ late_sender+ .send(Ok(acp_v2::PromptResponse::new("late-id")))+ .expect("late receipt receiver");+ assert!(matches!(+ late.await.expect("late response"),+ Some(SubmissionResponse::Accepted(_))+ ));+ thread.read_with(cx, |thread, _| {+ assert_eq!(thread.foreground_activity(), ForegroundActivity::Idle);+ assert!(matches!(+ thread.submission(late_id).expect("late").state,+ SubmissionState::Accepted { echoed: false, .. }+ ));+ });+ thread.update(cx, |thread, cx| {+ thread+ .update_session_state(+ acp_v2::StateUpdate::Idle(+ acp_v2::IdleStateUpdate::new().stop_reason(acp_v2::StopReason::Refusal),+ ),+ cx,+ )+ .expect("duplicate idle");+ thread+ .upsert_user_message(+ acp_v2::UserMessage::new("second-id").content(vec!["normalized".into()]),+ cx,+ )+ .expect("echo after receipt");+ thread+ .upsert_user_message(+ acp_v2::UserMessage::new("late-id").content(vec!["agent late echo".into()]),+ cx,+ )+ .expect("echo after late receipt");+ });+ cx.run_until_parked();+ assert_eq!(*stopped.borrow(), [(1, Some(acp_v2::StopReason::Refusal))]);+ thread.read_with(cx, |thread, _| {+ assert_eq!(thread.entries().len(), 3);+ assert!(+ thread.submission(second_id).is_none(),+ "older echoed receipt is pruned"+ );+ assert!(matches!(+ thread.submission(late_id).expect("late").state,+ SubmissionState::Accepted { echoed: true, .. }+ ));+ assert!(thread.recoverable_submissions().next().is_none());+ assert!(!thread.has_unsettled_submissions());+ assert!(thread.is_idle_for_retention());+ });+ thread.update(cx, |thread, cx| {+ thread+ .update_session_state(+ acp_v2::StateUpdate::Running(acp_v2::RunningStateUpdate::new()),+ cx,+ )+ .expect("second running generation");+ assert_eq!(thread.activity_generation(), 2);+ assert_eq!(thread.latest_submission_id(), Some(late_id));+ thread+ .update_session_state(+ acp_v2::StateUpdate::Idle(+ acp_v2::IdleStateUpdate::new().stop_reason(acp_v2::StopReason::MaxTokens),+ ),+ cx,+ )+ .expect("max tokens");+ assert!(thread.had_error());+ assert_eq!(thread.latest_submission_id(), Some(late_id));+ assert!(matches!(+ thread.submission(late_id).expect("late").state,+ SubmissionState::Accepted { echoed: true, .. }+ ));+ assert!(thread.recoverable_submissions().next().is_none());+ thread+ .update_session_state(+ acp_v2::StateUpdate::Idle(+ acp_v2::IdleStateUpdate::new().stop_reason(acp_v2::StopReason::MaxTokens),+ ),+ cx,+ )+ .expect("duplicate max tokens idle");+ });+ cx.run_until_parked();+ assert_eq!(+ *stopped.borrow(),+ [+ (1, Some(acp_v2::StopReason::Refusal)),+ (2, Some(acp_v2::StopReason::MaxTokens)),+ ]+ );+ assert_eq!(*legacy_errors.borrow(), 0);+ thread.update(cx, |thread, cx| {+ thread.forget_submission(late_id, cx);+ assert!(thread.submission(late_id).is_none());+ assert_eq!(thread.latest_submission_id(), None);+ assert_eq!(thread.entries().len(), 3);+ });+ }++ #[gpui::test]+ async fn test_reported_activity_survives_rejection_and_idle_keeps_unrelated_actions(+ cx: &mut TestAppContext,+ ) {+ init_test(cx);+ let (thread, connection) = 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("autonomous running");+ });+ cx.run_until_parked();+ assert_eq!(cx.active_idle_sleep_preventions(), 1);+ thread.read_with(cx, |thread, _| {+ assert!(!thread.is_waiting_for_confirmation());+ assert_eq!(thread.activity_generation(), 1);+ });+ let rejected_sender = connection.defer_next_receipt_response();+ let rejected = thread.update(cx, |thread, cx| thread.send(vec!["reject me".into()], cx));+ let rejected_id = rejected.id;+ let pending_sender = connection.defer_next_receipt_response();+ let pending = thread.update(cx, |thread, cx| thread.send(vec!["pending".into()], cx));+ let pending_id = pending.id;+ thread.read_with(cx, |thread, _| {+ assert_eq!(thread.latest_submission_id(), Some(pending_id));+ assert_eq!(+ thread+ .recoverable_submissions()+ .map(|(id, _)| id)+ .collect::<Vec<_>>(),+ [rejected_id, pending_id],+ );+ });+ rejected_sender+ .send(Err(anyhow!("agent rejected: quota")))+ .expect("rejection receiver");+ assert!(+ rejected+ .await+ .expect_err("rejection must reach caller")+ .to_string()+ .contains("agent rejected: quota")+ );+ thread.read_with(cx, |thread, _| {+ let rejected_record = thread.submission(rejected_id).expect("rejected");+ assert!(matches!(&rejected_record.state,+ SubmissionState::Failed(error) if error.contains("agent rejected: quota")));+ assert_eq!(rejected_record.content.as_ref(), &["reject me".into()]);+ assert_eq!(thread.latest_submission_id(), Some(pending_id));+ assert_eq!(+ thread+ .recoverable_submissions()+ .map(|(id, _)| id)+ .collect::<Vec<_>>(),+ [rejected_id, pending_id],+ );+ assert_eq!(thread.foreground_activity(), ForegroundActivity::Running);+ assert!(thread.has_unsettled_submissions());+ assert!(!thread.is_idle_for_retention());+ });+ thread.update(cx, |thread, cx| {+ thread+ .update_session_state(+ acp_v2::StateUpdate::RequiresAction(acp_v2::RequiresActionStateUpdate::new()),+ cx,+ )+ .expect("requires action");+ });+ cx.run_until_parked();+ assert_eq!(cx.active_idle_sleep_preventions(), 0);+ assert!(thread.read_with(cx, |thread, _| thread.is_waiting_for_confirmation()));+ thread.update(cx, |thread, cx| {+ thread+ .update_session_state(+ acp_v2::StateUpdate::Running(acp_v2::RunningStateUpdate::new()),+ cx,+ )+ .expect("resume running");+ });+ cx.run_until_parked();+ assert_eq!(cx.active_idle_sleep_preventions(), 1);+ assert_eq!(+ thread.read_with(cx, |thread, _| thread.activity_generation()),+ 1+ );++ let tool_call_id = acp_v1::ToolCallId::new("unrelated-permission");+ let permission = request_test_permission(&thread, tool_call_id.clone(), cx);+ let cancelled = Rc::new(std::cell::Cell::new(false));+ cx.update(|cx| {+ let cancel = thread.update(cx, |thread, cx| thread.cancel(cx));+ cx.spawn({+ let cancelled = cancelled.clone();+ async move |_| {+ cancel.await;+ cancelled.set(true);+ }+ })+ .detach();+ });+ cx.run_until_parked();+ assert!(!cancelled.get());+ assert_eq!(+ thread.read_with(cx, |thread, _| thread.foreground_activity()),+ ForegroundActivity::Running+ );+ thread.update(cx, |thread, cx| {+ thread+ .update_session_state(+ acp_v2::StateUpdate::Idle(acp_v2::IdleStateUpdate::new()),+ cx,+ )+ .expect("reported idle");+ });+ cx.run_until_parked();+ assert!(cancelled.get());+ assert_eq!(cx.active_idle_sleep_preventions(), 0);+ thread.read_with(cx, |thread, _| {+ assert!(thread.has_unsettled_submissions());+ assert!(!thread.is_idle_for_retention());+ assert!(thread.entries().iter().any(|entry| matches!(entry,+ AgentThreadEntry::ToolCall(call) if call.authorization().is_some())));+ });+ pending_sender+ .send(Ok(acp_v2::PromptResponse::new("pending-id")))+ .expect("pending receipt receiver");+ assert!(matches!(+ pending.await.expect("pending response"),+ Some(SubmissionResponse::Accepted(_))+ ));+ thread.update(cx, |thread, cx| {+ thread+ .upsert_user_message(+ acp_v2::UserMessage::new("pending-id").content(vec!["agent echo".into()]),+ cx,+ )+ .expect("pending echo");+ });+ thread.read_with(cx, |thread, _| {+ assert!(!thread.has_unsettled_submissions());+ assert_eq!(+ thread+ .recoverable_submissions()+ .map(|(id, _)| id)+ .collect::<Vec<_>>(),+ [rejected_id],+ );+ assert!(!thread.is_idle_for_retention());+ });+ thread.update(cx, |thread, cx| {+ thread.authorize_tool_call(+ tool_call_id,+ SelectedPermissionOutcome::new(+ acp_v1::PermissionOptionId::new("allow"),+ acp_v1::PermissionOptionKind::AllowOnce,+ ),+ cx,+ );+ });+ assert!(matches!(+ permission.await,+ RequestPermissionOutcome::Selected(_)+ ));+ thread.update(cx, |thread, cx| {+ assert!(+ !thread.is_idle_for_retention(),+ "failed submission still needs recovery"+ );+ assert_eq!(+ thread+ .submission(rejected_id)+ .expect("recoverable failure")+ .content+ .as_ref(),+ &["reject me".into()]+ );+ thread.forget_submission(rejected_id, cx);+ assert!(thread.submission(rejected_id).is_none());+ assert!(thread.recoverable_submissions().next().is_none());+ assert!(thread.is_idle_for_retention());+ });+ }++ #[gpui::test]+ async fn test_receipt_settlement_survives_observer_drop_without_retaining_thread(+ cx: &mut TestAppContext,+ ) {+ init_test(cx);+ let (thread, connection) = new_receipt_test_thread(cx).await;+ let sender = connection.defer_next_receipt_response();+ let submission = thread.update(cx, |thread, cx| thread.send(vec!["unobserved".into()], cx));+ let id = submission.id;+ drop(submission);+ sender+ .send(Ok(acp_v2::PromptResponse::new("unobserved-id")))+ .expect("unobserved receipt receiver");+ cx.run_until_parked();+ thread.read_with(cx, |thread, _| {+ assert!(matches!(&thread.submission(id).expect("settled").state,+ SubmissionState::Accepted { receipt, echoed: false }+ if receipt.message_id == "unobserved-id".into()));+ assert_eq!(+ thread+ .recoverable_submissions()+ .map(|(id, _)| id)+ .collect::<Vec<_>>(),+ [id]+ );+ assert!(!thread.is_idle_for_retention());+ });++ let pending_sender = connection.defer_next_receipt_response();+ let pending = thread.update(cx, |thread, cx| thread.send(vec!["abandoned".into()], cx));+ thread.read_with(cx, |thread, _| {+ assert_eq!(+ thread+ .recoverable_submissions()+ .map(|(id, _)| id)+ .collect::<Vec<_>>(),+ [id, pending.id],+ );+ });+ let weak_thread = thread.downgrade();+ drop(pending);+ drop(thread);+ cx.run_until_parked();+ assert!(+ weak_thread.upgrade().is_none(),+ "pending receipt must not retain the thread"+ );+ drop(pending_sender);+ }+#[gpui::test]async fn test_keyed_messages_keep_first_seen_order_across_interleaved_updates(cx: &mut TestAppContext,@@ -13823,7 +14665,10 @@ mod tests {.await.expect("first turn should succeed").expect("first turn should return a response");- assert_eq!(response.stop_reason, acp_v1::StopReason::EndTurn);+ assert!(+ matches!(response, SubmissionResponse::LegacyCompleted(response)+ if response.stop_reason == acp_v1::StopReason::EndTurn)+ );let session_id = thread.read_with(cx, |thread, _| thread.session_id().clone());let url_elicitation_id = acp_v1::ElicitationId::new("url-1");@@ -13867,7 +14712,10 @@ mod tests {.await.expect("second turn should succeed").expect("second turn should return a response");- assert_eq!(response.stop_reason, acp_v1::StopReason::Cancelled);+ assert!(+ matches!(response, SubmissionResponse::LegacyCompleted(response)+ if response.stop_reason == acp_v1::StopReason::Cancelled)+ );thread.read_with(cx, |thread, _| {let Some((_, elicitation)) = thread.elicitation(&entry_id) else {panic!("missing elicitation entry");@@ -16580,7 +17428,8 @@ mod tests {})});let request = thread.update(cx, |thread, cx| {- thread.run_turn(cx, {+ let id = thread.register_submission(Arc::from([]), cx);+ thread.run_turn(id, cx, {let backend_finished = backend_finished.clone();async move |_, _| {completion.await?;@@ -16596,6 +17445,7 @@ mod tests {);assert!(!backend_finished.load(SeqCst));+ let submission_id = request.id;drop(request);cx.run_until_parked();assert_eq!(@@ -16614,6 +17464,15 @@ mod tests {*statuses.borrow(),vec![ThreadStatus::Generating, ThreadStatus::Idle]);+ thread.read_with(cx, |thread, _| {+ assert!(matches!(+ thread+ .submission(submission_id)+ .expect("settled submission")+ .state,+ SubmissionState::Completed,+ ));+ });}#[gpui::test]@@ -17741,9 +18600,22 @@ mod tests {) {let (complete, completion) = oneshot::channel::<Result<acp_v1::PromptResponse>>();let request = thread.update(cx, |thread, cx| {- thread.run_turn(cx, async move |_, _| completion.await?)- });- (complete, request)+ let id = thread.register_submission(Arc::from([]), cx);+ thread.run_turn(id, cx, async move |_, _| completion.await?)+ });+ (+ complete,+ async move {+ match request.await? {+ Some(SubmissionResponse::LegacyCompleted(response)) => Ok(Some(response)),+ None => Ok(None),+ Some(SubmissionResponse::Accepted(_)) => {+ Err(anyhow!("Expected legacy test turn completion"))+ }+ }+ }+ .boxed(),+ )}fn request_test_permission(@@ -17852,7 +18724,7 @@ mod tests {let event = match event {AcpThreadEvent::StatusChanged => "status changed",AcpThreadEvent::EntriesRemoved(_) => "entries removed",- AcpThreadEvent::Stopped(_) => "stopped",+ AcpThreadEvent::Stopped { .. } => "stopped",AcpThreadEvent::Refusal => "refusal",AcpThreadEvent::Error => "error",_ => return,diff --git a/crates/acp_thread/src/connection.rs b/crates/acp_thread/src/connection.rsindex d5260036cfe..2c1f0ce5c17 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;+use agent_client_protocol::schema::{v1 as acp_v1, v2 as acp_v2};use anyhow::Result;use chrono::{DateTime, Utc};use collections::{HashMap, HashSet, IndexMap};@@ -192,6 +192,14 @@ pub trait AgentConnection {None}+ fn receipt_submissions(+ &self,+ _session_id: &acp_v1::SessionId,+ _cx: &App,+ ) -> Option<Rc<dyn ReceiptSessionSubmissions>> {+ None+ }+fn prompt(&self,params: acp_v1::PromptRequest,@@ -292,6 +300,16 @@ pub trait AgentSessionClientUserMessageIds {) -> Task<Result<acp_v1::PromptResponse>>;}+/// A session-bound prompt transport whose response acknowledges acceptance, not completion.+/// Implementations must report foreground state separately through `AcpThread::update_session_state`.+pub trait ReceiptSessionSubmissions {+ fn prompt(+ &self,+ content: Vec<acp_v1::ContentBlock>,+ cx: &mut App,+ ) -> Task<Result<acp_v2::PromptResponse>>;+}+pub trait AgentSessionRetry {fn run(&self, cx: &mut App) -> Task<Result<acp_v1::PromptResponse>>;}@@ -697,12 +715,12 @@ impl PermissionOptions {}}-#[cfg(feature = "test-support")]+#[cfg(any(test, feature = "test-support"))]mod test_support {//! Test-only stubs and helpers for acp_thread.//!- //! This module is gated by the `test-support` feature and is not included- //! in production builds. It provides:+ //! This module is available to unit tests and the `test-support` feature,+ //! but not production builds. It provides://! - `StubAgentConnection` for mocking agent connections in tests//! - `create_test_png_base64` for generating test images@@ -768,7 +786,10 @@ mod test_support {permission_requests: HashMap<acp_v1::ToolCallId, PermissionOptions>,next_prompt_updates: Arc<Mutex<Vec<acp_v1::SessionUpdate>>>,next_prompt_response: Arc<Mutex<Option<oneshot::Receiver<Result<acp_v1::PromptResponse>>>>>,+ next_receipt_response:+ Arc<Mutex<Option<oneshot::Receiver<Result<acp_v2::PromptResponse>>>>>,next_truncate: Arc<Mutex<Option<oneshot::Receiver<()>>>>,+ supports_receipt_submissions: bool,supports_load_session: bool,supports_session_additional_directories: bool,supports_set_title: bool,@@ -792,9 +813,11 @@ mod test_support {Self {next_prompt_updates: Default::default(),next_prompt_response: Default::default(),+ next_receipt_response: Default::default(),next_truncate: Default::default(),permission_requests: HashMap::default(),sessions: Arc::default(),+ supports_receipt_submissions: false,supports_load_session: false,supports_session_additional_directories: false,supports_set_title: true,@@ -815,6 +838,19 @@ mod test_support {sender}+ pub fn defer_next_receipt_response(+ &self,+ ) -> oneshot::Sender<Result<acp_v2::PromptResponse>> {+ let (sender, receiver) = oneshot::channel();+ assert!(+ self.next_receipt_response+ .lock()+ .replace(receiver)+ .is_none()+ );+ sender+ }+pub fn defer_next_truncate(&self) -> oneshot::Sender<()> {let (sender, receiver) = oneshot::channel();assert!(self.next_truncate.lock().replace(receiver).is_none());@@ -834,6 +870,11 @@ mod test_support {self}+ pub fn with_receipt_submissions(mut self, enabled: bool) -> Self {+ self.supports_receipt_submissions = enabled;+ self+ }+pub fn with_supports_session_additional_directories(mut self,supports_session_additional_directories: bool,@@ -1061,6 +1102,20 @@ mod test_support {}))}+ fn receipt_submissions(+ &self,+ session_id: &acp_v1::SessionId,+ _cx: &App,+ ) -> Option<Rc<dyn ReceiptSessionSubmissions>> {+ self.supports_receipt_submissions.then(|| {+ Rc::new(StubReceiptSessionSubmissions {+ session_id: session_id.clone(),+ sessions: self.sessions.clone(),+ next_receipt_response: self.next_receipt_response.clone(),+ }) as Rc<dyn ReceiptSessionSubmissions>+ })+ }+fn cancel(&self, session_id: &acp_v1::SessionId, _cx: &mut App) {if let Some(end_turn_tx) = self.sessions@@ -1122,6 +1177,29 @@ mod test_support {}}+ struct StubReceiptSessionSubmissions {+ session_id: acp_v1::SessionId,+ sessions: Arc<Mutex<HashMap<acp_v1::SessionId, Session>>>,+ next_receipt_response:+ Arc<Mutex<Option<oneshot::Receiver<Result<acp_v2::PromptResponse>>>>>,+ }++ impl ReceiptSessionSubmissions for StubReceiptSessionSubmissions {+ fn prompt(+ &self,+ _content: Vec<acp_v1::ContentBlock>,+ cx: &mut App,+ ) -> Task<Result<acp_v2::PromptResponse>> {+ if !self.sessions.lock().contains_key(&self.session_id) {+ return Task::ready(Err(anyhow::Error::msg("Unknown receipt session")));+ }+ match self.next_receipt_response.lock().take() {+ Some(receiver) => cx.spawn(async move |_| Ok(receiver.await??)),+ None => Task::ready(Err(anyhow::Error::msg("No deferred receipt response"))),+ }+ }+ }+struct StubAgentSessionEditor {next_truncate: Arc<Mutex<Option<oneshot::Receiver<()>>>>,}@@ -1184,5 +1262,5 @@ mod test_support {}}-#[cfg(feature = "test-support")]+#[cfg(any(test, feature = "test-support"))]pub use test_support::*;diff --git a/crates/acp_thread/src/submission.rs b/crates/acp_thread/src/submission.rsnew file mode 100644index 00000000000..19e1dd9e861--- /dev/null+++ b/crates/acp_thread/src/submission.rs@@ -0,0 +1,296 @@+use crate::ReceiptSessionSubmissions;+use agent_client_protocol::schema::{v1 as acp_v1, v2 as acp_v2};+use futures::{channel::oneshot, future::BoxFuture};+use gpui::{SharedString, Task};+use std::collections::BTreeMap;+use std::{+ fmt,+ future::Future,+ pin::Pin,+ rc::Rc,+ sync::Arc,+ task::{Context, Poll},+ time::{Duration, Instant},+};++#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]+pub struct SubmissionId(pub(crate) u64);++impl SubmissionId {+ pub fn as_u64(self) -> u64 {+ self.0+ }+}++#[derive(Debug)]+pub enum SubmissionResponse {+ LegacyCompleted(acp_v1::PromptResponse),+ Accepted(acp_v2::PromptResponse),+}++pub struct Submission {+ pub id: SubmissionId,+ pub response: BoxFuture<'static, anyhow::Result<Option<SubmissionResponse>>>,+}++impl Submission {+ pub(crate) fn new(+ id: SubmissionId,+ response: BoxFuture<'static, anyhow::Result<Option<SubmissionResponse>>>,+ ) -> Self {+ Self { id, response }+ }+}++impl Future for Submission {+ type Output = anyhow::Result<Option<SubmissionResponse>>;++ fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {+ self.get_mut().response.as_mut().poll(cx)+ }+}++#[derive(Debug)]+pub enum SubmissionState {+ Pending,+ Accepted {+ receipt: acp_v2::PromptResponse,+ echoed: bool,+ },+ Completed,+ Failed(SharedString),+ Cancelled,+}++pub struct SubmissionRecord {+ pub content: Arc<[acp_v1::ContentBlock]>,+ pub state: SubmissionState,+ task: Option<Task<()>>,+}++impl fmt::Debug for SubmissionRecord {+ fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {+ formatter+ .debug_struct("SubmissionRecord")+ .field("content", &self.content)+ .field("state", &self.state)+ .finish_non_exhaustive()+ }+}++impl SubmissionRecord {+ fn is_unsettled(&self) -> bool {+ matches!(+ self.state,+ SubmissionState::Pending | SubmissionState::Accepted { echoed: false, .. }+ )+ }++ fn is_recoverable(&self) -> bool {+ self.is_unsettled()+ || matches!(+ self.state,+ SubmissionState::Failed(_) | SubmissionState::Cancelled+ )+ }+}++pub(crate) struct SessionSubmissions {+ receipt_transport: Option<Rc<dyn ReceiptSessionSubmissions>>,+ records: BTreeMap<SubmissionId, SubmissionRecord>,+ next_id: u64,+ latest_id: Option<SubmissionId>,+}++impl SessionSubmissions {+ pub(crate) fn new(receipt_transport: Option<Rc<dyn ReceiptSessionSubmissions>>) -> Self {+ Self {+ receipt_transport,+ records: BTreeMap::default(),+ next_id: 0,+ latest_id: None,+ }+ }++ pub(crate) fn receipt_transport(&self) -> Option<&Rc<dyn ReceiptSessionSubmissions>> {+ self.receipt_transport.as_ref()+ }++ pub(crate) fn get(&self, id: SubmissionId) -> Option<&SubmissionRecord> {+ self.records.get(&id)+ }++ pub(crate) fn latest_id(&self) -> Option<SubmissionId> {+ self.latest_id+ }++ pub(crate) fn has_unsettled(&self) -> bool {+ self.records.values().any(SubmissionRecord::is_unsettled)+ }++ pub(crate) fn recoverable(&self) -> impl Iterator<Item = (SubmissionId, &SubmissionRecord)> {+ self.records.iter().filter_map(|(id, record)| {+ (self.receipt_transport.is_some() && record.is_recoverable()).then_some((*id, record))+ })+ }++ pub(crate) fn register(&mut self, content: Arc<[acp_v1::ContentBlock]>) -> SubmissionId {+ self.next_id += 1;+ let id = SubmissionId(self.next_id);+ self.latest_id = Some(id);+ self.prune();+ self.records.insert(+ id,+ SubmissionRecord {+ content,+ state: SubmissionState::Pending,+ task: None,+ },+ );+ id+ }++ pub(crate) fn track(&mut self, id: SubmissionId, task: Task<()>) {+ if let Some(record) = self.records.get_mut(&id) {+ record.task = Some(task);+ }+ }++ pub(crate) fn settle(&mut self, id: SubmissionId, state: SubmissionState) {+ if let Some(record) = self.records.get_mut(&id) {+ record.state = state;+ }+ self.prune();+ }++ pub(crate) fn observe_echo(&mut self, message_id: &acp_v2::MessageId) -> Vec<SubmissionId> {+ let mut changed = Vec::new();+ for (id, record) in &mut self.records {+ if let SubmissionState::Accepted { receipt, echoed } = &mut record.state+ && &receipt.message_id == message_id+ && !*echoed+ {+ *echoed = true;+ changed.push(*id);+ }+ }+ self.prune();+ changed+ }++ pub(crate) fn forget(&mut self, id: SubmissionId) -> bool {+ if self+ .records+ .get(&id)+ .is_some_and(SubmissionRecord::is_unsettled)+ {+ return false;+ }+ if self.records.remove(&id).is_none() {+ return false;+ }+ if self.latest_id == Some(id) {+ self.latest_id = None;+ }+ true+ }++ fn prune(&mut self) {+ self.records.retain(|id, record| {+ Some(*id) == self.latest_id+ || record.is_unsettled()+ || (self.receipt_transport.is_some() && record.is_recoverable())+ });+ }+}++#[derive(Copy, Clone, Debug, PartialEq, Eq)]+pub enum ForegroundActivity {+ Idle,+ Running,+ RequiresAction,+}++pub(crate) struct SessionActivity {+ state: acp_v2::StateUpdate,+ generation: u64,+ started_at: Option<Instant>,+ duration: Option<Duration>,+ first_entry_index: usize,+ cancel_waiters: Vec<oneshot::Sender<()>>,+}++impl Default for SessionActivity {+ fn default() -> Self {+ Self {+ state: acp_v2::StateUpdate::Idle(acp_v2::IdleStateUpdate::new()),+ generation: 0,+ started_at: None,+ duration: None,+ first_entry_index: 0,+ cancel_waiters: Vec::new(),+ }+ }+}++impl SessionActivity {+ pub(crate) fn state(&self) -> &acp_v2::StateUpdate {+ &self.state+ }++ pub(crate) fn phase(&self) -> ForegroundActivity {+ match self.state {+ acp_v2::StateUpdate::Idle(_) => ForegroundActivity::Idle,+ acp_v2::StateUpdate::RequiresAction(_) => ForegroundActivity::RequiresAction,+ _ => ForegroundActivity::Running,+ }+ }++ pub(crate) fn generation(&self) -> u64 {+ self.generation+ }++ pub(crate) fn started_at(&self) -> Option<Instant> {+ self.started_at+ }++ pub(crate) fn duration(&self) -> Option<Duration> {+ if self.phase() == ForegroundActivity::Idle {+ self.duration+ } else {+ self.started_at.map(|started| started.elapsed())+ }+ }++ pub(crate) fn first_entry_index(&self) -> usize {+ self.first_entry_index+ }++ pub(crate) fn update(&mut self, state: acp_v2::StateUpdate, first_entry_index: usize) {+ let previous = self.phase();+ self.state = state;+ let current = self.phase();+ if previous == ForegroundActivity::Idle && current != ForegroundActivity::Idle {+ self.generation += 1;+ self.started_at = Some(Instant::now());+ self.duration = None;+ self.first_entry_index = first_entry_index;+ } else if previous != ForegroundActivity::Idle && current == ForegroundActivity::Idle {+ self.duration = self.started_at.map(|started| started.elapsed());+ for waiter in self.cancel_waiters.drain(..) {+ if waiter.send(()).is_err() {+ log::debug!("Foreground cancellation observer was dropped");+ }+ }+ }+ }++ pub(crate) fn wait_for_idle(&mut self) -> Option<oneshot::Receiver<()>> {+ if self.phase() == ForegroundActivity::Idle {+ return None;+ }+ let (sender, receiver) = oneshot::channel();+ self.cancel_waiters.push(sender);+ Some(receiver)+ }+}diff --git a/crates/agent/src/agent.rs b/crates/agent/src/agent.rsindex 1a961c46790..a3d072cfd04 100644--- a/crates/agent/src/agent.rs+++ b/crates/agent/src/agent.rs@@ -3594,11 +3594,11 @@ impl SubagentHandle for NativeSubagentHandle {};let discard_partial_output = matches!(&response,- Ok(Some(response)) if response.stop_reason == acp_v1::StopReason::Cancelled+ Ok(Some(acp_thread::SubmissionResponse::LegacyCompleted(response))) if response.stop_reason == acp_v1::StopReason::Cancelled|| response.stop_reason == acp_v1::StopReason::Refusal);let result = match response {- Ok(Some(response)) => match response.stop_reason {+ Ok(Some(acp_thread::SubmissionResponse::LegacyCompleted(response))) => match response.stop_reason {acp_v1::StopReason::Cancelled => Err(anyhow!("User canceled")),acp_v1::StopReason::MaxTokens => Err(anyhow!("The agent reached the maximum number of tokens.")),acp_v1::StopReason::MaxTurnRequests => Err(anyhow!("The agent reached the maximum number of allowed requests between user turns. Try prompting again.")),@@ -3624,6 +3624,9 @@ impl SubagentHandle for NativeSubagentHandle {.context("No response from subagent")}),},+ Ok(Some(acp_thread::SubmissionResponse::Accepted(_))) => {+ Err(anyhow!("Native subagent returned acceptance instead of turn completion"))+ }Ok(None) => Err(anyhow!("No response from the agent. You can try messaging again.")),Err(error) => Err(error),};diff --git a/crates/agent_ui/src/agent_diff.rs b/crates/agent_ui/src/agent_diff.rsindex b81549dc6fd..48f6487560c 100644--- a/crates/agent_ui/src/agent_diff.rs+++ b/crates/agent_ui/src/agent_diff.rs@@ -1461,7 +1461,7 @@ impl AgentDiff {self.update_reviewing_editors(workspace, window, cx);}}- AcpThreadEvent::Stopped(_) => {+ AcpThreadEvent::Stopped { .. } => {self.update_reviewing_editors(workspace, window, cx);}AcpThreadEvent::Error | AcpThreadEvent::LoadError(_) | AcpThreadEvent::Refusal => {@@ -1469,6 +1469,7 @@ impl AgentDiff {}AcpThreadEvent::TitleUpdated| AcpThreadEvent::StatusChanged+ | AcpThreadEvent::SubmissionUpdated(_)| AcpThreadEvent::TokenUsageUpdated| AcpThreadEvent::NoticesUpdated| AcpThreadEvent::SubagentSpawned(_)diff --git a/crates/agent_ui/src/agent_panel.rs b/crates/agent_ui/src/agent_panel.rsindex d6f0229cec2..0d8804757f8 100644--- a/crates/agent_ui/src/agent_panel.rs+++ b/crates/agent_ui/src/agent_panel.rs@@ -10,7 +10,7 @@ use std::{time::Duration,};-use acp_thread::{AcpThread, AcpThreadEvent, MentionUri, ThreadStatus, line_range_suffix};+use acp_thread::{AcpThread, AcpThreadEvent, MentionUri, line_range_suffix};use agent::{ContextServerRegistry, SharedThread, ThreadStore};use agent_client_protocol::schema::v1 as acp;use agent_servers::AgentServer;@@ -4230,8 +4230,13 @@ impl AgentPanel {) {let subscription = if let Some(acp_thread) = conversation_view.read(cx).root_thread(cx) {let subscription = cx.subscribe(&acp_thread, |this, acp_thread, event, cx| {- if matches!(event, AcpThreadEvent::StatusChanged)- && acp_thread.read(cx).status() == ThreadStatus::Idle+ if matches!(+ event,+ AcpThreadEvent::StatusChanged+ | AcpThreadEvent::SubmissionUpdated(_)+ | AcpThreadEvent::ToolAuthorizationReceived(_)+ | AcpThreadEvent::ElicitationResponded(_)+ ) && acp_thread.read(cx).is_idle_for_retention(){this.cleanup_retained_threads(cx);}@@ -4262,7 +4267,7 @@ impl AgentPanel {return true;};let thread = thread_view.read(cx).thread.read(cx);- thread.connection().supports_load_session() && thread.status() == ThreadStatus::Idle+ thread.connection().supports_load_session() && thread.is_idle_for_retention()}).collect::<Vec<_>>();diff --git a/crates/agent_ui/src/conversation_view.rs b/crates/agent_ui/src/conversation_view.rsindex 35d9f248b3a..ee2ac1d5b21 100644--- a/crates/agent_ui/src/conversation_view.rs+++ b/crates/agent_ui/src/conversation_view.rs@@ -1,9 +1,9 @@use acp_thread::{AcpThread, AcpThreadEvent, AgentThreadEntry, AssistantMessage, AssistantMessageChunk,AuthRequired, ClientUserMessageId, ElicitationEntryId, ElicitationStatus, ElicitationStore,- LoadError, MaxOutputTokensError, MentionUri, PermissionOptionChoice, PermissionOptions,- PermissionPattern, RetryStatus, SelectedPermissionOutcome, ThreadStatus, ToolCall,- ToolCallContent, ToolCallStatus,+ ForegroundActivity, LoadError, MaxOutputTokensError, MentionUri, PermissionOptionChoice,+ PermissionOptions, PermissionPattern, RetryStatus, SelectedPermissionOutcome, ThreadStatus,+ ToolCall, ToolCallContent, ToolCallStatus,};use acp_thread::{AgentConnection, Plan};use action_log::{ActionLog, ActionLogTelemetry, DiffStats};@@ -335,13 +335,14 @@ impl Conversation {}AcpThreadEvent::NewEntry| AcpThreadEvent::StatusChanged+ | AcpThreadEvent::SubmissionUpdated(_)| AcpThreadEvent::TitleUpdated| AcpThreadEvent::TokenUsageUpdated| AcpThreadEvent::EntryUpdated(_)| AcpThreadEvent::EntriesRemoved(_)| AcpThreadEvent::Retry(_)| AcpThreadEvent::SubagentSpawned(_)- | AcpThreadEvent::Stopped(_)+ | AcpThreadEvent::Stopped { .. }| AcpThreadEvent::Error| AcpThreadEvent::LoadError(_)| AcpThreadEvent::PromptCapabilitiesUpdated@@ -604,7 +605,7 @@ fn affects_thread_metadata(event: &AcpThreadEvent) -> bool {| AcpThreadEvent::ToolAuthorizationReceived(_)| AcpThreadEvent::ElicitationRequested(_)| AcpThreadEvent::ElicitationResponded(_)- | AcpThreadEvent::Stopped(_)+ | AcpThreadEvent::Stopped { .. }| AcpThreadEvent::Error| AcpThreadEvent::LoadError(_)| AcpThreadEvent::Refusal@@ -612,6 +613,7 @@ fn affects_thread_metadata(event: &AcpThreadEvent) -> bool {// --AcpThreadEvent::EntryUpdated(_)| AcpThreadEvent::StatusChanged+ | AcpThreadEvent::SubmissionUpdated(_)| AcpThreadEvent::EntriesRemoved(_)| AcpThreadEvent::Retry(_)| AcpThreadEvent::TokenUsageUpdated@@ -1649,10 +1651,22 @@ impl ConversationView {AcpThreadEvent::StatusChanged => {if let Some(active) = self.thread_view(&session_id) {active.update(cx, |active, cx| {+ active.sync_reported_activity(cx);active.sync_generating_indicator(cx);});}}+ AcpThreadEvent::SubmissionUpdated(submission_id) => {+ if let Some(active) = self.thread_view(&session_id) {+ let is_latest = thread.read(cx).latest_submission_id() == Some(*submission_id);+ active.update(cx, |active, cx| {+ if is_latest {+ active.current_submission = Some(*submission_id);+ }+ cx.notify();+ });+ }+ }AcpThreadEvent::NewEntry => {let len = thread.read(cx).entries().len();let index = len - 1;@@ -1725,7 +1739,23 @@ impl ConversationView {});}}- AcpThreadEvent::Stopped(stop_reason) => {+ AcpThreadEvent::Stopped {+ activity_generation,+ activity_duration,+ stop_reason,+ } => {+ if thread.read(cx).uses_reported_activity()+ && let Some(active) = self.thread_view(&session_id)+ {+ active+ .read(cx)+ .report_activity_completion(stop_reason, *activity_duration, cx);+ }+ if thread.read(cx).activity_generation() != *activity_generation+ || thread.read(cx).foreground_activity() != ForegroundActivity::Idle+ {+ return;+ }if let Some(active) = self.thread_view(&session_id) {let is_generating =matches!(thread.read(cx).status(), ThreadStatus::Generating);@@ -1741,7 +1771,7 @@ impl ConversationView {});}if is_subagent {- if *stop_reason == acp_v1::StopReason::EndTurn {+ if *stop_reason == Some(acp_v2::StopReason::EndTurn) {thread.update(cx, |thread, cx| {thread.mark_as_subagent_output(cx);});@@ -1749,6 +1779,42 @@ impl ConversationView {return;}+ if *stop_reason == Some(acp_v2::StopReason::MaxTokens)+ && thread.read(cx).uses_reported_activity()+ {+ if let Some(active) = self.root_thread_view() {+ 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,+ );+ return;+ }+ if *stop_reason == Some(acp_v2::StopReason::Refusal)+ && thread.read(cx).uses_reported_activity()+ {+ if let Some(active) = self.root_thread_view() {+ 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,+ );+ return;+ }+let sent_queued_message = if let Some(active) = self.root_thread_view() {active.update(cx, |active, cx| {// Don't auto-send while the user is editing the next message.@@ -4321,6 +4387,390 @@ pub(crate) mod tests {});}+ #[gpui::test]+ async fn test_receipt_submission_waits_for_echo_and_reported_idle(cx: &mut TestAppContext) {+ init_test(cx);++ let connection = StubAgentConnection::new().with_receipt_submissions(true);+ let (conversation_view, cx) =+ setup_conversation_view(StubAgentServer::new(connection.clone()), 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());+ let message_editor = message_editor(&conversation_view, cx);+ let finish_receipt = connection.defer_next_receipt_response();++ message_editor.update_in(cx, |editor, window, cx| {+ editor.set_text("receipt prompt", window, cx);+ });+ thread_view.update_in(cx, |view, window, cx| view.send(window, cx));+ cx.run_until_parked();++ let submission_id = thread_view.read_with(cx, |view, cx| {+ assert_eq!(view.thread.read(cx).entries().len(), 0);+ view.current_submission.expect("submission created")+ });+ let copy_selector: &'static str =+ Box::leak(format!("copy-submission-{}", submission_id.as_u64()).into_boxed_str());+ assert!(cx.debug_bounds(copy_selector).is_some());+ thread.update(cx, |thread, cx| {+ thread+ .update_session_state(+ acp_v2::StateUpdate::Running(acp_v2::RunningStateUpdate::new()),+ cx,+ )+ .expect("running state update");+ });+ cx.run_until_parked();+ thread_view.update_in(cx, |view, window, cx| {+ view.add_to_queue(vec!["queued".into()], vec![], window, cx);+ });+ finish_receipt+ .send(Ok(acp_v2::PromptResponse::new("receipt-echo")))+ .expect("receipt response pending");+ cx.run_until_parked();++ assert!(cx.debug_bounds(copy_selector).is_some());+ thread_view.read_with(cx, |view, cx| {+ assert_eq!(view.message_queue.len(), 1);+ assert!(view.turn_fields.turn_started_at.is_some());+ assert!(matches!(+ view.thread+ .read(cx)+ .submission(submission_id)+ .map(|record| &record.state),+ Some(acp_thread::SubmissionState::Accepted { echoed: false, .. })+ ));+ assert!(view.thread.read(cx).entries().is_empty());+ });++ thread.update(cx, |thread, cx| {+ thread+ .upsert_user_message(+ acp_v2::UserMessage::new("receipt-echo").content(vec!["receipt prompt".into()]),+ cx,+ )+ .expect("echo update");+ });+ cx.run_until_parked();+ assert!(cx.debug_bounds(copy_selector).is_none());+ thread_view.read_with(cx, |view, cx| {+ assert!(matches!(+ view.thread+ .read(cx)+ .submission(submission_id)+ .map(|record| &record.state),+ Some(acp_thread::SubmissionState::Accepted { echoed: true, .. })+ ));+ assert_eq!(view.thread.read(cx).entries().len(), 1);+ assert_eq!(view.message_queue.len(), 1);+ assert!(view.turn_fields.turn_started_at.is_some());+ });++ let finish_queued = connection.defer_next_receipt_response();+ thread.update(cx, |thread, cx| {+ thread+ .update_session_state(+ acp_v2::StateUpdate::Idle(acp_v2::IdleStateUpdate::new()),+ cx,+ )+ .expect("idle state update");+ });+ cx.run_until_parked();+ thread_view.read_with(cx, |view, _| {+ assert!(view.turn_fields.turn_started_at.is_none());+ assert_eq!(view.message_queue.len(), 0);+ });+ finish_queued+ .send(Ok(acp_v2::PromptResponse::new("queued-echo")))+ .expect("queued submission pending");+ cx.run_until_parked();+ }++ #[gpui::test]+ async fn test_authentication_keeps_receipt_submission_recoverable(cx: &mut TestAppContext) {+ init_test(cx);+ let connection = StubAgentConnection::new().with_receipt_submissions(true);+ let (conversation_view, cx) =+ setup_conversation_view(StubAgentServer::new(connection.clone()), 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());+ let message_editor = message_editor(&conversation_view, cx);+ let reject = connection.defer_next_receipt_response();++ message_editor.update_in(cx, |editor, window, cx| {+ editor.set_text("retain this prompt", window, cx);+ });+ thread_view.update_in(cx, |view, window, cx| view.send(window, cx));+ cx.run_until_parked();+ let submission_id = thread.read_with(cx, |thread, _| {+ thread.latest_submission_id().expect("submission")+ });+ reject+ .send(Err(anyhow!(acp_v1::Error::auth_required())))+ .expect("receipt response pending");+ cx.run_until_parked();+ thread_view.read_with(cx, |view, _| {+ assert!(matches!(+ view.thread_error,+ Some(ThreadError::AuthenticationRequired(_))+ ));+ });++ let authenticate = cx+ .debug_bounds("authenticate-submission")+ .expect("authentication recovery button");+ cx.simulate_click(authenticate.center(), gpui::Modifiers::default());+ cx.run_until_parked();+ assert_eq!(+ message_editor.read_with(cx, |editor, cx| editor.text(cx)),+ "retain this prompt",+ );+ thread.read_with(cx, |thread, _| {+ let original = thread.submission(submission_id).expect("retained original");+ assert_eq!(original.content.as_ref(), &["retain this prompt".into()]);+ assert!(matches!(+ original.state,+ acp_thread::SubmissionState::Failed(_)+ ));+ assert!(!thread.is_idle_for_retention());+ });+ }++ #[gpui::test]+ async fn test_receipt_recovery_preserves_draft_and_copies_failed_submission(+ cx: &mut TestAppContext,+ ) {+ init_test(cx);+ let connection = StubAgentConnection::new().with_receipt_submissions(true);+ let (conversation_view, cx) =+ setup_conversation_view(StubAgentServer::new(connection.clone()), cx).await;+ add_to_workspace_with_size(conversation_view.clone(), true, cx);+ let thread_view = active_thread(&conversation_view, cx);+ let thread = thread_view.read_with(cx, |view, _| view.thread.clone());+ let message_editor = message_editor(&conversation_view, cx);+ let reject = connection.defer_next_receipt_response();+ message_editor.update_in(cx, |editor, window, cx| {+ editor.set_text("first rejected text", window, cx);+ });+ thread_view.update_in(cx, |view, window, cx| view.send(window, cx));+ cx.run_until_parked();+ let first_id = thread.read_with(cx, |thread, _| {+ thread.latest_submission_id().expect("first submission")+ });+ reject+ .send(Err(anyhow!("first rejected")))+ .expect("rejection receiver");+ cx.run_until_parked();+ assert!(thread_view.read_with(cx, |view, _| view.thread_error.is_some()));+ thread.update(cx, |thread, cx| {+ thread+ .update_session_state(+ acp_v2::StateUpdate::Running(acp_v2::RunningStateUpdate::new()),+ cx,+ )+ .expect("running after rejection");+ });+ cx.run_until_parked();+ assert!(thread_view.read_with(cx, |view, _| view.thread_error.is_some()));+ thread.update(cx, |thread, cx| {+ thread+ .update_session_state(+ acp_v2::StateUpdate::Idle(acp_v2::IdleStateUpdate::new()),+ cx,+ )+ .expect("idle after independent activity");+ });+ cx.run_until_parked();++ let accept = connection.defer_next_receipt_response();+ message_editor.update_in(cx, |editor, window, cx| {+ editor.set_text("second un-echoed text", window, cx);+ });+ thread_view.update_in(cx, |view, window, cx| view.send(window, cx));+ cx.run_until_parked();+ let second_id = thread.read_with(cx, |thread, _| {+ thread.latest_submission_id().expect("second submission")+ });+ accept+ .send(Ok(acp_v2::PromptResponse::new("second-echo")))+ .expect("receipt receiver");+ cx.run_until_parked();+ thread.read_with(cx, |thread, _| {+ assert_eq!(+ thread+ .recoverable_submissions()+ .map(|(id, _)| id)+ .collect::<Vec<_>>(),+ [first_id, second_id]+ );+ });+ let first_copy: &'static str =+ Box::leak(format!("copy-submission-{}", first_id.as_u64()).into_boxed_str());+ let second_copy: &'static str =+ Box::leak(format!("copy-submission-{}", second_id.as_u64()).into_boxed_str());+ let first_restore: &'static str =+ Box::leak(format!("restore-submission-{}", first_id.as_u64()).into_boxed_str());+ assert!(cx.debug_bounds(first_copy).is_some());+ assert!(cx.debug_bounds(second_copy).is_some());+ let copy = cx+ .debug_bounds(first_copy)+ .expect("failed submission copy button");+ cx.simulate_click(copy.center(), gpui::Modifiers::default());+ assert_eq!(+ cx.update(|_, cx| cx.read_from_clipboard().and_then(|item| item.text())),+ Some("first rejected text".to_string())+ );++ message_editor.update_in(cx, |editor, window, cx| {+ editor.set_text("keep this draft", window, cx);+ });+ let restore = cx+ .debug_bounds(first_restore)+ .expect("failed submission restore button");+ cx.simulate_click(restore.center(), gpui::Modifiers::default());+ cx.run_until_parked();+ assert_eq!(+ message_editor.read_with(cx, |editor, cx| editor.text(cx)),+ "keep this draft"+ );+ assert!(thread.read_with(cx, |thread, _| thread.submission(first_id).is_some()));+ message_editor.update_in(cx, |editor, window, cx| {+ editor.set_text("", window, cx);+ });+ let restore = cx+ .debug_bounds(first_restore)+ .expect("failed submission remains restorable");+ cx.simulate_click(restore.center(), gpui::Modifiers::default());+ cx.run_until_parked();+ assert_eq!(+ message_editor.read_with(cx, |editor, cx| editor.text(cx)),+ "first rejected text"+ );+ thread.read_with(cx, |thread, _| {+ assert_eq!(+ thread+ .submission(first_id)+ .expect("retained original")+ .content+ .as_ref(),+ &[acp_v1::ContentBlock::from("first rejected text")],+ );+ });+ assert!(cx.debug_bounds(first_copy).is_some());+ thread.update(cx, |thread, cx| thread.forget_submission(first_id, cx));+ cx.run_until_parked();+ assert!(thread.read_with(cx, |thread, _| thread.submission(first_id).is_none()));+ assert!(cx.debug_bounds(first_copy).is_none());+ assert!(cx.debug_bounds(second_copy).is_some());+ }++ #[gpui::test]+ async fn test_reported_stale_stop_and_token_limit_do_not_send_queue(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_view.update_in(cx, |view, window, cx| {+ view.add_to_queue(vec!["queued".into()], vec![], window, cx);+ });+ thread.update(cx, |thread, cx| {+ thread+ .update_session_state(+ acp_v2::StateUpdate::Running(acp_v2::RunningStateUpdate::new()),+ cx,+ )+ .expect("running A");+ });+ cx.run_until_parked();+ let generation_a = thread.read_with(cx, |thread, _| thread.activity_generation());+ thread.update(cx, |thread, cx| {+ thread+ .update_session_state(+ acp_v2::StateUpdate::Idle(acp_v2::IdleStateUpdate::new()),+ cx,+ )+ .expect("idle A");+ thread+ .update_session_state(+ acp_v2::StateUpdate::Running(acp_v2::RunningStateUpdate::new()),+ cx,+ )+ .expect("running B");+ });+ cx.run_until_parked();+ thread_view.read_with(cx, |view, _| assert_eq!(view.message_queue.len(), 1));+ assert!(thread.read_with(cx, |thread, _| thread.activity_generation() > generation_a));+ thread.update(cx, |thread, cx| {+ thread+ .update_session_state(+ acp_v2::StateUpdate::Idle(acp_v2::IdleStateUpdate::new()),+ cx,+ )+ .expect("idle B");+ thread+ .update_session_state(+ acp_v2::StateUpdate::Running(acp_v2::RunningStateUpdate::new()),+ cx,+ )+ .expect("running C");+ thread+ .update_session_state(+ acp_v2::StateUpdate::Idle(+ acp_v2::IdleStateUpdate::new().stop_reason(acp_v2::StopReason::MaxTokens),+ ),+ cx,+ )+ .expect("token limit");+ });+ cx.run_until_parked();+ thread_view.read_with(cx, |view, cx| {+ assert!(matches!(+ view.thread_error,+ Some(ThreadError::MaxOutputTokens)+ ));+ assert_eq!(view.message_queue.len(), 1);+ assert!(view.turn_fields.turn_started_at.is_none());+ assert!(view.turn_fields._turn_timer_task.is_none());+ assert_eq!(+ view.turn_fields.last_turn_duration,+ thread.read(cx).activity_duration(),+ );+ });+ thread.update(cx, |thread, cx| {+ thread+ .update_session_state(+ acp_v2::StateUpdate::Running(acp_v2::RunningStateUpdate::new()),+ cx,+ )+ .expect("independent running");+ thread+ .update_session_state(+ acp_v2::StateUpdate::Idle(acp_v2::IdleStateUpdate::new()),+ cx,+ )+ .expect("independent idle");+ });+ cx.run_until_parked();+ thread_view.read_with(cx, |view, cx| {+ assert!(matches!(+ view.thread_error,+ Some(ThreadError::MaxOutputTokens)+ ));+ assert_eq!(view.message_queue.len(), 1);+ assert!(view.turn_fields.turn_started_at.is_none());+ assert!(view.turn_fields._turn_timer_task.is_none());+ assert_eq!(+ view.turn_fields.last_turn_duration,+ thread.read(cx).activity_duration(),+ );+ });+ }+#[gpui::test]async fn test_stale_send_result_preserves_new_prompt(cx: &mut TestAppContext) {init_test(cx);@@ -4370,7 +4820,7 @@ pub(crate) mod tests {} else {assert_eq!(view.thread.read(cx).status(), ThreadStatus::Generating);assert!(matches!(- view.in_flight_prompt.as_deref(),+ view.in_flight_prompt(cx).as_deref(),Some([acp_v1::ContentBlock::Text(text)]) if text.text == "second"));}@@ -4397,7 +4847,7 @@ pub(crate) mod tests {assert_eq!(view.thread.read(cx).status(), ThreadStatus::Generating);assert!(view.turn_fields.turn_started_at.is_some());assert!(matches!(- view.in_flight_prompt.as_deref(),+ view.in_flight_prompt(cx).as_deref(),Some([acp_v1::ContentBlock::Text(text)]) if text.text == "second"));assert!(view.thread_error.is_none());@@ -4421,12 +4871,12 @@ pub(crate) mod tests {Some(ThreadError::Other { message, .. }) if message.as_ref() == "current prompt failed"));assert!(matches!(- view.in_flight_prompt.as_deref(),+ view.in_flight_prompt(cx).as_deref(),Some([acp_v1::ContentBlock::Text(text)]) if text.text == "second"));} else {assert!(view.thread_error.is_none());- assert!(view.in_flight_prompt.is_none());+ assert!(view.in_flight_prompt(cx).is_none());}});}diff --git a/crates/agent_ui/src/conversation_view/thread_view.rs b/crates/agent_ui/src/conversation_view/thread_view.rsindex db76274fe3e..e94334f7917 100644--- a/crates/agent_ui/src/conversation_view/thread_view.rs+++ b/crates/agent_ui/src/conversation_view/thread_view.rs@@ -8,8 +8,9 @@ use agent_client_protocol::schema::{v1 as acp_v1, v2 as acp_v2};use std::cell::RefCell;use acp_thread::{- Elicitation, ElicitationEntryId, ElicitationStatus, SandboxAuthorizationDetails,- SandboxFallbackAuthorizationDetails, SandboxNotAppliedReason, decode_path_escapes,+ Elicitation, ElicitationEntryId, ElicitationStatus, ForegroundActivity,+ SandboxAuthorizationDetails, SandboxFallbackAuthorizationDetails, SandboxNotAppliedReason,+ SubmissionId, SubmissionResponse, SubmissionState, decode_path_escapes,};use agent::{SandboxStatusKey, SandboxStatusRefresh, SkillLoadingIssue, SkillLoadingIssueKind,@@ -34,6 +35,7 @@ use gpui::List;use gpui::Stateful;use gpui::TaskExt;use heapless::Vec as ArrayVec;+use itertools::Itertools;use language_model::{FastModeConfirmation, LanguageModel, LanguageModelEffortLevel, LanguageModelId,LanguageModelProvider, LanguageModelProviderId, LanguageModelRegistry, Speed,@@ -617,7 +619,7 @@ pub struct ThreadView {_draft_resolve_task: Option<Task<()>>,_sandbox_status_refresh_task: Option<Task<()>>,pub hovered_edited_file_buttons: Option<usize>,- pub in_flight_prompt: Option<Vec<acp_v1::ContentBlock>>,+ pub current_submission: Option<SubmissionId>,pub _subscriptions: Vec<Subscription>,pub message_editor: Entity<MessageEditor>,pub add_context_menu_handle: PopoverMenuHandle<ContextMenu>,@@ -669,6 +671,7 @@ pub struct TurnFields {pub turn_generation: usize,pub turn_started_at: Option<Instant>,pub turn_tokens: Option<u64>,+ pub reported_activity_generation: Option<u64>,}/// How a tool call is rendered relative to its surroundings.@@ -980,6 +983,7 @@ impl ThreadView {}));}));+ let current_submission = thread.read(cx).latest_submission_id();let mut this = Self {root_thread_id,session_id,@@ -1033,7 +1037,7 @@ impl ThreadView {_draft_resolve_task: None,_sandbox_status_refresh_task: None,hovered_edited_file_buttons: None,- in_flight_prompt: None,+ current_submission,message_editor,add_context_menu_handle: PopoverMenuHandle::default(),thinking_effort_menu_handle: PopoverMenuHandle::default(),@@ -1053,6 +1057,7 @@ impl ThreadView {thread_search_visible: false,};+ this.sync_reported_activity(cx);this.sync_generating_indicator(cx);this.sync_editor_mode(cx);this.sync_existing_elicitation_states(window, cx);@@ -1404,6 +1409,10 @@ impl ThreadView {pub fn start_turn(&mut self, cx: &mut Context<Self>) -> usize {// A previous response may have settled while the new prompt's contents were loading.self.thread_error.take();+ self.initialize_turn(cx)+ }++ fn initialize_turn(&mut self, cx: &mut Context<Self>) -> usize {self.turn_fields.turn_generation += 1;let generation = self.turn_fields.turn_generation;self.turn_fields.turn_started_at = Some(Instant::now());@@ -1434,6 +1443,242 @@ impl ThreadView {self.turn_fields._turn_timer_task = None;}+ pub(crate) fn sync_reported_activity(&mut self, cx: &mut Context<Self>) {+ let thread = self.thread.read(cx);+ if !thread.uses_reported_activity() {+ return;+ }+ let activity = thread.foreground_activity();+ let activity_generation = thread.activity_generation();+ let started_at = thread.activity_started_at();+ let duration = thread.activity_duration();++ if activity != ForegroundActivity::Idle {+ if self.turn_fields.reported_activity_generation != Some(activity_generation) {+ self.initialize_turn(cx);+ self.turn_fields.turn_started_at = started_at;+ self.turn_fields.reported_activity_generation = Some(activity_generation);+ }+ } else {+ if self.turn_fields.turn_started_at.is_some() {+ self.stop_turn(self.turn_fields.turn_generation, cx);+ }+ if self.turn_fields.reported_activity_generation != Some(activity_generation) {+ self.turn_fields.last_turn_tokens = None;+ }+ self.turn_fields.reported_activity_generation = Some(activity_generation);+ self.turn_fields.last_turn_duration = duration;+ }+ cx.notify();+ }++ pub(crate) fn report_activity_completion(+ &self,+ stop_reason: &Option<acp_v2::StopReason>,+ duration: Option<Duration>,+ cx: &App,+ ) {+ let thread = self.thread.read(cx);+ telemetry::event!(+ "Agent Turn Completed",+ agent = thread.connection().telemetry_id(),+ session = thread.session_id().clone(),+ parent_session_id = thread.parent_session_id().map(|id| id.to_string()),+ model = self.current_model_id(cx),+ mode = self.current_mode_id(cx),+ status = Self::activity_completion_status(stop_reason.as_ref()),+ turn_time_ms = duration.unwrap_or_default().as_millis(),+ side = crate::agent_sidebar_side(cx)+ );+ }++ fn activity_completion_status(stop_reason: Option<&acp_v2::StopReason>) -> &'static str {+ match stop_reason {+ Some(acp_v2::StopReason::EndTurn) => "success",+ Some(acp_v2::StopReason::Cancelled) => "cancelled",+ Some(+ acp_v2::StopReason::MaxTokens+ | acp_v2::StopReason::MaxTurnRequests+ | acp_v2::StopReason::Refusal,+ ) => "failure",+ _ => "unknown",+ }+ }++ pub(crate) fn in_flight_prompt(&self, cx: &App) -> Option<Arc<[acp_v1::ContentBlock]>> {+ let record = self.thread.read(cx);+ let record = record.submission(self.current_submission?)?;+ (!matches!(record.state, SubmissionState::Completed)).then(|| record.content.clone())+ }++ fn submission_text_parts(content: &[acp_v1::ContentBlock]) -> impl Iterator<Item = &str> {+ content.iter().map(|block| match block {+ acp_v1::ContentBlock::Text(text) => text.text.as_str(),+ acp_v1::ContentBlock::ResourceLink(link) => link.name.as_str(),+ acp_v1::ContentBlock::Resource(resource) => match &resource.resource {+ acp_v1::EmbeddedResourceResource::TextResourceContents(resource) => {+ resource.uri.as_str()+ }+ acp_v1::EmbeddedResourceResource::BlobResourceContents(resource) => {+ resource.uri.as_str()+ }+ _ => "[Resource attachment]",+ },+ acp_v1::ContentBlock::Image(_) => "[Image attachment]",+ acp_v1::ContentBlock::Audio(_) => "[Audio attachment]",+ _ => "[Unsupported attachment]",+ })+ }++ fn restore_submission(+ &mut self,+ submission_id: SubmissionId,+ window: &mut Window,+ cx: &mut Context<Self>,+ ) {+ if !self.message_editor.read(cx).text(cx).is_empty() {+ return;+ }+ let content = self+ .thread+ .read(cx)+ .submission(submission_id)+ .and_then(|record| {+ matches!(+ record.state,+ SubmissionState::Failed(_) | SubmissionState::Cancelled+ )+ .then(|| record.content.to_vec())+ });+ if let Some(content) = content {+ self.message_editor.update(cx, |editor, cx| {+ editor.set_message(content, window, cx);+ });+ // The editor is not a lossless ACP round trip. Keep the original until explicit discard.+ cx.notify();+ }+ }++ fn render_recoverable_submissions(&self, cx: &mut Context<Self>) -> Option<Stateful<Div>> {+ let submissions = {+ let thread = self.thread.read(cx);+ if !thread.uses_reported_activity() {+ return None;+ }+ thread+ .recoverable_submissions()+ .map(|(submission_id, record)| {+ let (status, settled): (SharedString, bool) = match &record.state {+ SubmissionState::Pending => ("Sending message…".into(), false),+ SubmissionState::Accepted { echoed: false, .. } => {+ ("Waiting for message to appear…".into(), false)+ }+ SubmissionState::Failed(error) => (+ format!(+ "Message failed to send: {}",+ util::truncate_and_trailoff(error, 160)+ )+ .into(),+ true,+ ),+ SubmissionState::Cancelled => ("Message cancelled".into(), true),+ _ => ("Message".into(), false),+ };+ (+ submission_id,+ status,+ settled,+ Itertools::intersperse(Self::submission_text_parts(&record.content), "\n")+ .flat_map(str::chars)+ .take(161)+ .collect::<String>(),+ )+ })+ .collect::<Vec<_>>()+ };+ if submissions.is_empty() {+ return None;+ }+ let rows = submissions+ .into_iter()+ .map(|(submission_id, status, settled, text)| {+ let preview: SharedString = util::truncate_and_trailoff(&text, 160).into();+ let row_id = submission_id.as_u64();+ v_flex()+ .id(("recoverable-submission", row_id))+ .px_3()+ .py_1()+ .gap_1()+ .child(Label::new(status).size(LabelSize::Small))+ .child(Label::new(preview).size(LabelSize::Small))+ .child(+ h_flex()+ .gap_1()+ .child(+ div()+ .debug_selector(move || format!("copy-submission-{row_id}"))+ .child(+ Button::new(("copy-submission", row_id), "Copy")+ .label_size(LabelSize::Small)+ .on_click(cx.listener(move |this, _, _, cx| {+ if let Some(record) =+ this.thread.read(cx).submission(submission_id)+ {+ let text = Self::submission_text_parts(+ &record.content,+ )+ .join("\n");+ cx.write_to_clipboard(+ ClipboardItem::new_string(text),+ );+ }+ })),+ ),+ )+ .when(settled, |this| {+ this.child(+ div()+ .debug_selector(move || {+ format!("restore-submission-{row_id}")+ })+ .child(+ Button::new(("restore-submission", row_id), "Restore")+ .label_size(LabelSize::Small)+ .tooltip(Tooltip::text("Copy into an empty composer. The saved submission is kept until discarded."))+ .on_click(cx.listener(+ move |this, _, window, cx| {+ this.restore_submission(+ submission_id,+ window,+ cx,+ );+ },+ )),+ ),+ )+ .child(+ Button::new(("discard-submission", row_id), "Discard")+ .label_size(LabelSize::Small)+ .on_click(cx.listener(move |this, _, _, cx| {+ this.thread.update(cx, |thread, cx| {+ thread.forget_submission(submission_id, cx);+ });+ cx.notify();+ })),+ )+ }),+ )+ })+ .collect::<Vec<_>>();+ Some(+ v_flex()+ .id("recoverable-submissions")+ .max_h(px(180.))+ .overflow_y_scroll()+ .children(rows),+ )+ }+pub fn update_turn_tokens(&mut self, cx: &App) {if let Some(usage) = self.thread.read(cx).token_usage() {if let Some(tokens) = &mut self.turn_fields.turn_tokens {@@ -1703,11 +1948,12 @@ impl ThreadView {return Ok(());};+ let uses_reported_activity =+ thread.read_with(cx, |thread, _| thread.uses_reported_activity())?;let generation = this.update(cx, |this, cx| {this.clear_external_source_prompt_warning(cx);- let generation = this.start_turn(cx);- this.in_flight_prompt = Some(contents.clone());- generation+ this.thread_error.take();+ (!uses_reported_activity).then(|| this.start_turn(cx))})?;this.update_in(cx, |this, _window, cx| {@@ -1719,16 +1965,18 @@ impl ThreadView {cx.notify();});- let _stop_turn = defer({+ let _stop_turn = (!uses_reported_activity).then(|| {let this = this.clone();let mut cx = cx.clone();- move || {+ defer(move || {this.update(&mut cx, |this, cx| {- this.stop_turn(generation, cx);+ if let Some(generation) = generation {+ this.stop_turn(generation, cx);+ }cx.notify();}).ok();- }+ })});if is_first_message && thread.read_with(cx, |thread, _cx| thread.title().is_none())? {let text: String = contents@@ -1776,8 +2024,10 @@ impl ThreadView {thread.send(contents, cx)}})?;+ let submission_id = send.id;let _ = this.update(cx, |this, cx| {+ this.current_submission = Some(submission_id);this.sync_generating_indicator(cx);cx.notify();});@@ -1785,29 +2035,34 @@ impl ThreadView {let res = send.await;let turn_time_ms = turn_start_time.elapsed().as_millis();drop(_stop_turn);- let status = if res.is_ok() { "success" } else { "failure" };- telemetry::event!(- "Agent Turn Completed",- agent = agent_telemetry_id,- session = session_id,- parent_session_id = parent_session_id.as_ref().map(|id| id.to_string()),- model = model_id,- mode = mode_id,- status,- turn_time_ms,- side = side- );+ if !uses_reported_activity {+ let status = if res.is_ok() { "success" } else { "failure" };+ telemetry::event!(+ "Agent Turn Completed",+ agent = agent_telemetry_id,+ session = session_id,+ parent_session_id = parent_session_id.as_ref().map(|id| id.to_string()),+ model = model_id,+ mode = mode_id,+ status,+ turn_time_ms,+ side = side+ );+ }this.update(cx, |this, cx| {// Cancellation can return control to the UI before this response settles.- if this.turn_fields.turn_generation != generation {+ if this.current_submission != Some(submission_id)+ || generation+ .is_some_and(|generation| this.turn_fields.turn_generation != generation)+ {if let Err(error) = res {log::debug!("Ignoring error from a superseded agent send: {error:#}");}return;}match res {- Ok(_) => {- this.in_flight_prompt.take();+ Ok(Some(SubmissionResponse::LegacyCompleted(_))) => {+ this.current_submission.take();this.should_be_following = this.workspace.update(cx, |workspace, _| {@@ -1815,6 +2070,8 @@ impl ThreadView {}).unwrap_or_default();}+ Ok(Some(SubmissionResponse::Accepted(_))) => {}+ Ok(None) => {}Err(error) => this.handle_thread_error(error, cx),}})?;@@ -2009,6 +2266,8 @@ impl ThreadView {}let task = thread.update(cx, |thread, cx| thread.retry(cx));+ let submission_id = task.id;+ self.current_submission = Some(submission_id);cx.emit(AcpThreadViewEvent::Interacted);self.sync_generating_indicator(cx);cx.notify();@@ -2016,8 +2275,15 @@ impl ThreadView {let result = task.await;this.update(cx, |this, cx| {- if let Err(err) = result {- this.handle_thread_error(err, cx);+ if this.current_submission != Some(submission_id) {+ return;+ }+ match result {+ Err(error) => this.handle_thread_error(error, cx),+ Ok(Some(SubmissionResponse::LegacyCompleted(_))) => {+ this.current_submission = None;+ }+ Ok(Some(SubmissionResponse::Accepted(_)) | None) => {}}})})@@ -11531,9 +11797,27 @@ impl ThreadView {let server_view = this.server_view.clone();this.clear_thread_error(cx);- if let Some(message) = this.in_flight_prompt.take() {+ if let Some(message) = this.in_flight_prompt(cx) {+ if !this.thread.read(cx).uses_reported_activity()+ && let Some(submission_id) = this.current_submission+ && this.thread.read(cx).submission(submission_id).is_some_and(+ |record| {+ matches!(+ record.state,+ SubmissionState::Completed+ | SubmissionState::Failed(_)+ | SubmissionState::Cancelled+ )+ },+ )+ {+ this.thread.update(cx, |thread, cx| {+ thread.forget_submission(submission_id, cx);+ });+ this.current_submission = None;+ }this.message_editor.update(cx, |editor, cx| {- editor.set_message(message, window, cx);+ editor.set_message(message.to_vec(), window, cx);});}let connection = this.thread.read(cx).connection().clone();@@ -11548,6 +11832,11 @@ impl ThreadView {})}}))+ .map(|button| {+ div()+ .debug_selector(|| "authenticate-submission".into())+ .child(button)+ })}fn current_model_name(&self, cx: &App) -> SharedString {@@ -12658,6 +12947,10 @@ impl Render for ThreadView {.child(conversation).children(self.render_multi_root_callout(cx)).children(self.render_activity_bar(window, cx))+ .when_some(+ self.render_recoverable_submissions(cx),+ |this, submissions| this.child(submissions),+ ).when_some(self.render_session_notices(cx), |this, notices| {this.child(notices)})@@ -12873,6 +13166,25 @@ mod tests {use util::path;use workspace::MultiWorkspace;+ #[test]+ fn test_reported_activity_completion_status() {+ use acp_v2::StopReason::*;+ for (reason, expected) in [+ (None, "unknown"),+ (Some(Other("_custom".into())), "unknown"),+ (Some(EndTurn), "success"),+ (Some(Cancelled), "cancelled"),+ (Some(Refusal), "failure"),+ (Some(MaxTokens), "failure"),+ (Some(MaxTurnRequests), "failure"),+ ] {+ assert_eq!(+ ThreadView::activity_completion_status(reason.as_ref()),+ expected+ );+ }+ }+#[test]fn test_tool_call_icon_tooltip() {for (name, interrupted_edit, expected) in [diff --git a/crates/eval_cli/src/main.rs b/crates/eval_cli/src/main.rsindex 61844188f9c..88cd530d79f 100644--- a/crates/eval_cli/src/main.rs+++ b/crates/eval_cli/src/main.rs@@ -843,7 +843,7 @@ async fn run_agent(let outcome = select_biased! {result = send_future.fuse() => match result {- Ok(Some(response)) => {+ Ok(Some(acp_thread::SubmissionResponse::LegacyCompleted(response))) => {eprintln!("[eval-cli] stopped: {:?}", response.stop_reason);if response.stop_reason == acp::StopReason::MaxTokens {Err(anyhow::anyhow!("Model hit maximum token limit"))@@ -851,6 +851,9 @@ async fn run_agent(Ok(AgentOutcome::Completed)}}+ Ok(Some(acp_thread::SubmissionResponse::Accepted(_))) => {+ Err(anyhow::anyhow!("Native agent returned acceptance instead of turn completion"))+ }Ok(None) => {eprintln!("[eval-cli] completed (no response)");Ok(AgentOutcome::Completed)@@ -992,8 +995,8 @@ fn log_acp_thread_event(}}}- acp_thread::AcpThreadEvent::Stopped(reason) => {- eprintln!("\n[eval-cli] stopped: {reason:?}");+ acp_thread::AcpThreadEvent::Stopped { stop_reason, .. } => {+ eprintln!("\n[eval-cli] stopped: {stop_reason:?}");}acp_thread::AcpThreadEvent::Error => {eprintln!("[eval-cli] error event");