Skip to content

armgit / zed

Public Imported from GitHub
0

Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.

acp: Support background work in ACP v2 (#66446)

Ben Brandtd36a70661471
diff --git a/crates/acp_thread/src/acp_thread.rs b/crates/acp_thread/src/acp_thread.rs
index a6f34441d3a..ecb6ed87a40 100644
--- a/crates/acp_thread/src/acp_thread.rs
+++ b/crates/acp_thread/src/acp_thread.rs
@@ -1195,6 +1195,8 @@ pub struct ToolCall {
pub raw_input_markdown: Option<Entity<Markdown>>,
pub raw_output: Option<serde_json::Value>,
raw_output_content: Option<Box<ToolCallContent>>,
+ /// Whether the agent accepts `tool_call/cancel` for this tool call.
+ advertises_cancel: bool,
pub tool_name: Option<SharedString>,
pub subagent_session_info: Option<SubagentSessionInfo>,
pub sandbox_authorization_details: Option<SandboxAuthorizationDetails>,
@@ -1268,6 +1270,7 @@ struct ToolCallPatch {
locations: MaybeUndefined<Vec<ToolCallLocation>>,
raw_input: MaybeUndefined<serde_json::Value>,
raw_output: MaybeUndefined<serde_json::Value>,
+ capabilities: MaybeUndefined<acp_v2::ToolCallCapabilities>,
meta: ToolMetadataPatch,
}
@@ -1371,6 +1374,7 @@ impl ToolCallPatch {
),
raw_input: legacy_tool_field(fields.raw_input),
raw_output: legacy_tool_field(fields.raw_output),
+ capabilities: MaybeUndefined::Undefined,
meta: ToolMetadataPatch::Legacy(meta),
}
}
@@ -1387,6 +1391,7 @@ impl ToolCallPatch {
.map_value(|locations| locations.into_iter().map(Into::into).collect()),
raw_input: update.raw_input,
raw_output: update.raw_output,
+ capabilities: update.capabilities,
meta: ToolMetadataPatch::Protocol(update.meta),
}
}
@@ -1476,6 +1481,11 @@ impl ToolCall {
raw_input_markdown,
raw_output: patch.raw_output.take(),
raw_output_content: None,
+ advertises_cancel: patch
+ .capabilities
+ .as_opt_ref()
+ .flatten()
+ .is_some_and(|capabilities| capabilities.cancel.is_some()),
tool_name,
subagent_session_info,
sandbox_authorization_details,
@@ -1504,6 +1514,16 @@ impl ToolCall {
self.authorization
}
+ /// Whether Zed may stop this tool call with `tool_call/cancel`: the agent advertises it
+ /// and the tool call hasn't finished.
+ pub fn can_cancel(&self) -> bool {
+ self.advertises_cancel
+ && matches!(
+ self.underlying_status(),
+ ToolCallStatus::Pending | ToolCallStatus::InProgress | ToolCallStatus::Paused
+ )
+ }
+
fn underlying_status(&self) -> ToolCallStatus {
self.local_status
.or_else(|| ToolCallStatus::from_reported(self.reported_status.as_ref()))
@@ -1589,8 +1609,13 @@ impl ToolCall {
locations,
raw_input,
raw_output,
+ capabilities,
meta,
} = patch;
+ if let Some(capabilities) = capabilities.as_opt_ref() {
+ self.advertises_cancel =
+ capabilities.is_some_and(|capabilities| capabilities.cancel.is_some());
+ }
let output_changed = !content.is_undefined() || !raw_output.is_undefined();
// Completion remains authoritative even when output cannot be displayed;
// otherwise a finished tool could leave its permission request waiting.
@@ -2007,6 +2032,8 @@ pub enum ToolCallStatus {
WaitingForConfirmation,
/// The tool call is currently running.
InProgress,
+ /// The tool call has started but is not running now, until something resumes it.
+ Paused,
/// The tool call completed successfully.
Completed,
/// The tool call failed.
@@ -2081,6 +2108,7 @@ impl ToolCallStatus {
match status? {
acp_v2::ToolCallStatus::Pending => Some(Self::Pending),
acp_v2::ToolCallStatus::InProgress => Some(Self::InProgress),
+ acp_v2::ToolCallStatus::Paused => Some(Self::Paused),
acp_v2::ToolCallStatus::Completed => Some(Self::Completed),
acp_v2::ToolCallStatus::Failed => Some(Self::Failed),
acp_v2::ToolCallStatus::Cancelled => Some(Self::Canceled),
@@ -2093,6 +2121,7 @@ impl ToolCallStatus {
match self {
ToolCallStatus::Pending => Some(acp_v2::ToolCallStatus::Pending),
ToolCallStatus::InProgress => Some(acp_v2::ToolCallStatus::InProgress),
+ ToolCallStatus::Paused => Some(acp_v2::ToolCallStatus::Paused),
ToolCallStatus::Completed => Some(acp_v2::ToolCallStatus::Completed),
ToolCallStatus::Failed => Some(acp_v2::ToolCallStatus::Failed),
// A new authorization can retry a locally canceled tool; the
@@ -2119,6 +2148,7 @@ impl Display for ToolCallStatus {
ToolCallStatus::Pending => "Pending",
ToolCallStatus::WaitingForConfirmation => "Waiting for confirmation",
ToolCallStatus::InProgress => "In Progress",
+ ToolCallStatus::Paused => "Paused",
ToolCallStatus::Completed => "Completed",
ToolCallStatus::Failed => "Failed",
ToolCallStatus::Rejected => "Rejected",
@@ -4333,6 +4363,12 @@ impl AcpThread {
self.activity.state()
}
+ /// The work the agent reported as running independently of foreground work in its latest
+ /// state snapshot. `None` means the agent hasn't reported it, not that nothing is running.
+ pub fn background_work(&self) -> Option<&[acp_v2::BackgroundWork]> {
+ self.foreground_state()?.background()
+ }
+
pub fn mark_activity_unconfirmed(&mut self, cx: &mut Context<Self>) {
if self.uses_reported_activity()
&& !self.received_session_state
@@ -7556,6 +7592,41 @@ impl AcpThread {
}
}
+ /// Asks the agent to stop one tool call, without cancelling the rest of the session's work.
+ pub fn cancel_tool_call(
+ &self,
+ tool_call_id: &acp_v2::ToolCallId,
+ cx: &mut Context<Self>,
+ ) -> Task<Result<()>> {
+ // The agent must only receive `tool_call/cancel` for a tool call that advertises it.
+ let Some((_, call)) = self.tool_call(tool_call_id) else {
+ return Task::ready(Err(anyhow!("Unknown tool call")));
+ };
+ if !call.can_cancel() {
+ return Task::ready(Err(anyhow!("This tool call cannot be stopped")));
+ }
+ self.connection
+ .cancel_tool_call(self.session_id(), tool_call_id, cx)
+ }
+
+ /// Asks the agent to stop an agent-run terminal's process. Its output stays available.
+ pub fn cancel_terminal(
+ &self,
+ terminal_id: &acp_v2::TerminalId,
+ cx: &mut Context<Self>,
+ ) -> Task<Result<()>> {
+ // The agent must only receive `terminal/cancel` for a terminal that advertises it.
+ if !self
+ .terminals
+ .get(terminal_id)
+ .is_some_and(|terminal| terminal.read(cx).can_cancel())
+ {
+ return Task::ready(Err(anyhow!("This terminal cannot be stopped")));
+ }
+ self.connection
+ .cancel_terminal(self.session_id(), terminal_id, cx)
+ }
+
fn request_cancellation(
&mut self,
permission_outcome: RequestPermissionOutcome,
@@ -10704,6 +10775,7 @@ mod tests {
thread.upsert_display_terminal(
terminal_id.clone(),
DisplayTerminalPatch {
+ capabilities: Default::default(),
command: MaybeUndefined::Value("actual command".into()),
..Default::default()
},
@@ -10754,6 +10826,7 @@ mod tests {
thread.upsert_display_terminal(
terminal_id,
DisplayTerminalPatch {
+ capabilities: Default::default(),
command: MaybeUndefined::Null,
..Default::default()
},
@@ -10807,6 +10880,7 @@ mod tests {
thread.upsert_display_terminal(
"shared-terminal".into(),
DisplayTerminalPatch {
+ capabilities: Default::default(),
meta: MaybeUndefined::Value(acp_v2::Meta::new()),
..Default::default()
},
@@ -10858,6 +10932,7 @@ mod tests {
.upsert_display_terminal(
"mixed".into(),
DisplayTerminalPatch {
+ capabilities: Default::default(),
command: MaybeUndefined::Value("reported command".into()),
output: MaybeUndefined::Value(DisplayTerminalOutput {
data: b"new output".to_vec(),
@@ -10928,6 +11003,7 @@ mod tests {
.upsert_display_terminal(
"mixed".into(),
DisplayTerminalPatch {
+ capabilities: Default::default(),
exit_status: MaybeUndefined::Null,
..Default::default()
},
@@ -10962,6 +11038,7 @@ mod tests {
thread.upsert_display_terminal(
terminal_id.clone(),
DisplayTerminalPatch {
+ capabilities: Default::default(),
command: MaybeUndefined::Value("first command".into()),
cwd: MaybeUndefined::Value(acp_v2::AbsolutePath::new(PathBuf::from(
path!("/work"),
@@ -10998,6 +11075,7 @@ mod tests {
thread.upsert_display_terminal(
terminal_id.clone(),
DisplayTerminalPatch {
+ capabilities: Default::default(),
output: MaybeUndefined::Value(DisplayTerminalOutput {
data: b"new line\r\n".to_vec(),
meta: None,
@@ -11010,6 +11088,7 @@ mod tests {
thread.upsert_display_terminal(
terminal_id.clone(),
DisplayTerminalPatch {
+ capabilities: Default::default(),
exit_status: MaybeUndefined::Value(acp_v2::TerminalExitStatus::new()),
..Default::default()
},
@@ -11047,6 +11126,7 @@ mod tests {
thread.upsert_display_terminal(
terminal_id.clone(),
DisplayTerminalPatch {
+ capabilities: Default::default(),
output: MaybeUndefined::Null,
exit_status: MaybeUndefined::Null,
..Default::default()
@@ -11101,6 +11181,7 @@ mod tests {
thread.upsert_display_terminal(
terminal_id,
DisplayTerminalPatch {
+ capabilities: Default::default(),
command: MaybeUndefined::Null,
cwd: MaybeUndefined::Null,
meta: MaybeUndefined::Null,
@@ -11162,6 +11243,7 @@ mod tests {
.upsert_display_terminal(
acp_v2::TerminalId::new("native-terminal"),
DisplayTerminalPatch {
+ capabilities: Default::default(),
command: MaybeUndefined::Value("wrong command".into()),
output: MaybeUndefined::Null,
exit_status: MaybeUndefined::Value(acp_v2::TerminalExitStatus::new()),
@@ -14308,6 +14390,7 @@ mod tests {
.upsert_display_terminal(
"metadata".into(),
DisplayTerminalPatch {
+ capabilities: Default::default(),
meta: metadata.clone(),
output: MaybeUndefined::Value(DisplayTerminalOutput {
data: b"snapshot".to_vec(),
diff --git a/crates/acp_thread/src/connection.rs b/crates/acp_thread/src/connection.rs
index 2db73fe8a27..ce03f4df92c 100644
--- a/crates/acp_thread/src/connection.rs
+++ b/crates/acp_thread/src/connection.rs
@@ -260,6 +260,32 @@ pub trait AgentConnection {
/// Requests cancellation; success does not establish that execution stopped.
fn cancel(&self, session_id: &acp_v2::SessionId, cx: &mut App) -> Result<()>;
+ /// Asks the agent to stop one tool call. Success means the agent accepted the request;
+ /// the tool call's own updates report when it stops.
+ fn cancel_tool_call(
+ &self,
+ _session_id: &acp_v2::SessionId,
+ _tool_call_id: &acp_v2::ToolCallId,
+ _cx: &mut App,
+ ) -> Task<Result<()>> {
+ Task::ready(Err(anyhow::anyhow!(
+ "Cancelling tool calls is not supported"
+ )))
+ }
+
+ /// Asks the agent to stop one terminal's process. Success means the agent accepted the
+ /// request; the terminal's exit status reports when it stops.
+ fn cancel_terminal(
+ &self,
+ _session_id: &acp_v2::SessionId,
+ _terminal_id: &acp_v2::TerminalId,
+ _cx: &mut App,
+ ) -> Task<Result<()>> {
+ Task::ready(Err(anyhow::anyhow!(
+ "Cancelling terminals is not supported"
+ )))
+ }
+
/// Request-scoped elicitations are connection-level because they can arrive before a session
/// thread exists. Session-scoped elicitations stay in the thread timeline, but use
/// `ElicitationStore` for shared processing.
diff --git a/crates/acp_thread/src/terminal.rs b/crates/acp_thread/src/terminal.rs
index afeb6db2abf..abf82c73282 100644
--- a/crates/acp_thread/src/terminal.rs
+++ b/crates/acp_thread/src/terminal.rs
@@ -429,6 +429,8 @@ pub struct DisplayTerminalState {
command: DisplayCommand,
pub meta: Option<acp_v2::Meta>,
pub output_meta: Option<acp_v2::Meta>,
+ /// Whether the agent accepts `terminal/cancel` for this terminal.
+ can_cancel: bool,
legacy_created: bool,
legacy_exited: bool,
}
@@ -459,6 +461,7 @@ pub struct DisplayTerminalPatch {
pub cwd: MaybeUndefined<acp_v2::AbsolutePath>,
pub output: MaybeUndefined<DisplayTerminalOutput>,
pub exit_status: MaybeUndefined<acp_v2::TerminalExitStatus>,
+ pub capabilities: MaybeUndefined<acp_v2::TerminalCapabilities>,
pub meta: MaybeUndefined<acp_v2::Meta>,
}
@@ -711,6 +714,12 @@ impl Terminal {
}
}
+ /// Whether Zed may stop this agent-run terminal with `terminal/cancel`: the agent
+ /// advertises it and hasn't reported an exit status.
+ pub fn can_cancel(&self) -> bool {
+ self.output.is_none() && self.display_state().is_some_and(|state| state.can_cancel)
+ }
+
pub(crate) fn initialize_legacy_display(
&mut self,
command: &str,
@@ -763,6 +772,7 @@ impl Terminal {
cwd,
output,
exit_status,
+ capabilities,
meta,
} = patch;
let output_changed = !output.is_undefined();
@@ -795,6 +805,10 @@ impl Terminal {
if let Some(meta) = output_meta {
state.output_meta = meta;
}
+ if let Some(capabilities) = capabilities.as_opt_ref() {
+ state.can_cancel =
+ capabilities.is_some_and(|capabilities| capabilities.cancel.is_some());
+ }
}
if !cwd.is_undefined() {
self.working_dir = cwd.take().map(|path| path.0);
diff --git a/crates/agent_servers/src/acp/terminal_updates.rs b/crates/agent_servers/src/acp/terminal_updates.rs
index 5ffe95047ac..3c048a98ef0 100644
--- a/crates/agent_servers/src/acp/terminal_updates.rs
+++ b/crates/agent_servers/src/acp/terminal_updates.rs
@@ -86,6 +86,7 @@ pub fn decode_terminal_notification(
cwd: update.cwd,
output,
exit_status: update.exit_status,
+ capabilities: update.capabilities,
meta: update.meta,
},
}
diff --git a/crates/agent_servers/src/acp/v2.rs b/crates/agent_servers/src/acp/v2.rs
index 442b21a22b8..9622b042ca0 100644
--- a/crates/agent_servers/src/acp/v2.rs
+++ b/crates/agent_servers/src/acp/v2.rs
@@ -1675,6 +1675,40 @@ impl AgentConnection for AcpV2Connection {
.map_err(map_acp_error)
}
+ fn cancel_tool_call(
+ &self,
+ session_id: &acp::SessionId,
+ tool_call_id: &acp::ToolCallId,
+ cx: &mut App,
+ ) -> Task<Result<()>> {
+ let response = Self::scoped_request(
+ &self.connection,
+ &self.dispatch_tx,
+ acp::CancelToolCallRequest::new(session_id.clone(), tool_call_id.clone()),
+ );
+ cx.foreground_executor().spawn(async move {
+ response.await?;
+ Ok(())
+ })
+ }
+
+ fn cancel_terminal(
+ &self,
+ session_id: &acp::SessionId,
+ terminal_id: &acp::TerminalId,
+ cx: &mut App,
+ ) -> Task<Result<()>> {
+ let response = Self::scoped_request(
+ &self.connection,
+ &self.dispatch_tx,
+ acp::CancelTerminalRequest::new(session_id.clone(), terminal_id.clone()),
+ );
+ cx.foreground_executor().spawn(async move {
+ response.await?;
+ Ok(())
+ })
+ }
+
fn request_elicitations(&self) -> Option<Entity<ElicitationStore>> {
Some(self.request_elicitations.clone())
}
@@ -3273,6 +3307,129 @@ mod tests {
);
}
+ #[gpui::test]
+ async fn v2_background_work_is_tracked_and_stoppable(cx: &mut TestAppContext) {
+ use acp_thread::ToolCallStatus;
+
+ let harness = SessionHarness::new(session_capabilities(), vec![], vec![], cx).await;
+ let thread = harness.thread(cx).await;
+ let session_id = thread.read_with(cx, |thread, _| thread.session_id().clone());
+ harness.send_update(
+ &session_id.0,
+ acp::SessionUpdate::ToolCallUpdate(
+ acp::ToolCallUpdate::new("watcher")
+ .status(acp::ToolCallStatus::Paused)
+ .capabilities(
+ acp::ToolCallCapabilities::new()
+ .cancel(acp::ToolCallCancelCapabilities::new()),
+ ),
+ ),
+ );
+ harness.send_update(
+ &session_id.0,
+ acp::SessionUpdate::ToolCallUpdate(
+ acp::ToolCallUpdate::new("fixed").status(acp::ToolCallStatus::InProgress),
+ ),
+ );
+ harness.send_update(
+ &session_id.0,
+ acp::SessionUpdate::TerminalUpdate(acp::TerminalUpdate::new("server").capabilities(
+ acp::TerminalCapabilities::new().cancel(acp::TerminalCancelCapabilities::new()),
+ )),
+ );
+ harness.send_update(
+ &session_id.0,
+ acp::SessionUpdate::StateUpdate(acp::StateUpdate::Idle(
+ acp::IdleStateUpdate::new()
+ .stop_reason(acp::StopReason::EndTurn)
+ .background(vec![
+ acp::BackgroundWork::Terminal(acp::BackgroundTerminal::new("server")),
+ acp::BackgroundWork::ToolCall(acp::BackgroundToolCall::new("watcher")),
+ ]),
+ )),
+ );
+ harness.drain_updates(cx).await;
+ thread.read_with(cx, |thread, cx| {
+ assert_eq!(thread.background_work().map(<[_]>::len), Some(2));
+ let (_, watcher) = thread.tool_call(&"watcher".into()).expect("watcher");
+ assert_eq!(watcher.status(), ToolCallStatus::Paused);
+ assert!(
+ watcher.can_cancel(),
+ "paused tool calls can advertise cancel"
+ );
+ let (_, fixed) = thread.tool_call(&"fixed".into()).expect("fixed");
+ assert!(!fixed.can_cancel());
+ assert!(
+ thread
+ .terminal("server".into())
+ .expect("server")
+ .read(cx)
+ .can_cancel()
+ );
+ });
+
+ // The agent has no handler for these methods, so the SDK answers -32602 once a
+ // request reaches it. A local refusal never sends one.
+ let sent_code = |result: Result<()>| {
+ result
+ .expect_err("the harness agent rejects cancellation")
+ .downcast_ref::<agent_client_protocol::Error>()
+ .map(|error| error.code)
+ };
+ let invalid_params = Some(agent_client_protocol::ErrorCode::INVALID_PARAMS);
+ let stop_watcher = thread.update(cx, |thread, cx| {
+ thread.cancel_tool_call(&"watcher".into(), cx)
+ });
+ assert_eq!(sent_code(bounded(stop_watcher, cx).await), invalid_params);
+ let stop_fixed = thread.update(cx, |thread, cx| {
+ thread.cancel_tool_call(&"fixed".into(), cx)
+ });
+ assert_eq!(
+ sent_code(bounded(stop_fixed, cx).await),
+ None,
+ "an unadvertised tool call is never sent tool_call/cancel"
+ );
+ let stop_server = thread.update(cx, |thread, cx| {
+ thread.cancel_terminal(&"server".into(), cx)
+ });
+ assert_eq!(sent_code(bounded(stop_server, cx).await), invalid_params);
+
+ harness.send_update(
+ &session_id.0,
+ acp::SessionUpdate::TerminalUpdate(
+ acp::TerminalUpdate::new("server").exit_status(acp::TerminalExitStatus::new()),
+ ),
+ );
+ harness.send_update(
+ &session_id.0,
+ acp::SessionUpdate::ToolCallUpdate(
+ acp::ToolCallUpdate::new("watcher").status(acp::ToolCallStatus::Cancelled),
+ ),
+ );
+ harness.send_update(
+ &session_id.0,
+ acp::SessionUpdate::StateUpdate(acp::StateUpdate::Idle(acp::IdleStateUpdate::new())),
+ );
+ harness.drain_updates(cx).await;
+ thread.read_with(cx, |thread, cx| {
+ assert_eq!(
+ thread.background_work(),
+ None,
+ "an omitted list means background work is unknown"
+ );
+ let (_, watcher) = thread.tool_call(&"watcher".into()).expect("watcher");
+ assert!(!watcher.can_cancel(), "final tool calls can't be stopped");
+ assert!(
+ !thread
+ .terminal("server".into())
+ .expect("server")
+ .read(cx)
+ .can_cancel(),
+ "exited terminals can't be stopped"
+ );
+ });
+ }
+
#[gpui::test]
async fn v2_cancel_sdk_eof_fails_observation_without_inventing_idle(cx: &mut TestAppContext) {
use acp_thread::ForegroundActivity;
diff --git a/crates/agent_ui/src/conversation_view.rs b/crates/agent_ui/src/conversation_view.rs
index ef374945a6b..c7cecc3dc51 100644
--- a/crates/agent_ui/src/conversation_view.rs
+++ b/crates/agent_ui/src/conversation_view.rs
@@ -15837,6 +15837,7 @@ pub(crate) mod tests {
.upsert_display_terminal(
"display".into(),
acp_thread::DisplayTerminalPatch {
+ capabilities: Default::default(),
command: agent_client_protocol::schema::MaybeUndefined::Value(
"actual command".into(),
),
@@ -15868,6 +15869,7 @@ pub(crate) mod tests {
.upsert_display_terminal(
"display".into(),
acp_thread::DisplayTerminalPatch {
+ capabilities: Default::default(),
output: agent_client_protocol::schema::MaybeUndefined::Value(
acp_thread::DisplayTerminalOutput {
data: b"new output".to_vec(),
@@ -15904,6 +15906,7 @@ pub(crate) mod tests {
.upsert_display_terminal(
"display".into(),
acp_thread::DisplayTerminalPatch {
+ capabilities: Default::default(),
output: agent_client_protocol::schema::MaybeUndefined::Null,
exit_status: agent_client_protocol::schema::MaybeUndefined::Null,
..Default::default()
diff --git a/crates/agent_ui/src/conversation_view/subagent_card.rs b/crates/agent_ui/src/conversation_view/subagent_card.rs
index 115a13da5e7..bc5436d2e9f 100644
--- a/crates/agent_ui/src/conversation_view/subagent_card.rs
+++ b/crates/agent_ui/src/conversation_view/subagent_card.rs
@@ -162,6 +162,7 @@ impl SubagentStatus {
match tool_call.status() {
ToolCallStatus::Pending
| ToolCallStatus::InProgress
+ | ToolCallStatus::Paused
| ToolCallStatus::WaitingForConfirmation => Self::Running,
_ if has_user_canceled_output(tool_call, cx) => Self::Canceled,
ToolCallStatus::Canceled => Self::Canceled,
diff --git a/crates/agent_ui/src/conversation_view/thread_view.rs b/crates/agent_ui/src/conversation_view/thread_view.rs
index e1e458be57c..f9d673e3d1a 100644
--- a/crates/agent_ui/src/conversation_view/thread_view.rs
+++ b/crates/agent_ui/src/conversation_view/thread_view.rs
@@ -2723,6 +2723,32 @@ impl ThreadView {
cx.notify();
}
+ fn cancel_tool_call(&self, tool_call_id: acp_v2::ToolCallId, cx: &mut Context<Self>) {
+ let cancellation = self
+ .thread
+ .update(cx, |thread, cx| thread.cancel_tool_call(&tool_call_id, cx));
+ cx.spawn(async move |this, cx| {
+ if let Err(error) = cancellation.await {
+ this.update(cx, |this, cx| this.handle_thread_error(error, cx))
+ .log_err();
+ }
+ })
+ .detach();
+ }
+
+ fn cancel_terminal(&self, terminal_id: acp_v2::TerminalId, cx: &mut Context<Self>) {
+ let cancellation = self
+ .thread
+ .update(cx, |thread, cx| thread.cancel_terminal(&terminal_id, cx));
+ cx.spawn(async move |this, cx| {
+ if let Err(error) = cancellation.await {
+ this.update(cx, |this, cx| this.handle_thread_error(error, cx))
+ .log_err();
+ }
+ })
+ .detach();
+ }
+
fn cancel_thread(&self, thread: &Entity<AcpThread>, cx: &mut Context<Self>) -> Task<()> {
let cancellation = thread.update(cx, |thread, cx| thread.cancel(cx));
cx.spawn(async move |this, cx| {
@@ -5580,20 +5606,34 @@ impl ThreadView {
}
fn render_activity_status_label(&self, cx: &Context<Self>) -> Option<impl IntoElement> {
- let (id, label, tooltip) = match self.thread.read(cx).foreground_activity() {
+ let thread = self.thread.read(cx);
+ let (id, label, tooltip): (_, SharedString, _) = match thread.foreground_activity() {
ForegroundActivity::Unconfirmed => (
"activity-unconfirmed",
- "Activity unconfirmed",
+ "Activity unconfirmed".into(),
"The session is attached, but the agent has not reported its activity. You can send manually; automatic sends wait for confirmed Idle.",
),
ForegroundActivity::Unknown => (
"activity-unknown",
- "Activity unknown",
+ "Activity unknown".into(),
"The agent can't currently tell whether it is working. You can send manually; automatic sends wait for confirmed Idle.",
),
- ForegroundActivity::Idle
- | ForegroundActivity::Running
- | ForegroundActivity::RequiresAction => return None,
+ ForegroundActivity::Idle => {
+ let background_count = thread.background_work().map_or(0, <[_]>::len);
+ if background_count == 0 {
+ return None;
+ }
+ (
+ "activity-background",
+ if background_count == 1 {
+ "1 task in background".into()
+ } else {
+ format!("{background_count} tasks in background").into()
+ },
+ "The agent finished responding, but work it started keeps running in the background, such as a dev server or a scheduled task.",
+ )
+ }
+ ForegroundActivity::Running | ForegroundActivity::RequiresAction => return None,
};
Some(
div()
@@ -9226,7 +9266,7 @@ impl ThreadView {
let command_finished = output.is_some()
&& !matches!(
tool_call.status(),
- ToolCallStatus::InProgress | ToolCallStatus::Pending
+ ToolCallStatus::InProgress | ToolCallStatus::Pending | ToolCallStatus::Paused
);
let truncated_output =
output.is_some_and(|output| output.original_content_len > output.content.len());
@@ -9334,6 +9374,14 @@ impl ThreadView {
})
})
})
+ .when(terminal_data.can_cancel(), |header| {
+ let terminal_id = terminal_data.id().clone();
+ header
+ .on_stop(cx.listener(move |this, _event, _window, cx| {
+ this.cancel_terminal(terminal_id.clone(), cx);
+ }))
+ .stop_description("Asks the agent to stop this process. Its output stays here.")
+ })
.when_some(truncated_tooltip, |header, tooltip| {
header.truncated(tooltip)
})
@@ -9753,6 +9801,7 @@ impl ThreadView {
}
ToolCallStatus::Pending
| ToolCallStatus::InProgress
+ | ToolCallStatus::Paused
| ToolCallStatus::Completed
| ToolCallStatus::Failed
| ToolCallStatus::Canceled => v_flex()
@@ -10002,6 +10051,42 @@ impl ThreadView {
}),
)
})
+ .when(
+ tool_call.status() == ToolCallStatus::Paused,
+ |this| {
+ this.child(
+ div()
+ .id(("paused-tool-call", entry_ix))
+ .pr_0p5()
+ .tooltip(Tooltip::text("Paused"))
+ .child(
+ Icon::new(IconName::DebugPause)
+ .color(Color::Muted)
+ .size(IconSize::Small),
+ ),
+ )
+ },
+ )
+ .when(tool_call.can_cancel(), |this| {
+ let tool_call_id = tool_call.id.clone();
+ this.child(
+ IconButton::new(
+ ("stop-tool-call", entry_ix),
+ IconName::Stop,
+ )
+ .icon_size(IconSize::Small)
+ .icon_color(Color::Error)
+ .tooltip(Tooltip::text("Stop Tool Call"))
+ .on_click(cx.listener(
+ move |this, _, _window, cx| {
+ this.cancel_tool_call(
+ tool_call_id.clone(),
+ cx,
+ );
+ },
+ )),
+ )
+ })
.when(tool_call_output_focus, |this| {
this.child(
Button::new("open-file-button", "Open File")
diff --git a/crates/agent_ui/src/ui/terminal_tool_header.rs b/crates/agent_ui/src/ui/terminal_tool_header.rs
index ffe5c9897dd..1d6f6c2f096 100644
--- a/crates/agent_ui/src/ui/terminal_tool_header.rs
+++ b/crates/agent_ui/src/ui/terminal_tool_header.rs
@@ -28,6 +28,7 @@ pub struct TerminalToolHeader {
sandbox_warning: Option<TerminalSandboxWarning>,
on_toggle_expand: Option<ClickHandler>,
on_stop: Option<ClickHandler>,
+ stop_description: SharedString,
command_slot: Option<AnyElement>,
rounded_top: bool,
rounded_bottom: bool,
@@ -53,6 +54,7 @@ impl TerminalToolHeader {
sandbox_warning: None,
on_toggle_expand: None,
on_stop: None,
+ stop_description: "Also possible by placing your cursor inside the terminal and using regular terminal bindings.".into(),
command_slot: None,
rounded_top: false,
rounded_bottom: false,
@@ -107,6 +109,11 @@ impl TerminalToolHeader {
self
}
+ pub fn stop_description(mut self, description: impl Into<SharedString>) -> Self {
+ self.stop_description = description.into();
+ self
+ }
+
pub fn command_slot(mut self, element: impl IntoElement) -> Self {
self.command_slot = Some(element.into_any_element());
self
@@ -132,6 +139,7 @@ impl RenderOnce for TerminalToolHeader {
sandbox_warning,
on_toggle_expand,
on_stop,
+ stop_description,
command_slot,
rounded_top,
rounded_bottom,
@@ -201,8 +209,7 @@ impl RenderOnce for TerminalToolHeader {
Tooltip::with_meta(
"Stop This Command",
None,
- "Also possible by placing your cursor inside the \
- terminal and using regular terminal bindings.",
+ stop_description.clone(),
cx,
)
})