Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
acp_thread: Align ACP foreground state and resume snapshots (#65724)
Ben Brandtda5921d6ba26
diff --git a/crates/acp_thread/src/acp_thread.rs b/crates/acp_thread/src/acp_thread.rsindex 0dd9876a737..fcc31adaaaf 100644--- a/crates/acp_thread/src/acp_thread.rs+++ b/crates/acp_thread/src/acp_thread.rs@@ -3478,6 +3478,8 @@ pub struct AcpThread {connection: Rc<dyn AgentConnection>,submissions: SessionSubmissions,activity: SessionActivity,+ received_session_state: bool,+ reported_usage: Option<ReportedTokenUsage>,token_usage: Option<TokenUsage>,cost: Option<SessionCost>,prompt_capabilities: acp_v2::PromptCapabilities,@@ -3597,15 +3599,38 @@ impl From<&AcpThread> for ActionLogTelemetry {}}+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+struct ReportedTokenUsage {+ activity_generation: u64,+ input_tokens: u64,+ output_tokens: u64,+}++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum OutputTokensUpdate {+ Unchanged,+ /// Preserve additive presentation for legacy/native usage notifications.+ LegacyAdd {+ activity_generation: u64,+ output_tokens: u64,+ },+ Snapshot {+ activity_generation: u64,+ output_tokens: u64,+ },+}+#[derive(Debug)]pub enum AcpThreadEvent {StatusChanged,+ /// Initial Idle confirmation is not a foreground completion.+ ActivityConfirmedIdle,SubmissionUpdated(SubmissionId),PromptUpdated,NewEntry,TitleUpdated,NoticesUpdated,- TokenUsageUpdated,+ TokenUsageUpdated(OutputTokensUpdate),EntryUpdated(usize),EntriesRemoved(Range<usize>),ToolAuthorizationRequested(PermissionRequestId),@@ -3673,6 +3698,7 @@ pub enum TerminalProviderCommand {#[derive(PartialEq, Eq, Debug)]pub enum ThreadStatus {+ Unconfirmed,Idle,Generating,}@@ -3753,11 +3779,12 @@ impl AcpThread {this.update_idle_sleep_prevention(cx);}AcpThreadEvent::PromptUpdated+ | AcpThreadEvent::ActivityConfirmedIdle| AcpThreadEvent::SubmissionUpdated(_)| AcpThreadEvent::NewEntry| AcpThreadEvent::TitleUpdated| AcpThreadEvent::NoticesUpdated- | AcpThreadEvent::TokenUsageUpdated+ | AcpThreadEvent::TokenUsageUpdated(_)| AcpThreadEvent::EntryUpdated(_)| AcpThreadEvent::Retry(_)| AcpThreadEvent::SubagentSpawned(_)@@ -3815,6 +3842,8 @@ impl AcpThread {turn_id: 0,submissions: SessionSubmissions::new(receipt_submissions),activity: SessionActivity::default(),+ received_session_state: false,+ reported_usage: None,connection,token_usage: None,cost: None,@@ -4019,6 +4048,7 @@ impl AcpThread {pub fn status(&self) -> ThreadStatus {match self.foreground_activity() {+ ForegroundActivity::Unconfirmed => ThreadStatus::Unconfirmed,ForegroundActivity::Idle => ThreadStatus::Idle,_ => ThreadStatus::Generating,}@@ -4028,10 +4058,26 @@ impl AcpThread {self.submissions.receipt_transport().is_some()}- pub fn foreground_state(&self) -> &acp_v2::StateUpdate {+ pub fn foreground_state(&self) -> Option<&acp_v2::StateUpdate> {self.activity.state()}+ pub fn mark_activity_unconfirmed(&mut self, cx: &mut Context<Self>) {+ if self.uses_reported_activity()+ && !self.received_session_state+ && self.activity.generation() == 0+ {+ self.activity.mark_unconfirmed();+ cx.emit(AcpThreadEvent::StatusChanged);+ cx.notify();+ }+ }++ /// Distinguishes a received snapshot from the default Idle used by new sessions.+ pub fn has_received_session_state(&self) -> bool {+ self.received_session_state+ }+pub fn foreground_activity(&self) -> ForegroundActivity {self.activity.phase()}@@ -4040,6 +4086,12 @@ impl AcpThread {self.activity.generation()}+ pub fn reported_activity_output_tokens(&self) -> Option<u64> {+ self.reported_usage+ .filter(|usage| usage.activity_generation == self.activity.generation())+ .map(|usage| usage.output_tokens)+ }+pub fn activity_started_at(&self) -> Option<Instant> {self.activity.started_at()}@@ -4293,7 +4345,7 @@ impl AcpThread {self.activity.update(state, self.entries.len().saturating_sub(1));let current = self.foreground_activity();- if previous == ForegroundActivity::Idle && current != ForegroundActivity::Idle {+ if !previous.is_active() && current.is_active() {self.had_error = false;self.local_execution_error = None;}@@ -4301,7 +4353,7 @@ impl AcpThread {}pub fn sync_local_action_state(&mut self, cx: &mut Context<Self>) {- if self.foreground_activity() == ForegroundActivity::Idle {+ if !self.foreground_activity().is_active() {return;}let desired = if self.has_pending_turn_action() {@@ -4332,15 +4384,30 @@ impl AcpThread {"Session does not report foreground state");let previous = self.foreground_activity();- let was_active = previous != ForegroundActivity::Idle;+ let was_active = previous.is_active();+ self.received_session_state = true;self.set_foreground_state(state, cx);- if let acp_v2::StateUpdate::Idle(idle) = self.activity.state() {+ if let Some(acp_v2::StateUpdate::Idle(idle)) = self.activity.state() {let stop_reason = idle.stop_reason.clone();if let Some(usage) = &idle.usage {+ let reported = ReportedTokenUsage {+ activity_generation: self.activity.generation(),+ input_tokens: usage.input_tokens,+ output_tokens: usage.output_tokens,+ };+ let changed = self.reported_usage != Some(reported);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);+ self.reported_usage = Some(reported);+ if changed {+ cx.emit(AcpThreadEvent::TokenUsageUpdated(+ OutputTokensUpdate::Snapshot {+ activity_generation: reported.activity_generation,+ output_tokens: usage.output_tokens,+ },+ ));+ }}if was_active {self.flush_streaming_text(cx);@@ -4368,6 +4435,11 @@ impl AcpThread {if previous != self.foreground_activity() {cx.emit(AcpThreadEvent::StatusChanged);}+ if previous == ForegroundActivity::Unconfirmed+ && self.foreground_activity() == ForegroundActivity::Idle+ {+ cx.emit(AcpThreadEvent::ActivityConfirmedIdle);+ }Ok(())}@@ -5397,8 +5469,16 @@ impl AcpThread {if usage.is_none() {self.cost = None;}+ let output = usage+ .as_ref()+ .map_or(OutputTokensUpdate::Unchanged, |usage| {+ OutputTokensUpdate::LegacyAdd {+ activity_generation: self.activity.generation(),+ output_tokens: usage.output_tokens,+ }+ });self.token_usage = usage;- cx.emit(AcpThreadEvent::TokenUsageUpdated);+ cx.emit(AcpThreadEvent::TokenUsageUpdated(output));}pub fn update_usage(&mut self, update: acp_v2::UsageUpdate, cx: &mut Context<Self>) {@@ -5413,7 +5493,9 @@ impl AcpThread {meta: cost.meta,});}- cx.emit(AcpThreadEvent::TokenUsageUpdated);+ cx.emit(AcpThreadEvent::TokenUsageUpdated(+ OutputTokensUpdate::Unchanged,+ ));}pub fn update_retry_status(&mut self, status: RetryStatus, cx: &mut Context<Self>) {@@ -6816,7 +6898,12 @@ impl AcpThread {let usage = this.token_usage.get_or_insert_with(Default::default);usage.input_tokens = response_usage.input_tokens;usage.output_tokens = response_usage.output_tokens;- cx.emit(AcpThreadEvent::TokenUsageUpdated);+ cx.emit(AcpThreadEvent::TokenUsageUpdated(+ OutputTokensUpdate::LegacyAdd {+ activity_generation: this.activity.generation(),+ output_tokens: usage.output_tokens,+ },+ ));}if is_same_turn {@@ -7137,7 +7224,7 @@ impl AcpThread {}fn update_last_checkpoint_if_changed(&mut self, cx: &mut Context<Self>) -> Task<Result<()>> {- if self.foreground_activity() == ForegroundActivity::Idle {+ if !self.foreground_activity().is_active() {return Task::ready(Ok(()));}let activity_generation = self.activity_generation();@@ -7182,7 +7269,7 @@ impl AcpThread {}this.update(cx, |this, cx| {- if this.foreground_activity() == ForegroundActivity::Idle+ if !this.foreground_activity().is_active()|| this.activity_generation() != activity_generation{return;@@ -12031,7 +12118,7 @@ mod tests {assert!(thread.activity_started_at().is_some());assert!(thread.activity_duration().is_some());assert!(- matches!(thread.foreground_state(), acp_v2::StateUpdate::Running(running)+ matches!(thread.foreground_state(), Some(acp_v2::StateUpdate::Running(running))if running.meta.as_ref().and_then(|meta| meta.get("future")) == Some(&json!(42))));});@@ -12069,7 +12156,7 @@ mod tests {SubmissionState::Pending));assert!(- matches!(thread.foreground_state(), acp_v2::StateUpdate::Idle(idle)+ matches!(thread.foreground_state(), Some(acp_v2::StateUpdate::Idle(idle))if idle.stop_reason == Some(acp_v2::StopReason::Refusal)));});@@ -12229,7 +12316,7 @@ mod tests {.expect("running");assert!(!thread.had_error());thread.update_session_state(idle.clone(), cx).expect("idle");- assert_eq!(thread.foreground_state(), &idle);+ assert_eq!(thread.foreground_state(), Some(&idle));assert_eq!(thread.had_error(), expected_had_error);assert_eq!(thread.entries().len(), 3);assert!(matches!(@@ -12258,6 +12345,382 @@ mod tests {});}+ #[gpui::test]+ async fn test_unconfirmed_activity_waits_for_idle_without_inventing_completion(+ cx: &mut TestAppContext,+ ) {+ init_test(cx);+ for initially_blocked in [false, true] {+ let (thread, connection) = new_receipt_test_thread(cx).await;+ let events = Rc::new(RefCell::new((0, 0)));+ let _subscription = cx.update(|cx| {+ cx.subscribe(&thread, {+ let events = events.clone();+ move |_, event, _| match event {+ AcpThreadEvent::Stopped { .. } => events.borrow_mut().0 += 1,+ AcpThreadEvent::ActivityConfirmedIdle => events.borrow_mut().1 += 1,+ _ => {}+ }+ })+ });+ let mut cancelled = thread.update(cx, |thread, cx| {+ thread.mark_activity_unconfirmed(cx);+ assert_eq!(thread.status(), ThreadStatus::Unconfirmed);+ assert!(thread.foreground_state().is_none());+ assert!(thread.activity_started_at().is_none());+ assert!(thread.activity_duration().is_none());+ assert!(!thread.is_idle_for_retention());+ thread.cancel(cx)+ });+ cx.run_until_parked();+ assert!((&mut cancelled).now_or_never().is_none());+ assert_eq!(connection.take_cancel_calls().len(), 1);+ if initially_blocked {+ thread.update(cx, |thread, cx| {+ thread+ .update_session_state(+ acp_v2::StateUpdate::RequiresAction(+ acp_v2::RequiresActionStateUpdate::new(),+ ),+ cx,+ )+ .expect("first report is blocked work");+ thread.mark_activity_unconfirmed(cx);+ assert_eq!(+ thread.foreground_activity(),+ ForegroundActivity::RequiresAction+ );+ assert_eq!(thread.activity_generation(), 1);+ });+ cx.run_until_parked();+ assert!((&mut cancelled).now_or_never().is_none());+ }+ for _ in 0..2 {+ thread.update(cx, |thread, cx| {+ thread+ .update_session_state(+ acp_v2::StateUpdate::Idle(+ acp_v2::IdleStateUpdate::new()+ .stop_reason(acp_v2::StopReason::Cancelled),+ ),+ cx,+ )+ .expect("confirmed idle");+ });+ }+ cancelled.await.expect("stop is now confirmed");+ cx.run_until_parked();+ assert_eq!(+ *events.borrow(),+ (+ usize::from(initially_blocked),+ usize::from(!initially_blocked)+ )+ );+ thread.read_with(cx, |thread, _| {+ assert_eq!(thread.status(), ThreadStatus::Idle);+ assert_eq!(thread.activity_generation(), u64::from(initially_blocked));+ assert!(thread.is_idle_for_retention());+ });+ }+ }++ #[gpui::test]+ async fn test_unconfirmed_stop_reports_observation_loss(cx: &mut TestAppContext) {+ init_test(cx);+ let (thread, _) = new_receipt_test_thread(cx).await;+ let mut cancelled = thread.update(cx, |thread, cx| {+ thread.mark_activity_unconfirmed(cx);+ thread.cancel(cx)+ });+ cx.run_until_parked();+ assert!((&mut cancelled).now_or_never().is_none());+ thread.update(cx, |thread, cx| thread.handle_connection_lost(cx));+ assert!(+ cancelled+ .await+ .expect_err("observation loss cannot confirm stop")+ .to_string()+ .contains("before cancellation was confirmed")+ );+ thread.read_with(cx, |thread, _| {+ assert_eq!(+ thread.foreground_activity(),+ ForegroundActivity::Unconfirmed+ );+ assert_eq!(thread.activity_generation(), 0);+ assert!(thread.activity_duration().is_none());+ });+ }++ #[gpui::test]+ async fn test_reported_snapshots_are_idempotent_and_preserve_url_interactions(+ cx: &mut TestAppContext,+ ) {+ init_test(cx);+ let (thread, _) = new_receipt_test_thread(cx).await;+ thread.update(cx, |thread, cx| thread.mark_activity_unconfirmed(cx));+ let stops = Rc::new(RefCell::new(Vec::new()));+ let usage_updates = Rc::new(RefCell::new(Vec::new()));+ let _subscription = cx.update(|cx| {+ cx.subscribe(&thread, {+ let stops = stops.clone();+ let usage_updates = usage_updates.clone();+ move |_, event, _| match event {+ AcpThreadEvent::Stopped {+ activity_generation,+ stop_reason,+ ..+ } => {+ stops+ .borrow_mut()+ .push((*activity_generation, stop_reason.clone()));+ }+ AcpThreadEvent::TokenUsageUpdated(update) => {+ usage_updates.borrow_mut().push(*update)+ }+ _ => {}+ }+ })+ });+ let (entry_id, response) = thread.update(cx, |thread, cx| {+ thread+ .request_elicitation_with_id(+ acp_v2::CreateElicitationRequest::new(+ acp_v2::ElicitationUrlMode::new(+ acp_v2::ElicitationSessionScope::new(thread.session_id().clone()),+ "current-url",+ "https://example.com/finish",+ ),+ "Continue in browser",+ ),+ cx,+ )+ .expect("URL elicitation")+ });+ thread.update(cx, |thread, cx| {+ thread.respond_to_elicitation(+ &entry_id,+ acp_v2::CreateElicitationResponse::new(acp_v2::ElicitationAction::Accept(+ acp_v2::ElicitationAcceptAction::new(),+ )),+ cx,+ );+ });+ assert!(matches!(+ response.await.action,+ acp_v2::ElicitationAction::Accept(_)+ ));+ let idle: acp_v2::StateUpdate = serde_json::from_value(json!({+ "state": "idle", "stopReason": "cancelled",+ "usage": {"totalTokens": 12, "inputTokens": 5, "outputTokens": 7}+ }))+ .expect("idle snapshot");+ for _ in 0..2 {+ thread+ .update(cx, |thread, cx| {+ thread.update_session_state(idle.clone(), cx)+ })+ .expect("initial snapshot");+ }+ cx.run_until_parked();+ assert!(stops.borrow().is_empty());+ assert_eq!(usage_updates.borrow().len(), 1);+ thread.read_with(cx, |thread, _| {+ assert_eq!(thread.activity_generation(), 0);+ assert!(matches!(+ thread+ .elicitation(&entry_id)+ .expect("URL interaction")+ .1+ .status,+ ElicitationStatus::Accepted+ ));+ });+ for output_tokens in [7, 9] {+ thread.update(cx, |thread, cx| {+ thread+ .update_session_state(+ acp_v2::StateUpdate::RequiresAction(+ acp_v2::RequiresActionStateUpdate::new(),+ ),+ cx,+ )+ .expect("work starts blocked");+ });+ let generation = thread.read_with(cx, |thread, _| thread.activity_generation());+ let snapshot: acp_v2::StateUpdate = serde_json::from_value(json!({+ "state": "idle", "stopReason": "end_turn",+ "usage": {"totalTokens": 5 + output_tokens, "inputTokens": 5, "outputTokens": output_tokens}+ })).expect("completion snapshot");+ for _ in 0..2 {+ thread+ .update(cx, |thread, cx| {+ thread.update_session_state(snapshot.clone(), cx)+ })+ .expect("completion or repeat");+ }+ cx.run_until_parked();+ assert_eq!(stops.borrow().len(), generation as usize);+ assert_eq!(+ usage_updates.borrow().last(),+ Some(&OutputTokensUpdate::Snapshot {+ activity_generation: generation,+ output_tokens+ })+ );+ }+ assert_eq!(+ usage_updates.borrow().len(),+ 3,+ "one usage snapshot per observed interval"+ );+ let correction: acp_v2::StateUpdate = serde_json::from_value(json!({+ "state": "idle", "stopReason": "cancelled",+ "usage": {"totalTokens": 15, "inputTokens": 5, "outputTokens": 10}+ }))+ .expect("updated idle information");+ thread+ .update(cx, |thread, cx| thread.update_session_state(correction, cx))+ .expect("idle information changes");+ cx.run_until_parked();+ assert_eq!(stops.borrow().len(), 2);+ assert_eq!(usage_updates.borrow().len(), 4);+ thread.update(cx, |thread, cx| {+ assert!(matches!(+ thread.elicitation(&entry_id).expect("URL").1.status,+ ElicitationStatus::Accepted+ ));+ thread.complete_url_elicitation(&"current-url".into(), cx);+ });+ }++ #[gpui::test]+ async fn test_reported_interactions_do_not_invent_foreground_transitions(+ cx: &mut TestAppContext,+ ) {+ init_test(cx);+ let (thread, _) = new_receipt_test_thread(cx).await;+ let (permission_id, permission) = thread.update(cx, |thread, cx| {+ thread+ .request_permission(test_generic_permission_request(thread, "background"), cx)+ .expect("background permission")+ });+ let (elicitation_id, elicitation) = request_test_form_elicitation(&thread, cx);+ cx.run_until_parked();+ assert_eq!(+ thread.read_with(cx, |thread, _| thread.foreground_activity()),+ ForegroundActivity::Idle+ );+ thread.update(cx, |thread, cx| {+ thread+ .update_session_state(+ acp_v2::StateUpdate::RequiresAction(acp_v2::RequiresActionStateUpdate::new()),+ cx,+ )+ .expect("blocked foreground work");+ thread.cancel_permission_request(permission_id, cx);+ });+ assert_eq!(+ permission.await,+ acp_v2::RequestPermissionOutcome::Cancelled+ );+ cx.run_until_parked();+ assert_eq!(+ thread.read_with(cx, |thread, _| thread.foreground_activity()),+ ForegroundActivity::RequiresAction+ );+ thread.update(cx, |thread, cx| {+ thread+ .update_session_state(+ acp_v2::StateUpdate::Running(acp_v2::RunningStateUpdate::new()),+ cx,+ )+ .expect("other foreground work can progress");+ });+ cx.run_until_parked();+ assert_eq!(+ thread.read_with(cx, |thread, _| thread.foreground_activity()),+ ForegroundActivity::Running+ );+ thread.update(cx, |thread, cx| {+ thread.cancel_elicitation(&elicitation_id, cx)+ });+ assert_eq!(elicitation.await.action, acp_v2::ElicitationAction::Cancel);+ cx.run_until_parked();+ 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 end");+ assert_eq!(thread.activity_generation(), 1);+ assert!(thread.latest_submission_id().is_none());+ });+ }++ #[gpui::test]+ async fn test_reported_idle_preserves_unknown_completion_outcomes(cx: &mut TestAppContext) {+ init_test(cx);+ let (thread, _) = new_receipt_test_thread(cx).await;+ let stops = Rc::new(RefCell::new(Vec::new()));+ let _subscription = cx.update(|cx| {+ cx.subscribe(&thread, {+ let stops = stops.clone();+ move |_, event, _| {+ if let AcpThreadEvent::Stopped { stop_reason, .. } = event {+ stops.borrow_mut().push(stop_reason.clone());+ }+ }+ })+ });+ for reason in [+ None,+ Some(json!(null)),+ Some(json!(7)),+ Some(json!({"invalid": true})),+ Some(json!("_future")),+ ] {+ let mut snapshot = json!({"state": "idle"});+ if let Some(reason) = reason {+ snapshot["stopReason"] = reason;+ }+ let snapshot: acp_v2::StateUpdate =+ serde_json::from_value(snapshot).expect("tolerant idle decoding");+ thread.update(cx, |thread, cx| {+ thread+ .update_session_state(+ acp_v2::StateUpdate::RequiresAction(+ acp_v2::RequiresActionStateUpdate::new(),+ ),+ cx,+ )+ .expect("active interval");+ thread+ .update_session_state(snapshot.clone(), cx)+ .expect("idle");+ thread+ .update_session_state(snapshot, cx)+ .expect("idle repeat");+ assert_eq!(thread.foreground_activity(), ForegroundActivity::Idle);+ assert!(!thread.had_error());+ });+ cx.run_until_parked();+ }+ let stops = stops.borrow();+ assert_eq!(stops.len(), 5);+ assert!(+ stops+ .iter()+ .all(|reason| matches!(reason, None | Some(acp_v2::StopReason::Other(_))))+ );+ }+#[gpui::test]async fn test_reported_activity_survives_rejection_and_idle_keeps_unrelated_actions(cx: &mut TestAppContext,diff --git a/crates/acp_thread/src/submission.rs b/crates/acp_thread/src/submission.rsindex 5ebccf54c1c..53bfe1b34e8 100644--- a/crates/acp_thread/src/submission.rs+++ b/crates/acp_thread/src/submission.rs@@ -323,13 +323,20 @@ impl SessionSubmissions {#[derive(Copy, Clone, Debug, PartialEq, Eq)]pub enum ForegroundActivity {+ Unconfirmed,Idle,Running,RequiresAction,}+impl ForegroundActivity {+ pub fn is_active(self) -> bool {+ matches!(self, Self::Running | Self::RequiresAction)+ }+}+pub(crate) struct SessionActivity {- state: acp_v2::StateUpdate,+ state: Option<acp_v2::StateUpdate>,generation: u64,started_at: Option<Instant>,duration: Option<Duration>,@@ -341,7 +348,7 @@ pub(crate) struct SessionActivity {impl Default for SessionActivity {fn default() -> Self {Self {- state: acp_v2::StateUpdate::Idle(acp_v2::IdleStateUpdate::new()),+ state: Some(acp_v2::StateUpdate::Idle(acp_v2::IdleStateUpdate::new())),generation: 0,started_at: None,duration: None,@@ -353,15 +360,20 @@ impl Default for SessionActivity {}impl SessionActivity {- pub(crate) fn state(&self) -> &acp_v2::StateUpdate {- &self.state+ pub(crate) fn state(&self) -> Option<&acp_v2::StateUpdate> {+ self.state.as_ref()+ }++ pub(crate) fn mark_unconfirmed(&mut self) {+ self.state = None;}pub(crate) fn phase(&self) -> ForegroundActivity {match self.state {- acp_v2::StateUpdate::Idle(_) => ForegroundActivity::Idle,- acp_v2::StateUpdate::RequiresAction(_) => ForegroundActivity::RequiresAction,- _ => ForegroundActivity::Running,+ None => ForegroundActivity::Unconfirmed,+ Some(acp_v2::StateUpdate::Idle(_)) => ForegroundActivity::Idle,+ Some(acp_v2::StateUpdate::RequiresAction(_)) => ForegroundActivity::RequiresAction,+ Some(_) => ForegroundActivity::Running,}}@@ -387,15 +399,17 @@ impl SessionActivity {pub(crate) fn update(&mut self, state: acp_v2::StateUpdate, first_entry_index: usize) {let previous = self.phase();- self.state = state;+ self.state = Some(state);let current = self.phase();- if previous == ForegroundActivity::Idle && current != ForegroundActivity::Idle {+ if !previous.is_active() && current.is_active() {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 {+ } else if previous.is_active() && current == ForegroundActivity::Idle {self.duration = self.started_at.map(|started| started.elapsed());+ }+ if current == ForegroundActivity::Idle {for waiter in self.cancel_waiters.drain(..) {if waiter.send(()).is_err() {log::debug!("Foreground cancellation observer was dropped");diff --git a/crates/agent/src/agent.rs b/crates/agent/src/agent.rsindex 3c881d11634..8e2a0cc0c29 100644--- a/crates/agent/src/agent.rs+++ b/crates/agent/src/agent.rs@@ -5122,7 +5122,7 @@ mod internal_tests {acp_thread.read_with(cx, |thread, _| {assert!(matches!(thread.foreground_state(),- acp_v2::StateUpdate::Running(_)+ Some(acp_v2::StateUpdate::Running(_))));});drop(completion);@@ -5144,7 +5144,7 @@ mod internal_tests {cx.run_until_parked();acp_thread.read_with(cx, |thread, _| {assert!(- matches!(thread.foreground_state(), acp_v2::StateUpdate::Idle(idle)+ matches!(thread.foreground_state(), Some(acp_v2::StateUpdate::Idle(idle))if idle.stop_reason == Some(acp_v2::StopReason::EndTurn)));});@@ -5217,7 +5217,7 @@ mod internal_tests {cx.run_until_parked();acp_thread.read_with(cx, |thread, cx| {assert!(- matches!(thread.foreground_state(), acp_v2::StateUpdate::Idle(idle)+ matches!(thread.foreground_state(), Some(acp_v2::StateUpdate::Idle(idle))if idle.stop_reason == Some(acp_v2::StopReason::EndTurn)));assert!(thread.to_markdown(cx).contains("retried"));diff --git a/crates/agent_servers/src/acp/v1.rs b/crates/agent_servers/src/acp/v1.rsindex 3b82b3dbdd8..cd7e6a5b92d 100644--- a/crates/agent_servers/src/acp/v1.rs+++ b/crates/agent_servers/src/acp/v1.rs@@ -3762,7 +3762,7 @@ mod tests {cx.subscribe(&harness.thread, {let events = events.clone();move |_, event, _| {- if matches!(event, AcpThreadEvent::TokenUsageUpdated) {+ if matches!(event, AcpThreadEvent::TokenUsageUpdated(_)) {*events.borrow_mut() += 1;}assert!(!matches!(event, AcpThreadEvent::Error));@@ -4971,7 +4971,7 @@ mod tests {thread.read_with(cx, |thread, _| {assert!(thread.uses_reported_activity());assert_eq!(thread.foreground_activity(), phase);- assert_eq!(thread.foreground_state(), &expected);+ assert_eq!(thread.foreground_state(), Some(&expected));assert!(thread.latest_submission_id().is_none());assert!(!thread.has_unsettled_submissions());assert!(thread.entries().is_empty());diff --git a/crates/agent_servers/src/acp/v2.rs b/crates/agent_servers/src/acp/v2.rsindex 13bef20f9cf..9f80fbe8ce7 100644--- a/crates/agent_servers/src/acp/v2.rs+++ b/crates/agent_servers/src/acp/v2.rs@@ -739,6 +739,7 @@ impl AcpV2Connection {Ok(thread) => thread,Err(error) => return Task::ready(Err(error)),};+ thread.update(cx, |thread, cx| thread.mark_activity_unconfirmed(cx));let request = self.connection.prepare_request(request);let request_id = request.id().clone();let cancellation = request.cancellation_handle();@@ -760,6 +761,11 @@ impl AcpV2Connection {let this = this.upgrade().context("Connection was released")?;let thread = thread.upgrade().context("Session was released")?;cx.update(|cx| {+ if !thread.read(cx).has_received_session_state() {+ log::warn!(+ "Agent resumed the session without reporting its current foreground state; activity remains unconfirmed"+ );+ }this.apply_initial_state(&thread,response.config_options,@@ -1673,6 +1679,15 @@ mod tests {})}+ fn resume_state(&self, state: acp::StateUpdate) {+ self.agent+ .send_notification(acp::UpdateSessionNotification::new(+ "saved",+ acp::SessionUpdate::StateUpdate(state),+ ))+ .expect("current resume state");+ }+fn reopen(&self,replay_history: bool,@@ -2854,6 +2869,364 @@ done}}+ #[gpui::test]+ async fn v2_state_sdk_separates_preinsertion_work_and_local_command_completion(+ cx: &mut TestAppContext,+ ) {+ use acp_thread::{+ AcpThreadEvent, AgentThreadEntry, ForegroundActivity, SubmissionResponse,+ };+ let harness = SessionHarness::new(session_capabilities(), vec![], vec![], cx).await;+ let thread = harness.thread(cx).await;+ let session_id = thread.read_with(cx, |thread, _| {+ assert_eq!(thread.foreground_activity(), ForegroundActivity::Idle);+ assert!(!thread.has_received_session_state());+ thread.session_id().clone()+ });+ let stops = Rc::new(RefCell::new(Vec::new()));+ let _subscription = cx.update(|cx| {+ cx.subscribe(&thread, {+ let stops = stops.clone();+ move |_, event, _| {+ if let AcpThreadEvent::Stopped { stop_reason, .. } = event {+ stops.borrow_mut().push(stop_reason.clone());+ }+ }+ })+ });+ let rejected = thread.update(cx, |thread, cx| thread.send(vec!["/rejected".into()], cx));+ let (_, responder) = bounded(harness.prompts.recv(), cx).await.expect("prompt");+ harness+ .agent+ .send_notification(acp::UpdateSessionNotification::new(+ session_id.clone(),+ acp::SessionUpdate::StateUpdate(acp::StateUpdate::Running(+ acp::RunningStateUpdate::new(),+ )),+ ))+ .expect("foreground hook before insertion");+ responder+ .respond_with_error(agent_client_protocol::Error::invalid_params())+ .expect("rejection");+ bounded(rejected, cx).await.expect_err("not inserted");+ thread.read_with(cx, |thread, _| {+ assert_eq!(thread.foreground_activity(), ForegroundActivity::Running);+ assert!(thread.entries().is_empty());+ });+ assert!(stops.borrow().is_empty());+ harness+ .agent+ .send_notification(acp::UpdateSessionNotification::new(+ session_id.clone(),+ acp::SessionUpdate::StateUpdate(+ acp::StateUpdate::Idle(acp::IdleStateUpdate::new()),+ ),+ ))+ .expect("hook work ends separately");+ cx.run_until_parked();+ assert_eq!(*stops.borrow(), [None]);+ let command = thread.update(cx, |thread, cx| thread.send(vec!["/local".into()], cx));+ let (_, responder) = bounded(harness.prompts.recv(), cx)+ .await+ .expect("local command");+ for update in [+ acp::SessionUpdate::UserMessage(+ acp::UserMessage::new("local-command").content(vec!["/local".into()]),+ ),+ acp::SessionUpdate::StateUpdate(acp::StateUpdate::Running(+ acp::RunningStateUpdate::new(),+ )),+ ] {+ harness+ .agent+ .send_notification(acp::UpdateSessionNotification::new(+ session_id.clone(),+ update,+ ))+ .expect("local command handling");+ }+ responder+ .respond(acp::PromptResponse::new("local-command"))+ .expect("insertion receipt");+ assert!(matches!(+ bounded(command, cx).await.expect("accepted"),+ Some(SubmissionResponse::Accepted(_))+ ));+ assert_eq!(+ thread.read_with(cx, |thread, _| thread.foreground_activity()),+ ForegroundActivity::Running+ );+ harness+ .agent+ .send_notification(acp::UpdateSessionNotification::new(+ session_id,+ acp::SessionUpdate::StateUpdate(acp::StateUpdate::Idle(+ acp::IdleStateUpdate::new().stop_reason(acp::StopReason::EndTurn),+ )),+ ))+ .expect("local completion without model output");+ cx.run_until_parked();+ assert_eq!(*stops.borrow(), [None, Some(acp::StopReason::EndTurn)]);+ thread.read_with(cx, |thread, _| {+ assert_eq!(thread.foreground_activity(), ForegroundActivity::Idle);+ assert!(matches!(+ thread.entries(),+ [AgentThreadEntry::UserMessage(_)]+ ));+ });+ }++ #[gpui::test]+ async fn v2_resume_sdk_synchronizes_current_state_without_inventing_completions(+ cx: &mut TestAppContext,+ ) {+ use acp_thread::{AcpThreadEvent, ForegroundActivity};+ for replay_history in [false, true] {+ for snapshot in [+ json!({"state": "idle", "stopReason": "cancelled"}),+ json!({"state": "running"}),+ json!({"state": "requires_action"}),+ ] {+ let harness = SessionHarness::new(session_capabilities(), vec![], vec![], cx).await;+ let mut loading = harness.reopen(replay_history, cx);+ let (_, responder) = bounded(harness.resume_requests.recv(), cx)+ .await+ .expect("resume");+ let opening = harness+ .client+ .sessions+ .borrow()+ .get(&"saved".into())+ .expect("registered before replay")+ .thread+ .upgrade()+ .expect("owner");+ let stops = Rc::new(RefCell::new(Vec::new()));+ let _subscription = cx.update(|cx| {+ cx.subscribe(&opening, {+ let stops = stops.clone();+ move |_, event, _| {+ if let AcpThreadEvent::Stopped {+ activity_generation,+ ..+ } = event+ {+ stops.borrow_mut().push(*activity_generation);+ }+ }+ })+ });+ if replay_history {+ harness+ .agent+ .send_notification(acp::UpdateSessionNotification::new(+ "saved",+ acp::SessionUpdate::UserMessage(+ acp::UserMessage::new("history")+ .content(vec!["retained history".into()]),+ ),+ ))+ .expect("history");+ }+ let snapshot: acp::StateUpdate = serde_json::from_value(snapshot).expect("state");+ harness.resume_state(snapshot.clone());+ cx.run_until_parked();+ assert!((&mut loading).now_or_never().is_none());+ opening.read_with(cx, |thread, _| {+ assert_eq!(thread.foreground_state(), Some(&snapshot));+ assert!(thread.has_received_session_state());+ assert_eq!(thread.entries().len(), usize::from(replay_history));+ });+ assert!(+ stops.borrow().is_empty(),+ "resume snapshot is not a completion"+ );+ let latest = acp::StateUpdate::RequiresAction(+ acp::RequiresActionStateUpdate::new().meta(meta("latest")),+ );+ harness.resume_state(latest.clone());+ responder+ .respond(acp::ResumeSessionResponse::new())+ .expect("resume response");+ let thread = bounded(loading, cx).await.expect("synchronized owner");+ assert_eq!(+ thread.read_with(cx, |thread, _| thread.foreground_state().cloned()),+ Some(latest.clone())+ );+ harness.resume_state(latest.clone());+ cx.run_until_parked();+ thread.read_with(cx, |thread, _| {+ assert_eq!(thread.foreground_state(), Some(&latest));+ assert_eq!(+ thread.foreground_activity(),+ ForegroundActivity::RequiresAction+ );+ assert_eq!(thread.activity_generation(), 1);+ });+ assert!(stops.borrow().is_empty());+ let idle = acp::StateUpdate::Idle(+ acp::IdleStateUpdate::new().stop_reason(acp::StopReason::EndTurn),+ );+ harness.resume_state(idle.clone());+ harness.resume_state(idle);+ cx.run_until_parked();+ assert_eq!(*stops.borrow(), [1]);+ assert_eq!(+ thread.read_with(cx, |thread, _| thread.foreground_activity()),+ ForegroundActivity::Idle+ );+ assert!(harness.closes.is_empty());+ }+ }+ }++ #[gpui::test]+ async fn v2_resume_sdk_keeps_attachment_without_state_snapshot(cx: &mut TestAppContext) {+ use acp_thread::{AcpThreadEvent, ForegroundActivity, SubmissionResponse, ThreadStatus};+ for (replay_history, late_snapshot) in+ [(false, false), (true, false), (false, true), (true, true)]+ {+ let harness = SessionHarness::new(session_capabilities(), vec![], vec![], cx).await;+ let loading = harness.reopen(replay_history, cx);+ let (_, responder) = bounded(harness.resume_requests.recv(), cx)+ .await+ .expect("resume");+ let owner = harness+ .client+ .sessions+ .borrow()+ .get(&"saved".into())+ .expect("owner")+ .thread+ .clone();+ let opening = owner.upgrade().expect("opening owner");+ let stops = Rc::new(RefCell::new(0));+ let _subscription = cx.update(|cx| {+ cx.subscribe(&opening, {+ let stops = stops.clone();+ move |_, event, _| {+ if matches!(event, AcpThreadEvent::Stopped { .. }) {+ *stops.borrow_mut() += 1;+ }+ }+ })+ });+ let input = cx.background_spawn(+ harness+ .agent+ .send_request(acp::CreateElicitationRequest::new(+ acp::ElicitationFormMode::new(+ acp::ElicitationRequestScope::new(responder.id().clone()),+ acp::ElicitationSchema::new(),+ ),+ "Resume setup input",+ ))+ .block_task(),+ );+ cx.run_until_parked();+ if replay_history {+ harness+ .agent+ .send_notification(acp::UpdateSessionNotification::new(+ "saved",+ acp::SessionUpdate::UserMessage(+ acp::UserMessage::new("retained")+ .content(vec!["retained history".into()]),+ ),+ ))+ .expect("replay without state");+ }+ let initial = initial_response();+ responder+ .respond(+ acp::ResumeSessionResponse::new()+ .config_options(initial.config_options.clone())+ .available_commands(initial.available_commands.clone()),+ )+ .expect("missing snapshot response");+ if late_snapshot {+ harness.resume_state(acp::StateUpdate::Idle(acp::IdleStateUpdate::new()));+ }+ let thread = bounded(loading, cx).await.expect("attachment succeeds");+ assert_eq!(thread.entity_id(), opening.entity_id());+ assert_eq!(+ bounded(input, cx)+ .await+ .expect("finished resume input cleanup")+ .action,+ acp::ElicitationAction::Cancel,+ );+ cx.run_until_parked();+ thread.read_with(cx, |thread, _| {+ assert_eq!(thread.entries().len(), usize::from(replay_history));+ assert_eq!(thread.available_commands(), initial.available_commands);+ assert_eq!(thread.activity_generation(), 0);+ assert_eq!(+ thread.status(),+ if late_snapshot {+ ThreadStatus::Idle+ } else {+ ThreadStatus::Unconfirmed+ }+ );+ if !late_snapshot {+ assert!(thread.foreground_state().is_none());+ assert!(!thread.is_idle_for_retention());+ }+ });+ let options = cx+ .read(|cx| harness.client.session_config_options(&"saved".into(), cx))+ .expect("config survives missing state");+ assert_eq!(options.config_options(), initial.config_options);+ let reused = bounded(harness.reopen(replay_history, cx), cx)+ .await+ .expect("reuse binding");+ assert_eq!(reused.entity_id(), thread.entity_id());+ assert!(harness.resume_requests.is_empty(), "no forced retry");+ if !late_snapshot {+ let sending =+ thread.update(cx, |thread, cx| thread.send(vec!["manual".into()], cx));+ let (_, responder) = bounded(harness.prompts.recv(), cx)+ .await+ .expect("manual send");+ responder+ .respond(acp::PromptResponse::new("manual"))+ .expect("receipt");+ harness+ .agent+ .send_notification(acp::UpdateSessionNotification::new(+ "saved",+ acp::SessionUpdate::UserMessage(+ acp::UserMessage::new("manual").content(vec!["manual".into()]),+ ),+ ))+ .expect("echo");+ assert!(matches!(+ bounded(sending, cx).await.expect("accepted"),+ Some(SubmissionResponse::Accepted(_))+ ));+ assert_eq!(+ thread.read_with(cx, |thread, _| thread.foreground_activity()),+ ForegroundActivity::Unconfirmed+ );+ harness.resume_state(acp::StateUpdate::Idle(+ acp::IdleStateUpdate::new().stop_reason(acp::StopReason::Cancelled),+ ));+ cx.run_until_parked();+ }+ assert_eq!(+ *stops.borrow(),+ 0,+ "confirmation does not create a completion"+ );+ assert_eq!(+ thread.read_with(cx, |thread, _| thread.foreground_activity()),+ ForegroundActivity::Idle+ );+ assert!(harness.closes.is_empty());+ }+ }+#[gpui::test]async fn v2_resume_sdk_applies_replay_before_reply_and_keeps_receipt_transport(cx: &mut TestAppContext,@@ -2895,9 +3268,6 @@ doneacp::SessionUpdate::UserMessage(acp::UserMessage::new("history").content(vec!["old question".into()]),),- acp::SessionUpdate::StateUpdate(acp::StateUpdate::Running(- acp::RunningStateUpdate::new(),- )),acp::SessionUpdate::SessionInfoUpdate(acp::SessionInfoUpdate::new().title("Agent title"),),@@ -2910,6 +3280,7 @@ done.send_notification(acp::UpdateSessionNotification::new("saved", update)).expect("replay notification");}+ harness.resume_state(acp::StateUpdate::Running(acp::RunningStateUpdate::new()));cx.run_until_parked();assert!((&mut loading).now_or_never().is_none(),@@ -3020,6 +3391,7 @@ done.await.expect_err("cannot promise missing history");}+ harness.resume_state(acp::StateUpdate::Idle(acp::IdleStateUpdate::new()));responder.respond(acp::ResumeSessionResponse::new()).expect("resumed");@@ -3115,6 +3487,7 @@ done),)).expect("late old replay");+ harness.resume_state(acp::StateUpdate::Idle(acp::IdleStateUpdate::new()));responder.respond(acp::ResumeSessionResponse::new()).expect("old RPC settles");@@ -3130,6 +3503,7 @@ done),)).expect("replacement replay");+ harness.resume_state(acp::StateUpdate::Idle(acp::IdleStateUpdate::new()));responder.respond(acp::ResumeSessionResponse::new()).expect("replacement response");@@ -3204,6 +3578,7 @@ donelet (_, responder) = bounded(harness.resume_requests.recv(), cx).await.expect("explicit retry");+ harness.resume_state(acp::StateUpdate::Idle(acp::IdleStateUpdate::new()));responder.respond(acp::ResumeSessionResponse::new()).expect("retry response");diff --git a/crates/agent_ui/src/agent_diff.rs b/crates/agent_ui/src/agent_diff.rsindex 48f6487560c..128b6736d5f 100644--- a/crates/agent_ui/src/agent_diff.rs+++ b/crates/agent_ui/src/agent_diff.rs@@ -1468,9 +1468,10 @@ impl AgentDiff {self.update_reviewing_editors(workspace, window, cx);}AcpThreadEvent::TitleUpdated+ | AcpThreadEvent::ActivityConfirmedIdle| AcpThreadEvent::StatusChanged| AcpThreadEvent::SubmissionUpdated(_)- | AcpThreadEvent::TokenUsageUpdated+ | AcpThreadEvent::TokenUsageUpdated(_)| AcpThreadEvent::NoticesUpdated| AcpThreadEvent::SubagentSpawned(_)| AcpThreadEvent::EntriesRemoved(_)diff --git a/crates/agent_ui/src/conversation_view.rs b/crates/agent_ui/src/conversation_view.rsindex 3f11b5439b4..1876149d3e3 100644--- a/crates/agent_ui/src/conversation_view.rs+++ b/crates/agent_ui/src/conversation_view.rs@@ -344,10 +344,11 @@ impl Conversation {}}AcpThreadEvent::NewEntry+ | AcpThreadEvent::ActivityConfirmedIdle| AcpThreadEvent::StatusChanged| AcpThreadEvent::SubmissionUpdated(_)| AcpThreadEvent::TitleUpdated- | AcpThreadEvent::TokenUsageUpdated+ | AcpThreadEvent::TokenUsageUpdated(_)| AcpThreadEvent::EntryUpdated(_)| AcpThreadEvent::EntriesRemoved(_)| AcpThreadEvent::Retry(_)@@ -762,11 +763,12 @@ fn affects_thread_metadata(event: &AcpThreadEvent) -> bool {| AcpThreadEvent::WorkingDirectoriesUpdated => true,// --AcpThreadEvent::EntryUpdated(_)+ | AcpThreadEvent::ActivityConfirmedIdle| AcpThreadEvent::StatusChanged| AcpThreadEvent::SubmissionUpdated(_)| AcpThreadEvent::EntriesRemoved(_)| AcpThreadEvent::Retry(_)- | AcpThreadEvent::TokenUsageUpdated+ | AcpThreadEvent::TokenUsageUpdated(_)| AcpThreadEvent::PromptCapabilitiesUpdated| AcpThreadEvent::AvailableCommandsUpdated(_)| AcpThreadEvent::ModeUpdated(_)@@ -1833,6 +1835,26 @@ impl ConversationView {matches!(self.server_state, ServerState::Loading { .. })}+ fn send_queued_after_confirmed_idle(+ &mut self,+ window: &mut Window,+ cx: &mut Context<Self>,+ ) -> bool {+ self.root_thread_view().is_some_and(|active| {+ active.update(cx, |active, cx| {+ let is_first_editor_focused = active+ .message_queue+ .first()+ .is_some_and(|entry| entry.editor.focus_handle(cx).is_focused(window));+ active.send_queued_message_after_generation_stopped(+ is_first_editor_focused,+ window,+ cx,+ )+ })+ })+ }+fn handle_thread_event(&mut self,thread: &Entity<AcpThread>,@@ -1852,6 +1874,11 @@ impl ConversationView {cx.emit(RootThreadUpdated);}match event {+ AcpThreadEvent::ActivityConfirmedIdle => {+ if !is_subagent {+ self.send_queued_after_confirmed_idle(window, cx);+ }+ }AcpThreadEvent::StatusChanged => {if let Some(active) = self.thread_view(&session_id) {active.update(cx, |active, cx| {@@ -2059,22 +2086,7 @@ impl ConversationView {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.- let is_first_editor_focused = active- .message_queue- .first()- .is_some_and(|entry| entry.editor.focus_handle(cx).is_focused(window));- active.send_queued_message_after_generation_stopped(- is_first_editor_focused,- window,- cx,- )- })- } else {- false- };+ let sent_queued_message = self.send_queued_after_confirmed_idle(window, cx);// Skip notifying when a queued message was just auto-sent: the agent// is not actually idle and a notification here would fire just before the@@ -2170,10 +2182,10 @@ impl ConversationView {});}}- AcpThreadEvent::TokenUsageUpdated => {+ AcpThreadEvent::TokenUsageUpdated(update) => {if let Some(active) = self.thread_view(&session_id) {active.update(cx, |active, cx| {- active.update_turn_tokens(cx);+ active.update_turn_tokens(*update, cx);});}}@@ -5006,6 +5018,377 @@ pub(crate) mod tests {cx.run_until_parked();}+ #[gpui::test]+ async fn test_unconfirmed_activity_allows_manual_send_but_defers_automatic_queue(+ cx: &mut TestAppContext,+ ) {+ init_test(cx);+ let connection = StubAgentConnection::new().with_receipt_submissions(true);+ let (conversation, cx) =+ setup_conversation_view(StubAgentServer::new(connection.clone()), cx).await;+ add_to_workspace(conversation.clone(), cx);+ let view = active_thread(&conversation, cx);+ let thread = view.read_with(cx, |view, _| view.thread.clone());+ thread.update(cx, |thread, cx| thread.mark_activity_unconfirmed(cx));+ view.update_in(cx, |view, window, cx| {+ view.add_to_queue(vec!["queued".into()], vec![], window, cx);+ assert!(!view.send_queued_message_after_generation_stopped(false, window, cx));+ });+ cx.run_until_parked();+ assert!(cx.debug_bounds("activity-unconfirmed").is_some());+ assert!(connection.take_receipt_prompt().is_none());+ let response = connection.defer_next_receipt_response();+ message_editor(&conversation, cx).update_in(cx, |editor, window, cx| {+ editor.set_text("manual", window, cx);+ });+ cx.run_until_parked();+ let button = cx.debug_bounds("ICON-Send").expect("manual send button");+ cx.simulate_click(button.center(), gpui::Modifiers::default());+ cx.run_until_parked();+ assert_eq!(+ connection.take_receipt_prompt(),+ Some(vec!["manual".into()])+ );+ response+ .send(Ok(acp_v2::PromptResponse::new("manual")))+ .expect("receipt");+ thread.update(cx, |thread, cx| {+ thread+ .upsert_user_message(+ acp_v2::UserMessage::new("manual").content(vec!["manual".into()]),+ cx,+ )+ .expect("echo");+ });+ cx.run_until_parked();+ view.read_with(cx, |view, cx| {+ assert_eq!(view.thread.read(cx).status(), ThreadStatus::Unconfirmed);+ assert_eq!(view.message_queue.len(), 1);+ assert!(view.thread_error.is_none());+ assert!(view.turn_fields.turn_started_at.is_none());+ assert!(view.turn_fields.last_turn_duration.is_none());+ assert!(!view.generating_indicator_in_list);+ });+ let response = connection.defer_next_receipt_response();+ thread.update(cx, |thread, cx| {+ thread+ .update_session_state(+ acp_v2::StateUpdate::Idle(+ acp_v2::IdleStateUpdate::new().stop_reason(acp_v2::StopReason::Cancelled),+ ),+ cx,+ )+ .expect("first confirmed idle");+ });+ cx.run_until_parked();+ assert_eq!(+ connection.take_receipt_prompt(),+ Some(vec!["queued".into()])+ );+ response+ .send(Ok(acp_v2::PromptResponse::new("queued")))+ .expect("queued receipt");+ thread.update(cx, |thread, cx| {+ thread+ .upsert_user_message(+ acp_v2::UserMessage::new("queued").content(vec!["queued".into()]),+ cx,+ )+ .expect("queued echo");+ });+ cx.run_until_parked();+ assert!(cx.debug_bounds("activity-unconfirmed").is_none());+ view.read_with(cx, |view, cx| {+ assert!(view.message_queue.is_empty());+ assert_eq!(view.thread.read(cx).activity_generation(), 0);+ assert!(view.turn_fields.last_turn_duration.is_none());+ });+ }++ #[gpui::test]+ async fn test_unconfirmed_stop_and_send_waits_for_confirmed_idle(cx: &mut TestAppContext) {+ init_test(cx);+ let connection = StubAgentConnection::new().with_receipt_submissions(true);+ let (conversation, cx) =+ setup_conversation_view(StubAgentServer::new(connection.clone()), cx).await;+ let view = active_thread(&conversation, cx);+ let thread = view.read_with(cx, |view, _| view.thread.clone());+ thread.update(cx, |thread, cx| thread.mark_activity_unconfirmed(cx));+ let editor = message_editor(&conversation, cx);+ editor.update_in(cx, |editor, window, cx| {+ editor.set_text("after stop", window, cx)+ });+ let response = connection.defer_next_receipt_response();+ view.update_in(cx, |view, window, cx| view.interrupt_and_send(window, cx));+ cx.run_until_parked();+ assert_eq!(connection.take_cancel_calls().len(), 1);+ assert!(connection.take_receipt_prompt().is_none());+ assert_eq!(+ editor.read_with(cx, |editor, cx| editor.text(cx)),+ "after stop"+ );+ thread.update(cx, |thread, cx| {+ thread+ .update_session_state(+ acp_v2::StateUpdate::RequiresAction(acp_v2::RequiresActionStateUpdate::new()),+ cx,+ )+ .expect("late blocked snapshot");+ });+ cx.run_until_parked();+ assert!(connection.take_receipt_prompt().is_none());+ thread.update(cx, |thread, cx| {+ thread+ .update_session_state(+ acp_v2::StateUpdate::Idle(acp_v2::IdleStateUpdate::new()),+ cx,+ )+ .expect("confirmed idle");+ });+ cx.run_until_parked();+ assert_eq!(+ connection.take_receipt_prompt(),+ Some(vec!["after stop".into()])+ );+ response+ .send(Ok(acp_v2::PromptResponse::new("after-stop")))+ .expect("receipt");+ cx.run_until_parked();+ }++ #[gpui::test]+ async fn test_reported_usage_snapshots_replace_totals_without_double_counting(+ cx: &mut TestAppContext,+ ) {+ init_test(cx);+ let (conversation, cx) = setup_conversation_view(+ StubAgentServer::new(StubAgentConnection::new().with_receipt_submissions(true)),+ cx,+ )+ .await;+ let view = active_thread(&conversation, cx);+ let thread = view.read_with(cx, |view, _| view.thread.clone());+ for output_tokens in [7, 7] {+ thread.update(cx, |thread, cx| {+ thread.update_session_state(+ acp_v2::StateUpdate::RequiresAction(acp_v2::RequiresActionStateUpdate::new()), cx,+ ).expect("active interval");+ let idle: acp_v2::StateUpdate = serde_json::from_value(serde_json::json!({+ "state": "idle", "stopReason": "end_turn",+ "usage": {"totalTokens": 5 + output_tokens, "inputTokens": 5, "outputTokens": output_tokens}+ })).expect("usage snapshot");+ thread.update_session_state(idle.clone(), cx).expect("completion");+ thread.update_session_state(idle, cx).expect("repeat in the same foreground update");+ });+ cx.run_until_parked();+ view.read_with(cx, |view, _| {+ assert_eq!(view.turn_fields.last_turn_tokens, Some(output_tokens));+ assert!(view.turn_fields.turn_started_at.is_none());+ });+ }+ let correction: acp_v2::StateUpdate = serde_json::from_value(serde_json::json!({+ "state": "idle", "stopReason": "end_turn",+ "usage": {"totalTokens": 15, "inputTokens": 5, "outputTokens": 10}+ }))+ .expect("corrected idle information");+ thread+ .update(cx, |thread, cx| thread.update_session_state(correction, cx))+ .expect("correction");+ cx.run_until_parked();+ assert_eq!(+ view.read_with(cx, |view, _| view.turn_fields.last_turn_tokens),+ Some(10)+ );+ thread.update(cx, |thread, cx| {+ thread+ .update_session_state(+ acp_v2::StateUpdate::Running(acp_v2::RunningStateUpdate::new()),+ cx,+ )+ .expect("next interval");+ });+ cx.run_until_parked();+ let generation = thread.read_with(cx, |thread, _| thread.activity_generation());+ view.update(cx, |view, cx| {+ view.update_turn_tokens(+ acp_thread::OutputTokensUpdate::Snapshot {+ activity_generation: generation - 1,+ output_tokens: 99,+ },+ cx,+ )+ });+ assert_eq!(+ view.read_with(cx, |view, _| view.turn_fields.turn_tokens),+ Some(0)+ );+ thread.update(cx, |thread, cx| {+ for output_tokens in [3, 5] {+ thread.update_token_usage(+ Some(acp_thread::TokenUsage {+ output_tokens,+ ..Default::default()+ }),+ cx,+ );+ }+ thread.update_usage(acp_v2::UsageUpdate::new(10, 100), cx);+ });+ cx.run_until_parked();+ assert_eq!(+ view.read_with(cx, |view, _| view.turn_fields.turn_tokens),+ Some(8)+ );+ thread.update(cx, |thread, cx| {+ thread+ .update_session_state(+ acp_v2::StateUpdate::Idle(acp_v2::IdleStateUpdate::new()),+ cx,+ )+ .expect("native-style completion without an idle usage payload");+ });+ cx.run_until_parked();+ assert_eq!(+ view.read_with(cx, |view, _| view.turn_fields.last_turn_tokens),+ Some(8)+ );+ }++ #[gpui::test]+ async fn test_usage_events_from_previous_interval_do_not_enter_next_interval(+ cx: &mut TestAppContext,+ ) {+ init_test(cx);+ let (conversation, cx) = setup_conversation_view(+ StubAgentServer::new(StubAgentConnection::new().with_receipt_submissions(true)),+ cx,+ )+ .await;+ let view = active_thread(&conversation, cx);+ let thread = view.read_with(cx, |view, _| view.thread.clone());+ thread.update(cx, |thread, cx| {+ for output_tokens in [3, 5] {+ thread+ .update_session_state(+ acp_v2::StateUpdate::Running(acp_v2::RunningStateUpdate::new()),+ cx,+ )+ .expect("running");+ thread.update_token_usage(+ Some(acp_thread::TokenUsage {+ output_tokens,+ ..Default::default()+ }),+ cx,+ );+ if output_tokens == 3 {+ thread+ .update_session_state(+ acp_v2::StateUpdate::Idle(acp_v2::IdleStateUpdate::new()),+ cx,+ )+ .expect("first interval ends");+ }+ }+ });+ cx.run_until_parked();+ assert_eq!(+ view.read_with(cx, |view, _| view.turn_fields.turn_tokens),+ Some(5)+ );+ thread.update(cx, |thread, cx| {+ thread+ .update_session_state(+ acp_v2::StateUpdate::Idle(acp_v2::IdleStateUpdate::new()),+ cx,+ )+ .expect("cleanup");+ });+ }++ #[gpui::test]+ async fn test_reported_usage_survives_thread_view_recreation(cx: &mut TestAppContext) {+ init_test(cx);+ let (conversation, cx) = setup_conversation_view(+ StubAgentServer::new(StubAgentConnection::new().with_receipt_submissions(true)),+ cx,+ )+ .await;+ let view = active_thread(&conversation, cx);+ let thread = view.read_with(cx, |view, _| view.thread.clone());+ thread.update(cx, |thread, cx| {+ thread+ .update_session_state(+ acp_v2::StateUpdate::Running(acp_v2::RunningStateUpdate::new()),+ cx,+ )+ .expect("running");+ let idle: acp_v2::StateUpdate = serde_json::from_value(serde_json::json!({+ "state": "idle", "stopReason": "end_turn",+ "usage": {"totalTokens": 12, "inputTokens": 5, "outputTokens": 7}+ }))+ .expect("usage");+ thread.update_session_state(idle, cx).expect("idle");+ thread+ .update_session_state(+ acp_v2::StateUpdate::Idle(acp_v2::IdleStateUpdate::new()),+ cx,+ )+ .expect("snapshot without new usage");+ });+ cx.run_until_parked();+ let restored = conversation.update_in(cx, |view, window, cx| {+ let history = view.as_connected().expect("connected").conversation.clone();+ view.new_thread_view(thread.clone(), history, false, None, window, cx)+ });+ restored.read_with(cx, |view, _| {+ assert_eq!(view.turn_fields.last_turn_tokens, Some(7));+ assert!(view.turn_fields.turn_started_at.is_none());+ });+ }++ #[gpui::test]+ async fn test_legacy_usage_updates_preserve_additive_presentation(cx: &mut TestAppContext) {+ init_test(cx);+ let connection = StubAgentConnection::new();+ let complete = connection.defer_next_prompt_response();+ let (conversation, cx) =+ setup_conversation_view(StubAgentServer::new(connection), cx).await;+ let view = active_thread(&conversation, cx);+ let thread = view.read_with(cx, |view, _| view.thread.clone());+ message_editor(&conversation, cx).update_in(cx, |editor, window, cx| {+ editor.set_text("legacy prompt", window, cx);+ });+ view.update_in(cx, |view, window, cx| view.send(window, cx));+ cx.run_until_parked();+ thread.update(cx, |thread, cx| {+ assert!(!thread.uses_reported_activity());+ for output_tokens in [3, 5] {+ thread.update_token_usage(+ Some(acp_thread::TokenUsage {+ output_tokens,+ ..Default::default()+ }),+ cx,+ );+ }+ thread.update_usage(acp_v2::UsageUpdate::new(10, 100), cx);+ });+ cx.run_until_parked();+ assert_eq!(+ view.read_with(cx, |view, _| view.turn_fields.turn_tokens),+ Some(8)+ );+ complete+ .send(Ok(acp_v1::PromptResponse::new(acp_v1::StopReason::EndTurn)))+ .expect("legacy completion");+ cx.run_until_parked();+ assert_eq!(+ view.read_with(cx, |view, _| view.turn_fields.last_turn_tokens),+ Some(8)+ );+ }+#[gpui::test]async fn test_authentication_keeps_receipt_submission_recoverable(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 54bebf50f6f..5789f12b302 100644--- a/crates/agent_ui/src/conversation_view/thread_view.rs+++ b/crates/agent_ui/src/conversation_view/thread_view.rs@@ -9,7 +9,7 @@ use agent_client_protocol::schema::v2 as acp_v2;use std::{cell::RefCell, path::Path};use acp_thread::{- Elicitation, ElicitationEntryId, ElicitationStatus, ForegroundActivity,+ Elicitation, ElicitationEntryId, ElicitationStatus, ForegroundActivity, OutputTokensUpdate,SandboxAuthorizationDetails, SandboxFallbackAuthorizationDetails, SandboxNotAppliedReason,SubmissionId, SubmissionResponse, SubmissionState, ToolCallLocation, decode_path_escapes,};@@ -1488,8 +1488,11 @@ impl ThreadView {let activity_generation = thread.activity_generation();let started_at = thread.activity_started_at();let duration = thread.activity_duration();+ let output_tokens = thread.reported_activity_output_tokens();- if activity != ForegroundActivity::Idle {+ if activity == ForegroundActivity::Unconfirmed {+ self.turn_fields.reported_activity_generation = None;+ } else if activity.is_active() {if self.turn_fields.reported_activity_generation != Some(activity_generation) {self.initialize_turn(cx);self.turn_fields.turn_started_at = started_at;@@ -1504,6 +1507,9 @@ impl ThreadView {}self.turn_fields.reported_activity_generation = Some(activity_generation);self.turn_fields.last_turn_duration = duration;+ if let Some(output_tokens) = output_tokens {+ self.turn_fields.last_turn_tokens = Some(output_tokens);+ }}cx.notify();}@@ -1747,13 +1753,34 @@ impl ThreadView {)}- 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 {- *tokens += usage.output_tokens;- self.emit_token_limit_telemetry_if_needed(cx);+ pub fn update_turn_tokens(&mut self, update: OutputTokensUpdate, cx: &mut Context<Self>) {+ match update {+ OutputTokensUpdate::Unchanged => {}+ OutputTokensUpdate::LegacyAdd {+ activity_generation,+ output_tokens,+ } => {+ if self.thread.read(cx).activity_generation() != activity_generation {+ return;+ }+ if self.thread.read(cx).foreground_activity() != ForegroundActivity::Idle {+ self.sync_reported_activity(cx);+ }+ if let Some(tokens) = &mut self.turn_fields.turn_tokens {+ *tokens += output_tokens;+ }+ }+ OutputTokensUpdate::Snapshot {+ activity_generation,+ ..+ } => {+ if self.thread.read(cx).activity_generation() != activity_generation {+ return;+ }+ self.sync_reported_activity(cx);}}+ self.emit_token_limit_telemetry_if_needed(cx);}fn emit_token_limit_telemetry_if_needed(&mut self, cx: &App) {@@ -1824,7 +1851,7 @@ impl ThreadView {let message_editor = self.message_editor.clone();let is_editor_empty = message_editor.read(cx).is_empty(cx);- let is_generating = thread.read(cx).status() != ThreadStatus::Idle;+ let is_generating = thread.read(cx).status() == ThreadStatus::Generating;if is_editor_empty {if self.message_queue.can_fast_track()@@ -2677,6 +2704,11 @@ impl ThreadView {window: &mut Window,cx: &mut Context<Self>,) -> bool {+ if self.thread.read(cx).foreground_activity() != ForegroundActivity::Idle+ || self.is_loading_contents+ {+ return false;+ }if let Some(id) = self.message_queue.auto_send_candidate(is_first_editor_focused)@@ -5102,6 +5134,25 @@ impl ThreadView {.min_w_0().flex_wrap().gap_1()+ .when(+ self.thread.read(cx).foreground_activity()+ == ForegroundActivity::Unconfirmed,+ |row| {+ row.child(+ div()+ .id("activity-unconfirmed")+ .debug_selector(|| "activity-unconfirmed".into())+ .child(+ Label::new("Activity unconfirmed")+ .size(LabelSize::Small)+ .color(Color::Muted),+ )+ .tooltip(Tooltip::text(+ "The session is attached, but the agent has not reported its activity. You can send manually; automatic sends wait for confirmed Idle.",+ )),+ )+ },+ ).children(discard_draft_button).children(self.render_token_usage(cx)).children(self.profile_selector.clone())@@ -6088,7 +6139,8 @@ impl ThreadView {let is_editor_empty = message_editor.is_empty(cx);let focus_handle = message_editor.focus_handle(cx);- let is_generating = self.thread.read(cx).status() != ThreadStatus::Idle;+ let is_generating = self.thread.read(cx).status() == ThreadStatus::Generating;+ let is_unconfirmed = self.thread.read(cx).status() == ThreadStatus::Unconfirmed;if self.is_loading_contents {div()@@ -6097,12 +6149,20 @@ impl ThreadView {.tooltip(Tooltip::text("Loading Added Context…")).child(loading_contents_spinner(IconSize::default())).into_any_element()- } else if is_generating && is_editor_empty {+ } else if (is_generating || is_unconfirmed) && is_editor_empty {IconButton::new("stop-generation", IconName::Stop).icon_color(Color::Error).style(ButtonStyle::Tinted(TintColor::Error)).tooltip(move |_window, cx| {- Tooltip::for_action("Stop Generation", &editor::actions::Cancel, cx)+ Tooltip::for_action(+ if is_unconfirmed {+ "Request Stop (Activity Unconfirmed)"+ } else {+ "Stop Generation"+ },+ &editor::actions::Cancel,+ cx,+ )}).on_click(cx.listener(|this, _event, _, cx| this.cancel_generation(cx))).into_any_element()diff --git a/crates/sidebar/src/sidebar.rs b/crates/sidebar/src/sidebar.rsindex 0cfd72880b7..68e309923d6 100644--- a/crates/sidebar/src/sidebar.rs+++ b/crates/sidebar/src/sidebar.rs@@ -5800,7 +5800,9 @@ impl Sidebar {match self.contents.entries.get(ix) {Some(ListEntry::Thread(thread)) => {match thread.status {- AgentThreadStatus::Running | AgentThreadStatus::WaitingForConfirmation => {+ AgentThreadStatus::Running+ | AgentThreadStatus::WaitingForConfirmation+ | AgentThreadStatus::Unconfirmed => {return;}AgentThreadStatus::Completed | AgentThreadStatus::Error => {}@@ -6297,9 +6299,11 @@ impl Sidebar {let is_selected = is_active;let is_draft = thread.draft.is_some();let is_empty_draft = thread.draft == Some(DraftKind::Empty);- let is_running = matches!(+ let can_request_stop = matches!(thread.status,- AgentThreadStatus::Running | AgentThreadStatus::WaitingForConfirmation+ AgentThreadStatus::Running+ | AgentThreadStatus::WaitingForConfirmation+ | AgentThreadStatus::Unconfirmed);let is_renaming =self.rename_target == Some(RenameTarget::Thread(thread.metadata.thread_id));@@ -6405,13 +6409,19 @@ impl Sidebar {})});- let contextual_action: Option<AnyElement> = if is_running {+ let contextual_action: Option<AnyElement> = if can_request_stop {Some(IconButton::new("stop-thread", IconName::Stop).icon_size(IconSize::Small).icon_color(Color::Error).style(ButtonStyle::Tinted(TintColor::Error))- .tooltip(Tooltip::text("Stop Generation"))+ .tooltip(Tooltip::text(+ if thread.status == AgentThreadStatus::Unconfirmed {+ "Request Stop (Activity Unconfirmed)"+ } else {+ "Stop Generation"+ },+ )).on_click(cx.listener(move |this, _, _window, cx| {this.stop_thread(&thread_id_for_actions, cx);}))@@ -8161,6 +8171,7 @@ fn all_thread_infos_for_workspace(AgentThreadStatus::Error} else {match thread.status() {+ ThreadStatus::Unconfirmed => AgentThreadStatus::Unconfirmed,ThreadStatus::Generating => AgentThreadStatus::Running,ThreadStatus::Idle => AgentThreadStatus::Completed,}@@ -8369,6 +8380,7 @@ fn dump_single_workspace(workspace: &Workspace, output: &mut String, cx: &gpui::let title = thread.title().unwrap_or_else(|| "(untitled)".into());let session_id = thread.session_id();let status = match thread.status() {+ ThreadStatus::Unconfirmed => "unconfirmed",ThreadStatus::Idle => "idle",ThreadStatus::Generating => "generating",};@@ -8403,6 +8415,7 @@ fn dump_single_workspace(workspace: &Workspace, output: &mut String, cx: &gpui::let thread = thread_view.read(cx).thread.read(cx);let title = thread.title().unwrap_or_else(|| "(untitled)".into());let status = match thread.status() {+ ThreadStatus::Unconfirmed => "unconfirmed",ThreadStatus::Idle => "idle",ThreadStatus::Generating => "generating",};diff --git a/crates/sidebar/src/sidebar_tests.rs b/crates/sidebar/src/sidebar_tests.rsindex 6ec961c2bd1..112dc159d8c 100644--- a/crates/sidebar/src/sidebar_tests.rs+++ b/crates/sidebar/src/sidebar_tests.rs@@ -4146,8 +4146,33 @@ async fn test_archive_selected_thread_archives_closed_linked_worktree(cx: &mut T});focus_sidebar(&sidebar, cx);- sidebar.update_in(cx, |sidebar, _window, _cx| {+ let previous_status = sidebar.update_in(cx, |sidebar, _window, _cx| {sidebar.selection = Some(thread_index);+ let Some(ListEntry::Thread(thread)) = sidebar.contents.entries.get_mut(thread_index) else {+ panic!("expected selected thread");+ };+ std::mem::replace(+ &mut Arc::make_mut(thread).status,+ AgentThreadStatus::Unconfirmed,+ )+ });+ cx.dispatch_action(ArchiveSelectedThread);+ cx.run_until_parked();+ assert_eq!(+ cx.update(|_, cx| {+ ThreadMetadataStore::global(cx)+ .read(cx)+ .entry_by_session(&worktree_session_id)+ .map(|thread| thread.archived)+ }),+ Some(false),+ "unconfirmed activity must not permit archival"+ );+ sidebar.update_in(cx, |sidebar, _window, _cx| {+ let Some(ListEntry::Thread(thread)) = sidebar.contents.entries.get_mut(thread_index) else {+ panic!("expected selected thread");+ };+ Arc::make_mut(thread).status = previous_status;});cx.dispatch_action(ArchiveSelectedThread);for _ in 0..8 {diff --git a/crates/ui/src/components/ai/thread_item.rs b/crates/ui/src/components/ai/thread_item.rsindex 7cf574848a8..3df79d9fbf4 100644--- a/crates/ui/src/components/ai/thread_item.rs+++ b/crates/ui/src/components/ai/thread_item.rs@@ -11,6 +11,7 @@ use std::{path::PathBuf, sync::Arc, time::Duration};pub enum AgentThreadStatus {#[default]Completed,+ Unconfirmed,Running,WaitingForConfirmation,Error,@@ -322,6 +323,12 @@ impl RenderOnce for ThreadItem {.size(IconSize::XSmall).color(Color::Warning),)+ } else if self.status == AgentThreadStatus::Unconfirmed {+ Some(+ Icon::new(IconName::Info)+ .size(IconSize::Small)+ .color(Color::Muted),+ )} else if self.notified {Some(Icon::new(IconName::Circle)