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: Fix provider-owned terminal lifecycle (#64544)

Ben Brandt656e3aed84e0
diff --git a/crates/acp_thread/src/acp_thread.rs b/crates/acp_thread/src/acp_thread.rs
index 15ef8aaf586..b170b623516 100644
--- a/crates/acp_thread/src/acp_thread.rs
+++ b/crates/acp_thread/src/acp_thread.rs
@@ -4968,30 +4968,46 @@ impl AcpThread {
output_byte_limit,
terminal,
} => {
- let entity = self.register_terminal_created(
- terminal_id.clone(),
- label,
- cwd,
- output_byte_limit,
- terminal,
- cx,
- );
+ if self.terminals.contains_key(&terminal_id) {
+ return;
+ }
+ let language_registry = self.project.read(cx).languages().clone();
+ let entity = cx.new(|cx| {
+ Terminal::new_display(
+ terminal_id.clone(),
+ &label,
+ cwd,
+ output_byte_limit.map(|limit| limit as usize),
+ terminal,
+ language_registry,
+ cx,
+ )
+ });
+ // Provider output and exit can arrive without another tool-call update.
+ cx.observe(&entity, |this, terminal, cx| {
+ for (index, entry) in this.entries.iter().enumerate() {
+ if entry
+ .terminals()
+ .any(|entry_terminal| entry_terminal == &terminal)
+ {
+ cx.emit(AcpThreadEvent::EntryUpdated(index));
+ }
+ }
+ cx.notify();
+ })
+ .detach();
+ self.terminals.insert(terminal_id.clone(), entity.clone());
if let Some(mut chunks) = self.pending_terminal_output.remove(&terminal_id) {
for data in chunks.drain(..) {
entity.update(cx, |term, cx| {
- term.inner().update(cx, |inner, cx| {
- inner.write_output(&data, cx);
- })
+ term.write_display_output(&data, cx);
});
}
}
- if let Some(_status) = self.pending_terminal_exit.remove(&terminal_id) {
- entity.update(cx, |term, cx| {
- term.inner().update(cx, |inner, _| inner.shrink_to_used());
- cx.notify();
- });
+ if let Some(status) = self.pending_terminal_exit.remove(&terminal_id) {
+ entity.update(cx, |term, cx| term.finish_display(status, cx));
}
cx.notify();
@@ -4999,9 +5015,7 @@ impl AcpThread {
TerminalProviderEvent::Output { terminal_id, data } => {
if let Some(entity) = self.terminals.get(&terminal_id) {
entity.update(cx, |term, cx| {
- term.inner().update(cx, |inner, cx| {
- inner.write_output(&data, cx);
- })
+ term.write_display_output(&data, cx);
});
} else {
self.pending_terminal_output
@@ -5025,12 +5039,11 @@ impl AcpThread {
status,
} => {
if let Some(entity) = self.terminals.get(&terminal_id) {
- entity.update(cx, |term, cx| {
- term.inner().update(cx, |inner, _| inner.shrink_to_used());
- cx.notify();
- });
+ entity.update(cx, |term, cx| term.finish_display(status, cx));
} else {
- self.pending_terminal_exit.insert(terminal_id, status);
+ self.pending_terminal_exit
+ .entry(terminal_id)
+ .or_insert(status);
}
}
}
@@ -5853,6 +5866,22 @@ mod tests {
cx,
);
});
+ cx.run_until_parked();
+ thread.update(cx, |thread, cx| {
+ let terminal = thread
+ .terminal(terminal_id.clone())
+ .expect("display terminal");
+ terminal.update(cx, |terminal, cx| {
+ assert!(!terminal.is_process_backed());
+ assert!(terminal.wait_for_exit().is_err());
+ terminal.stop_by_user(cx);
+ assert!(!terminal.was_stopped_by_user());
+ assert!(
+ terminal.output().is_none(),
+ "a display terminal must wait for the provider's exit event",
+ );
+ });
+ });
let mut output = String::new();
for line in 0..15_000 {
@@ -5867,17 +5896,36 @@ mod tests {
},
cx,
);
+ });
+ cx.run_until_parked();
+ thread.read_with(cx, |thread, cx| {
+ let terminal = thread
+ .terminal(terminal_id.clone())
+ .expect("display terminal");
+ let output = terminal.read(cx).current_output(cx);
+ assert!(output.output.contains("line 14999"));
+ assert!(output.exit_status.is_none());
+ });
+
+ thread.update(cx, |thread, cx| {
thread.on_terminal_provider_event(
TerminalProviderEvent::Exit {
terminal_id: terminal_id.clone(),
- status: acp::TerminalExitStatus::new().exit_code(0),
+ status: acp::TerminalExitStatus::new().exit_code(7),
},
cx,
);
});
+ cx.run_until_parked();
let content = thread.read_with(cx, |thread, cx| {
let term = thread.terminal(terminal_id.clone()).unwrap();
+ let output = term.read(cx).current_output(cx);
+ assert_eq!(
+ output.exit_status.and_then(|status| status.exit_code),
+ Some(7)
+ );
+ assert!(output.output.contains("line 14999"));
term.read_with(cx, |term, cx| term.inner().read(cx).get_content())
});
@@ -5885,6 +5933,68 @@ mod tests {
content.contains("line 14999"),
"expected output to remain visible after terminal exit, got: {content}"
);
+
+ let terminal = thread.read_with(cx, |thread, _| {
+ thread
+ .terminal(terminal_id.clone())
+ .expect("display terminal")
+ });
+ let ended_at = terminal.read_with(cx, |terminal, _| {
+ terminal.output().expect("completed output").ended_at
+ });
+ thread.update(cx, |thread, cx| {
+ thread.on_terminal_provider_event(
+ TerminalProviderEvent::Created {
+ terminal_id: terminal_id.clone(),
+ label: "Duplicate".to_string(),
+ cwd: None,
+ output_byte_limit: None,
+ terminal: lower.clone(),
+ },
+ cx,
+ );
+ assert_eq!(
+ thread
+ .terminal(terminal_id.clone())
+ .expect("terminal")
+ .entity_id(),
+ terminal.entity_id(),
+ );
+ thread.on_terminal_provider_event(
+ TerminalProviderEvent::Exit {
+ terminal_id: terminal_id.clone(),
+ status: acp::TerminalExitStatus::new().signal("SIGTERM"),
+ },
+ cx,
+ );
+ });
+ terminal.read_with(cx, |terminal, _| {
+ let output = terminal.output().expect("completed output");
+ assert_eq!(output.ended_at, ended_at);
+ assert_eq!(output.exit_status.exit_code, Some(7));
+ assert_eq!(output.exit_status.signal, None);
+ assert_eq!(output.content, content);
+ });
+
+ thread.update(cx, |thread, cx| {
+ thread.on_terminal_provider_event(
+ TerminalProviderEvent::Output {
+ terminal_id,
+ data: b"late output\n".to_vec(),
+ },
+ cx,
+ );
+ });
+ terminal.read_with(cx, |terminal, cx| {
+ let output = terminal.output().expect("completed output");
+ assert_eq!(output.ended_at, ended_at);
+ assert_eq!(output.exit_status.exit_code, Some(7));
+ assert_eq!(output.exit_status.signal, None);
+ assert!(output.content.contains("late output"));
+ assert_eq!(output.content, lower.read(cx).get_content());
+ assert_eq!(output.original_content_len, output.content.len());
+ assert_eq!(output.content_line_count, lower.read(cx).total_lines());
+ });
}
#[gpui::test]
@@ -5920,6 +6030,13 @@ mod tests {
// Send Exit BEFORE Created
thread.update(cx, |thread, cx| {
+ thread.on_terminal_provider_event(
+ TerminalProviderEvent::Exit {
+ terminal_id: terminal_id.clone(),
+ status: acp::TerminalExitStatus::new().signal("SIGTERM"),
+ },
+ cx,
+ );
thread.on_terminal_provider_event(
TerminalProviderEvent::Exit {
terminal_id: terminal_id.clone(),
@@ -5927,6 +6044,13 @@ mod tests {
},
cx,
);
+ thread.on_terminal_provider_event(
+ TerminalProviderEvent::Output {
+ terminal_id: terminal_id.clone(),
+ data: b"\nlate output".to_vec(),
+ },
+ cx,
+ );
});
// Now create a display-only lower-level terminal and send Created
@@ -5958,6 +6082,12 @@ mod tests {
// Output should be present after Created (flushed from buffer)
let content = thread.read_with(cx, |thread, cx| {
let term = thread.terminal(terminal_id.clone()).unwrap();
+ let output = term.read(cx).current_output(cx);
+ let exit_status = output.exit_status.expect("buffered exit status");
+ assert_eq!(exit_status.signal.as_deref(), Some("SIGTERM"));
+ assert_eq!(exit_status.exit_code, None);
+ assert!(output.output.contains("pre-exit data"));
+ assert!(output.output.contains("late output"));
term.read_with(cx, |t, cx| t.inner().read(cx).get_content())
});
@@ -5977,12 +6107,24 @@ mod tests {
#[cfg(unix)]
#[gpui::test]
async fn test_terminal_kill_allows_wait_for_exit_to_complete(cx: &mut gpui::TestAppContext) {
+ assert_process_terminal_can_stop(false, cx).await;
+ }
+
+ #[cfg(unix)]
+ #[gpui::test]
+ async fn test_headless_terminal_retains_process_control(cx: &mut gpui::TestAppContext) {
+ assert_process_terminal_can_stop(true, cx).await;
+ }
+
+ #[cfg(unix)]
+ async fn assert_process_terminal_can_stop(headless: bool, cx: &mut gpui::TestAppContext) {
use std::collections::HashMap;
use task::Shell;
use util::shell_builder::ShellBuilder;
init_test(cx);
cx.executor().allow_parking();
+ cx.update(|cx| cx.set_global(::terminal::HeadlessTerminal(headless)));
let fs = FakeFs::new(cx.executor());
let project = Project::test(fs, [], cx).await;
@@ -6000,7 +6142,6 @@ mod tests {
let terminal_id = acp::TerminalId::new(uuid::Uuid::new_v4().to_string());
- // Create a real PTY terminal that runs a command which prints output then sleeps
// We use printf instead of echo and chain with && sleep to ensure proper execution
let (program, args) = ShellBuilder::new(&Shell::System, false).build(
Some("printf 'output_before_kill\\n' && sleep 60".to_owned()),
@@ -6039,49 +6180,61 @@ mod tests {
.unwrap();
let lower_terminal = cx.new(|cx| builder.subscribe(cx));
+ assert_eq!(
+ lower_terminal.read_with(cx, |terminal, _| terminal.is_pty()),
+ !headless
+ );
// Create the acp_thread Terminal wrapper
thread.update(cx, |thread, cx| {
- thread.on_terminal_provider_event(
- TerminalProviderEvent::Created {
- terminal_id: terminal_id.clone(),
- label: "printf output_before_kill && sleep 60".to_string(),
- cwd: None,
- output_byte_limit: None,
- terminal: lower_terminal.clone(),
- },
+ let terminal = thread.register_terminal_created(
+ terminal_id.clone(),
+ "printf output_before_kill && sleep 60".to_string(),
+ None,
+ None,
+ lower_terminal.clone(),
cx,
);
+ assert!(terminal.read(cx).is_process_backed());
});
// Poll until the printf command produces output, rather than using a
// fixed sleep which is flaky on loaded machines.
- let deadline = std::time::Instant::now() + Duration::from_secs(10);
- loop {
- let has_output = thread.read_with(cx, |thread, cx| {
- let term = thread
- .terminals
- .get(&terminal_id)
- .expect("terminal not found");
- let content = term.read(cx).inner().read(cx).get_content();
- content.contains("output_before_kill")
- });
- if has_output {
- break;
+ if !headless {
+ let deadline = std::time::Instant::now() + Duration::from_secs(10);
+ loop {
+ let has_output = thread.read_with(cx, |thread, cx| {
+ let term = thread
+ .terminals
+ .get(&terminal_id)
+ .expect("terminal not found");
+ let content = term.read(cx).inner().read(cx).get_content();
+ content.contains("output_before_kill")
+ });
+ if has_output {
+ break;
+ }
+ assert!(
+ std::time::Instant::now() < deadline,
+ "Timed out waiting for printf output to appear in terminal",
+ );
+ cx.executor().timer(Duration::from_millis(50)).await;
}
- assert!(
- std::time::Instant::now() < deadline,
- "Timed out waiting for printf output to appear in terminal",
- );
- cx.executor().timer(Duration::from_millis(50)).await;
}
// Get the acp_thread Terminal and kill it
+ let killed_at = std::time::Instant::now();
let wait_for_exit = thread.update(cx, |thread, cx| {
let term = thread.terminals.get(&terminal_id).unwrap();
- let wait_for_exit = term.read(cx).wait_for_exit();
+ let wait_for_exit = term.read(cx).wait_for_exit().expect("process terminal");
term.update(cx, |term, cx| {
- term.kill(cx);
+ assert!(term.output().is_none(), "the process must still be running");
+ if headless {
+ term.stop_by_user(cx);
+ assert!(term.was_stopped_by_user());
+ } else {
+ term.kill(cx);
+ }
});
wait_for_exit
});
@@ -6100,22 +6253,28 @@ mod tests {
"wait_for_exit should complete after kill, but it timed out. \
This indicates kill_active_task is not properly killing the shell process."
);
+ assert!(
+ killed_at.elapsed() < Duration::from_secs(5),
+ "the process must stop without waiting for its natural exit",
+ );
// Give the system a chance to process any pending updates
cx.run_until_parked();
- // Verify that the underlying terminal still has the output that was
- // written before the kill. This verifies that killing doesn't lose output.
- let inner_content = thread.read_with(cx, |thread, cx| {
- let term = thread.terminals.get(&terminal_id).unwrap();
- term.read(cx).inner().read(cx).get_content()
- });
+ if !headless {
+ // Verify that the underlying terminal still has the output that was
+ // written before the kill. This verifies that killing doesn't lose output.
+ let inner_content = thread.read_with(cx, |thread, cx| {
+ let term = thread.terminals.get(&terminal_id).unwrap();
+ term.read(cx).inner().read(cx).get_content()
+ });
- assert!(
- inner_content.contains("output_before_kill"),
- "Underlying terminal should contain output from before kill, got: {}",
- inner_content
- );
+ assert!(
+ inner_content.contains("output_before_kill"),
+ "Underlying terminal should contain output from before kill, got: {}",
+ inner_content
+ );
+ }
}
#[gpui::test]
diff --git a/crates/acp_thread/src/terminal.rs b/crates/acp_thread/src/terminal.rs
index 1dde55ea437..a785de67a42 100644
--- a/crates/acp_thread/src/terminal.rs
+++ b/crates/acp_thread/src/terminal.rs
@@ -1,5 +1,5 @@
use agent_client_protocol::schema::v1 as acp;
-use anyhow::Result;
+use anyhow::{Result, bail};
use collections::HashMap;
use futures::{FutureExt as _, future::Shared};
use gpui::{App, AppContext, AsyncApp, Context, Entity, Task};
@@ -11,7 +11,6 @@ use serde::{Deserialize, Serialize};
use std::{
collections::HashMap as StdHashMap,
path::PathBuf,
- process::ExitStatus,
sync::{
Arc,
atomic::{AtomicBool, Ordering},
@@ -407,7 +406,7 @@ pub struct Terminal {
started_at: Instant,
output: Option<TerminalOutput>,
output_byte_limit: Option<usize>,
- _output_task: Shared<Task<acp::TerminalExitStatus>>,
+ execution: TerminalExecution,
/// Flag indicating whether this terminal was stopped by explicit user action
/// (e.g., clicking the Stop button). This is set before kill() is called
/// so that code awaiting wait_for_exit() can check it deterministically.
@@ -419,9 +418,14 @@ pub struct Terminal {
_sandbox: Option<SandboxConfigHandle>,
}
+enum TerminalExecution {
+ Process(Shared<Task<acp::TerminalExitStatus>>),
+ Display,
+}
+
pub struct TerminalOutput {
pub ended_at: Instant,
- pub exit_status: Option<ExitStatus>,
+ pub exit_status: acp::TerminalExitStatus,
pub content: String,
pub original_content_len: usize,
pub content_line_count: usize,
@@ -469,21 +473,17 @@ impl Terminal {
output: None,
output_byte_limit,
user_stopped: Arc::new(AtomicBool::new(false)),
- _output_task: cx
- .spawn(async move |this, cx| {
- let exit_status = command_task.await;
+ execution: TerminalExecution::Process(
+ cx.spawn(async move |this, cx| {
+ let exit_status = command_task.await.map(portable_pty::ExitStatus::from);
+ let exit_status = acp::TerminalExitStatus::new()
+ .exit_code(exit_status.as_ref().map(|status| status.exit_code()))
+ .signal(
+ exit_status.and_then(|status| status.signal().map(ToOwned::to_owned)),
+ );
this.update(cx, |this, cx| {
- let (content, original_content_len) = this.truncated_output(cx);
- let content_line_count = this.terminal.read(cx).total_lines();
-
- this.output = Some(TerminalOutput {
- ended_at: Instant::now(),
- exit_status,
- content,
- original_content_len,
- content_line_count,
- });
+ this.cache_output(exit_status.clone(), Instant::now(), cx);
this.terminal.update(cx, |terminal, _cx| {
terminal.release_pty_resources();
});
@@ -497,17 +497,43 @@ impl Terminal {
.spawn(async move { sandbox.drop_on_current_thread() })
.detach();
}
- cx.notify();
})
.ok();
- let exit_status = exit_status.map(portable_pty::ExitStatus::from);
-
- acp::TerminalExitStatus::new()
- .exit_code(exit_status.as_ref().map(|e| e.exit_code()))
- .signal(exit_status.and_then(|e| e.signal().map(ToOwned::to_owned)))
+ exit_status
})
.shared(),
+ ),
+ }
+ }
+
+ pub fn new_display(
+ id: acp::TerminalId,
+ command_label: &str,
+ working_dir: Option<PathBuf>,
+ output_byte_limit: Option<usize>,
+ terminal: Entity<terminal::Terminal>,
+ language_registry: Arc<LanguageRegistry>,
+ cx: &mut Context<Self>,
+ ) -> Self {
+ Self {
+ id,
+ command: cx.new(|cx| {
+ Markdown::new(
+ format!("```\n{}\n```", command_label).into(),
+ Some(language_registry),
+ None,
+ cx,
+ )
+ }),
+ working_dir,
+ terminal,
+ started_at: Instant::now(),
+ output: None,
+ output_byte_limit,
+ execution: TerminalExecution::Display,
+ user_stopped: Arc::new(AtomicBool::new(false)),
+ _sandbox: None,
}
}
@@ -515,11 +541,24 @@ impl Terminal {
&self.id
}
- pub fn wait_for_exit(&self) -> Shared<Task<acp::TerminalExitStatus>> {
- self._output_task.clone()
+ /// Ownership is independent of the renderer's PTY: headless tasks still own a process.
+ pub fn is_process_backed(&self) -> bool {
+ matches!(self.execution, TerminalExecution::Process(_))
+ }
+
+ pub fn wait_for_exit(&self) -> Result<Shared<Task<acp::TerminalExitStatus>>> {
+ match &self.execution {
+ TerminalExecution::Process(task) => Ok(task.clone()),
+ TerminalExecution::Display => {
+ bail!("Agent-provided terminals have no client-owned process to wait for")
+ }
+ }
}
pub fn kill(&mut self, cx: &mut App) {
+ if !self.is_process_backed() {
+ return;
+ }
self.terminal.update(cx, |terminal, _cx| {
terminal.kill_active_task();
});
@@ -528,6 +567,9 @@ impl Terminal {
/// Marks this terminal as stopped by user action and then kills it.
/// This should be called when the user explicitly clicks a Stop button.
pub fn stop_by_user(&mut self, cx: &mut App) {
+ if !self.is_process_backed() {
+ return;
+ }
self.user_stopped.store(true, Ordering::SeqCst);
self.kill(cx);
}
@@ -539,17 +581,11 @@ impl Terminal {
pub fn current_output(&self, cx: &App) -> acp::TerminalOutputResponse {
if let Some(output) = self.output.as_ref() {
- let exit_status = output.exit_status.map(portable_pty::ExitStatus::from);
-
acp::TerminalOutputResponse::new(
output.content.clone(),
output.original_content_len > output.content.len(),
)
- .exit_status(
- acp::TerminalExitStatus::new()
- .exit_code(exit_status.as_ref().map(|e| e.exit_code()))
- .signal(exit_status.and_then(|e| e.signal().map(ToOwned::to_owned))),
- )
+ .exit_status(output.exit_status.clone())
} else {
let (current_content, original_len) = self.truncated_output(cx);
let truncated = current_content.len() < original_len;
@@ -557,6 +593,50 @@ impl Terminal {
}
}
+ pub(crate) fn write_display_output(&mut self, data: &[u8], cx: &mut Context<Self>) {
+ if self.is_process_backed() {
+ return;
+ }
+ self.terminal
+ .update(cx, |terminal, cx| terminal.write_output(data, cx));
+ if let Some(output) = &self.output {
+ // A process may exit before its final output arrives. Refresh the
+ // cached content without changing its completion time or status.
+ self.cache_output(output.exit_status.clone(), output.ended_at, cx);
+ }
+ }
+
+ pub(crate) fn finish_display(
+ &mut self,
+ exit_status: acp::TerminalExitStatus,
+ cx: &mut Context<Self>,
+ ) {
+ if self.is_process_backed() || self.output.is_some() {
+ return;
+ }
+ self.terminal
+ .update(cx, |terminal, _| terminal.shrink_to_used());
+ self.cache_output(exit_status, Instant::now(), cx);
+ }
+
+ fn cache_output(
+ &mut self,
+ exit_status: acp::TerminalExitStatus,
+ ended_at: Instant,
+ cx: &mut Context<Self>,
+ ) {
+ let (content, original_content_len) = self.truncated_output(cx);
+ let content_line_count = self.terminal.read(cx).total_lines();
+ self.output = Some(TerminalOutput {
+ ended_at,
+ exit_status,
+ content,
+ original_content_len,
+ content_line_count,
+ });
+ cx.notify();
+ }
+
fn truncated_output(&self, cx: &App) -> (String, usize) {
let terminal = self.terminal.read(cx);
let mut content = terminal.get_content();
diff --git a/crates/agent/src/agent.rs b/crates/agent/src/agent.rs
index c5526e76145..9ea7e6bbfa7 100644
--- a/crates/agent/src/agent.rs
+++ b/crates/agent/src/agent.rs
@@ -3594,9 +3594,8 @@ impl TerminalHandle for AcpTerminalHandle {
}
fn wait_for_exit(&self, cx: &AsyncApp) -> Result<Shared<Task<acp::TerminalExitStatus>>> {
- Ok(self
- .terminal
- .read_with(cx, |term, _cx| term.wait_for_exit()))
+ self.terminal
+ .read_with(cx, |term, _cx| term.wait_for_exit())
}
fn current_output(&self, cx: &AsyncApp) -> Result<acp::TerminalOutputResponse> {
diff --git a/crates/agent_servers/src/acp.rs b/crates/agent_servers/src/acp.rs
index 9da6f3e1ca8..c4d8a0fd6ba 100644
--- a/crates/agent_servers/src/acp.rs
+++ b/crates/agent_servers/src/acp.rs
@@ -5113,7 +5113,7 @@ fn handle_wait_for_terminal_exit(
.run_until_cancelled(async {
let exit_status = thread
.update(cx, |thread, cx| {
- anyhow::Ok(thread.terminal(args.terminal_id)?.read(cx).wait_for_exit())
+ thread.terminal(args.terminal_id)?.read(cx).wait_for_exit()
})
.flatten_acp()?
.await;
diff --git a/crates/agent_ui/src/conversation_view.rs b/crates/agent_ui/src/conversation_view.rs
index 9c15fe2eeed..e2896e9ad8f 100644
--- a/crates/agent_ui/src/conversation_view.rs
+++ b/crates/agent_ui/src/conversation_view.rs
@@ -9525,6 +9525,108 @@ pub(crate) mod tests {
})
}
+ #[gpui::test]
+ async fn test_display_terminal_does_not_move_to_background_when_tool_completes(
+ cx: &mut TestAppContext,
+ ) {
+ init_test(cx);
+ for (exit_status, failure_selector) in [
+ (
+ acp::TerminalExitStatus::new().exit_code(7),
+ "terminal-tool-failed-Some(7)",
+ ),
+ (
+ acp::TerminalExitStatus::new().signal("SIGTERM"),
+ "terminal-tool-failed-None",
+ ),
+ (
+ acp::TerminalExitStatus::new().exit_code(u32::MAX),
+ "terminal-tool-failed-Some(4294967295)",
+ ),
+ ] {
+ let (conversation_view, cx) =
+ setup_conversation_view(StubAgentServer::new(StubAgentConnection::new()), 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 terminal_id = acp::TerminalId::new("provider-terminal");
+ let tool_id = acp::ToolCallId::new("provider-tool");
+ let terminal = cx.new(|cx| {
+ terminal::TerminalBuilder::new_display_only(
+ Default::default(),
+ terminal::terminal_settings::AlternateScroll::On,
+ None,
+ 0,
+ cx.background_executor(),
+ util::paths::PathStyle::local(),
+ )
+ .subscribe(cx)
+ });
+ thread.update(cx, |thread, cx| {
+ thread.on_terminal_provider_event(
+ acp_thread::TerminalProviderEvent::Created {
+ terminal_id: terminal_id.clone(),
+ label: "provider command".into(),
+ cwd: None,
+ output_byte_limit: None,
+ terminal,
+ },
+ cx,
+ );
+ thread
+ .handle_session_update(
+ acp::SessionUpdate::ToolCall(
+ acp::ToolCall::new(tool_id.clone(), "provider command")
+ .kind(acp::ToolKind::Execute)
+ .status(acp::ToolCallStatus::InProgress)
+ .content(vec![acp::ToolCallContent::Terminal(acp::Terminal::new(
+ terminal_id.clone(),
+ ))]),
+ ),
+ cx,
+ )
+ .expect("terminal tool call");
+ });
+ cx.run_until_parked();
+ let entry_state = thread_view.read_with(cx, |view, _| view.entry_view_state.clone());
+ entry_state.update(cx, |state, cx| {
+ state.expand_tool_call(tool_id.clone());
+ cx.notify();
+ });
+ assert!(cx.debug_bounds("ICON-Stop").is_none());
+ thread.update(cx, |thread, cx| {
+ thread
+ .handle_session_update(
+ acp::SessionUpdate::ToolCallUpdate(acp::ToolCallUpdate::new(
+ tool_id.clone(),
+ acp::ToolCallUpdateFields::new().status(acp::ToolCallStatus::Completed),
+ )),
+ cx,
+ )
+ .expect("tool completion");
+ });
+ cx.run_until_parked();
+ assert!(entry_state.read_with(cx, |state, _| state.is_tool_call_expanded(&tool_id)));
+ assert!(cx.debug_bounds(failure_selector).is_none());
+ thread.update(cx, |thread, cx| {
+ thread.on_terminal_provider_event(
+ acp_thread::TerminalProviderEvent::Exit {
+ terminal_id,
+ status: exit_status,
+ },
+ cx,
+ );
+ });
+ cx.run_until_parked();
+ assert!(entry_state.read_with(cx, |state, _| state.is_tool_call_expanded(&tool_id)));
+ assert!(
+ cx.debug_bounds(failure_selector).is_some(),
+ "expected rendered header metadata: {failure_selector}",
+ );
+ assert!(cx.debug_bounds("ICON-Stop").is_none());
+ }
+ }
+
#[gpui::test]
async fn test_tool_permission_buttons_terminal_with_pattern(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.rs
index eb55ab757fd..dea51ba96c4 100644
--- a/crates/agent_ui/src/conversation_view/thread_view.rs
+++ b/crates/agent_ui/src/conversation_view/thread_view.rs
@@ -7896,7 +7896,13 @@ impl ThreadView {
let output_line_count = output.map(|output| output.content_line_count).unwrap_or(0);
let command_failed = command_finished
- && output.is_some_and(|o| o.exit_status.is_some_and(|status| !status.success()));
+ && output.is_some_and(|output| {
+ output
+ .exit_status
+ .exit_code
+ .is_some_and(|exit_code| exit_code != 0)
+ || output.exit_status.signal.is_some()
+ });
let time_elapsed = if let Some(output) = output {
output.ended_at.duration_since(started_at)
@@ -7967,26 +7973,24 @@ impl ThreadView {
cx.notify();
}
}))
- .on_stop({
- let terminal = terminal.clone();
- cx.listener(move |this, _event, _window, cx| {
- terminal.update(cx, |terminal, cx| {
- terminal.stop_by_user(cx);
- });
- if AgentSettings::get_global(cx).cancel_generation_on_terminal_stop {
- this.cancel_generation(cx);
- }
+ .when(terminal_data.is_process_backed(), |header| {
+ header.on_stop({
+ let terminal = terminal.clone();
+ cx.listener(move |this, _event, _window, cx| {
+ terminal.update(cx, |terminal, cx| {
+ terminal.stop_by_user(cx);
+ });
+ if AgentSettings::get_global(cx).cancel_generation_on_terminal_stop {
+ this.cancel_generation(cx);
+ }
+ })
})
})
.when_some(truncated_tooltip, |header, tooltip| {
header.truncated(tooltip)
})
.when(tool_failed || command_failed, |header| {
- header.failed(
- output
- .and_then(|o| o.exit_status)
- .map(|status| status.code().unwrap_or(-1)),
- )
+ header.failed(output.and_then(|output| output.exit_status.exit_code))
})
.when_some(tool_call.sandbox_not_applied.as_ref(), |header, reason| {
header.sandbox_warning(self.sandbox_not_applied_warning(reason, cx))
diff --git a/crates/agent_ui/src/entry_view_state.rs b/crates/agent_ui/src/entry_view_state.rs
index 15538796280..a77366b7d89 100644
--- a/crates/agent_ui/src/entry_view_state.rs
+++ b/crates/agent_ui/src/entry_view_state.rs
@@ -323,7 +323,11 @@ impl EntryViewState {
entry.insert(element);
}
collections::hash_map::Entry::Occupied(_entry) => {
- if is_tool_call_completed && terminal.read(cx).output().is_none() {
+ let terminal = terminal.read(cx);
+ if is_tool_call_completed
+ && terminal.is_process_backed()
+ && terminal.output().is_none()
+ {
cx.emit(EntryViewEvent {
entry_index: index,
view_event: ViewEvent::TerminalMovedToBackground(id.clone()),
diff --git a/crates/agent_ui/src/ui/terminal_tool_header.rs b/crates/agent_ui/src/ui/terminal_tool_header.rs
index f22fce6797f..7627c31c6cd 100644
--- a/crates/agent_ui/src/ui/terminal_tool_header.rs
+++ b/crates/agent_ui/src/ui/terminal_tool_header.rs
@@ -24,7 +24,7 @@ pub struct TerminalToolHeader {
running: bool,
truncated_tooltip: Option<SharedString>,
failed: bool,
- exit_code: Option<i32>,
+ exit_code: Option<u32>,
sandbox_warning: Option<TerminalSandboxWarning>,
on_toggle_expand: Option<ClickHandler>,
on_stop: Option<ClickHandler>,
@@ -70,7 +70,7 @@ impl TerminalToolHeader {
self
}
- pub fn failed(mut self, exit_code: Option<i32>) -> Self {
+ pub fn failed(mut self, exit_code: Option<u32>) -> Self {
self.failed = true;
self.exit_code = exit_code;
self
@@ -178,22 +178,25 @@ impl RenderOnce for TerminalToolHeader {
.color(Color::Muted)
.with_rotate_animation(2),
)
- .child(Divider::vertical().color(DividerColor::Border).ml_1())
- .child(
- IconButton::new(child_id("stop"), IconName::Stop)
- .icon_size(IconSize::Small)
- .icon_color(Color::Error)
- .tooltip(move |_window, cx| {
- Tooltip::with_meta(
- "Stop This Command",
- None,
- "Also possible by placing your cursor inside the terminal \
- and using regular terminal bindings.",
- cx,
- )
- })
- .when_some(on_stop, |this, handler| this.on_click(handler)),
- )
+ .when_some(on_stop, |header, handler| {
+ header
+ .child(Divider::vertical().color(DividerColor::Border).ml_1())
+ .child(
+ IconButton::new(child_id("stop"), IconName::Stop)
+ .icon_size(IconSize::Small)
+ .icon_color(Color::Error)
+ .tooltip(move |_window, cx| {
+ Tooltip::with_meta(
+ "Stop This Command",
+ None,
+ "Also possible by placing your cursor inside the \
+ terminal and using regular terminal bindings.",
+ cx,
+ )
+ })
+ .on_click(handler),
+ )
+ })
})
.when_some(truncated_tooltip, |header, tooltip| {
header.child(
@@ -206,16 +209,18 @@ impl RenderOnce for TerminalToolHeader {
)
})
.when(failed, |header| {
- header.child(
- IconButton::new(child_id("failed"), IconName::Close)
- .cursor_style(CursorStyle::Arrow)
- .style(ButtonStyle::Transparent)
- .icon_size(IconSize::Small)
- .icon_color(Color::Error)
- .when_some(exit_code, |this, code| {
- this.tooltip(Tooltip::text(format!("Exited with code {code}")))
- }),
- )
+ header
+ .debug_selector(|| format!("terminal-tool-failed-{exit_code:?}"))
+ .child(
+ IconButton::new(child_id("failed"), IconName::Close)
+ .cursor_style(CursorStyle::Arrow)
+ .style(ButtonStyle::Transparent)
+ .icon_size(IconSize::Small)
+ .icon_color(Color::Error)
+ .when_some(exit_code, |this, code| {
+ this.tooltip(Tooltip::text(format!("Exited with code {code}")))
+ }),
+ )
})
.when_some(sandbox_warning, |header, warning| {
let TerminalSandboxWarning {
@@ -247,6 +252,48 @@ impl RenderOnce for TerminalToolHeader {
}
}
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[gpui::test]
+ fn running_header_only_offers_stop_when_control_is_available(cx: &mut gpui::TestAppContext) {
+ struct Header {
+ stoppable: bool,
+ stops: usize,
+ }
+ impl Render for Header {
+ fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
+ div().w(px(400.)).child(
+ TerminalToolHeader::new("test", "test", "/project", true)
+ .running(true)
+ .when(self.stoppable, |header| {
+ header.on_stop(cx.listener(|this, _, _, _| this.stops += 1))
+ }),
+ )
+ }
+ }
+
+ crate::test_support::init_test(cx);
+ let (header, cx) = cx.add_window_view(|_, _| Header {
+ stoppable: false,
+ stops: 0,
+ });
+ cx.run_until_parked();
+ assert!(cx.debug_bounds("ICON-Stop").is_none());
+
+ header.update(cx, |header, cx| {
+ header.stoppable = true;
+ cx.notify();
+ });
+ let stop = cx
+ .debug_bounds("ICON-Stop")
+ .expect("owned process Stop control");
+ cx.simulate_click(stop.center(), gpui::Modifiers::default());
+ assert_eq!(header.read_with(cx, |header, _| header.stops), 1);
+ }
+}
+
impl Component for TerminalToolHeader {
fn scope() -> ComponentScope {
ComponentScope::Agent