Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
agent: Add terminal output head and tail options (#58257)
Richard Feldmanc0db923b2431
diff --git a/crates/agent/src/tests/mod.rs b/crates/agent/src/tests/mod.rsindex 16faa56c786..dbe62e4cf2f 100644--- a/crates/agent/src/tests/mod.rs+++ b/crates/agent/src/tests/mod.rs@@ -117,6 +117,11 @@ impl FakeTerminalHandle {}}+ pub(crate) fn with_output(mut self, output: acp::TerminalOutputResponse) -> Self {+ self.output = output;+ self+ }+pub(crate) fn was_killed(&self) -> bool {self.killed.load(Ordering::SeqCst)}@@ -181,6 +186,7 @@ pub(crate) struct FakeThreadEnvironment {terminal_handle: Option<Rc<FakeTerminalHandle>>,subagent_handle: Option<Rc<FakeSubagentHandle>>,terminal_creations: Arc<AtomicUsize>,+ terminal_output_limits: std::cell::RefCell<Vec<Option<u64>>>,}impl FakeThreadEnvironment {@@ -194,6 +200,10 @@ impl FakeThreadEnvironment {pub(crate) fn terminal_creation_count(&self) -> usize {self.terminal_creations.load(Ordering::SeqCst)}++ pub(crate) fn terminal_output_limits(&self) -> Vec<Option<u64>> {+ self.terminal_output_limits.borrow().clone()+ }}impl crate::ThreadEnvironment for FakeThreadEnvironment {@@ -202,11 +212,14 @@ impl crate::ThreadEnvironment for FakeThreadEnvironment {_command: String,_extra_env: Vec<acp::EnvVariable>,_cwd: Option<std::path::PathBuf>,- _output_byte_limit: Option<u64>,+ output_byte_limit: Option<u64>,_sandbox_wrap: Option<acp_thread::SandboxWrap>,_cx: &mut AsyncApp,) -> Task<Result<Rc<dyn crate::TerminalHandle>>> {self.terminal_creations.fetch_add(1, Ordering::SeqCst);+ self.terminal_output_limits+ .borrow_mut()+ .push(output_byte_limit);let handle = self.terminal_handle.clone()@@ -5850,6 +5863,95 @@ async fn test_max_subagent_depth_prevents_tool_registration(cx: &mut TestAppCont});}+#[gpui::test]+async fn test_terminal_tail_tool_schema_gated_by_feature_flag(cx: &mut TestAppContext) {+ init_test(cx);++ let fs = FakeFs::new(cx.executor());+ fs.insert_tree(path!("/test"), json!({})).await;+ let project = Project::test(fs, [path!("/test").as_ref()], cx).await;+ let project_context = cx.new(|_cx| ProjectContext::default());+ let context_server_store = project.read_with(cx, |project, _| project.context_server_store());+ let context_server_registry = cx.new(|cx| ContextServerRegistry::new(context_server_store, cx));+ let model = Arc::new(FakeLanguageModel::default());++ let thread_without_flag = cx.new(|cx| {+ let environment = Rc::new(+ FakeThreadEnvironment::default().with_terminal(FakeTerminalHandle::new_never_exits(cx)),+ );+ let mut thread = Thread::new(+ project.clone(),+ project_context.clone(),+ context_server_registry.clone(),+ Templates::new(),+ Some(model.clone() as Arc<dyn LanguageModel>),+ cx,+ );+ thread.add_default_tools(environment, cx);+ thread+ });++ thread_without_flag+ .update(cx, |thread, cx| {+ thread.send(UserMessageId::new(), ["hello"], cx)+ })+ .unwrap();+ cx.run_until_parked();++ let completion = model.pending_completions().pop().unwrap();+ let terminal_tool = completion+ .tools+ .iter()+ .find(|tool| tool.name == TerminalTool::NAME)+ .expect("terminal tool should be present");+ let schema_text = terminal_tool.input_schema.to_string();+ assert!(!schema_text.contains("head_lines"));+ assert!(!schema_text.contains("tail_lines"));+ assert!(!terminal_tool.description.contains("head_lines"));+ assert!(!terminal_tool.description.contains("tail_lines"));+ model.end_last_completion_stream();+ cx.run_until_parked();++ cx.update(|cx| {+ cx.update_flags(false, vec!["terminal-tail".to_string()]);+ });++ let thread_with_flag = cx.new(|cx| {+ let environment = Rc::new(+ FakeThreadEnvironment::default().with_terminal(FakeTerminalHandle::new_never_exits(cx)),+ );+ let mut thread = Thread::new(+ project,+ project_context,+ context_server_registry,+ Templates::new(),+ Some(model.clone() as Arc<dyn LanguageModel>),+ cx,+ );+ thread.add_default_tools(environment, cx);+ thread+ });++ thread_with_flag+ .update(cx, |thread, cx| {+ thread.send(UserMessageId::new(), ["hello again"], cx)+ })+ .unwrap();+ cx.run_until_parked();++ let completion = model.pending_completions().pop().unwrap();+ let terminal_tool = completion+ .tools+ .iter()+ .find(|tool| tool.name == TerminalTool::NAME)+ .expect("terminal tool should be present");+ let schema_text = terminal_tool.input_schema.to_string();+ assert!(schema_text.contains("head_lines"));+ assert!(schema_text.contains("tail_lines"));+ assert!(terminal_tool.description.contains("head_lines"));+ assert!(terminal_tool.description.contains("tail_lines"));+}+#[gpui::test]async fn test_lsp_tools_gated_by_feature_flag(cx: &mut TestAppContext) {init_test(cx);diff --git a/crates/agent/src/thread.rs b/crates/agent/src/thread.rsindex 96aeca7ff2e..a31e2ed70ee 100644--- a/crates/agent/src/thread.rs+++ b/crates/agent/src/thread.rs@@ -3,15 +3,16 @@ use crate::{DbLanguageModel, DbThread, DeletePathTool, DiagnosticsTool, EditFileTool, FetchTool,FindPathTool, FindReferencesTool, GetCodeActionsTool, GoToDefinitionTool, GrepTool,ListDirectoryTool, MovePathTool, ProjectSnapshot, ReadFileTool, RenameTool, SpawnAgentTool,- SystemPromptTemplate, Template, Templates, TerminalTool, ToolPermissionDecision,- UpdatePlanTool, UpdateTitleTool, WebSearchTool, WriteFileTool, decide_permission_from_settings,+ SystemPromptTemplate, Template, Templates, TerminalTool, TerminalToolWithoutTail,+ ToolPermissionDecision, UpdatePlanTool, UpdateTitleTool, WebSearchTool, WriteFileTool,+ decide_permission_from_settings,};use acp_thread::{MentionUri, UserMessageId};use action_log::ActionLog;use agent_settings::UserAgentsMd;use feature_flags::{- FeatureFlagAppExt as _, LspToolFeatureFlag, RenameToolFeatureFlag, UpdatePlanToolFeatureFlag,- UpdateTitleToolFeatureFlag,+ FeatureFlagAppExt as _, LspToolFeatureFlag, RenameToolFeatureFlag, TerminalTailFeatureFlag,+ UpdatePlanToolFeatureFlag, UpdateTitleToolFeatureFlag,};use agent_client_protocol::schema as acp;@@ -1751,7 +1752,14 @@ impl Thread {self.action_log.clone(),update_agent_location,));- self.add_tool(TerminalTool::new(self.project.clone(), environment.clone()));+ if cx.has_flag::<TerminalTailFeatureFlag>() {+ self.add_tool(TerminalTool::new(self.project.clone(), environment.clone()));+ } else {+ self.add_tool(TerminalToolWithoutTail::new(+ self.project.clone(),+ environment.clone(),+ ));+ }self.add_tool(WebSearchTool);self.add_tool(DiagnosticsTool::new(self.project.clone()));diff --git a/crates/agent/src/tools/terminal_tool.rs b/crates/agent/src/tools/terminal_tool.rsindex 9944b57e0bd..ca25834e4f2 100644--- a/crates/agent/src/tools/terminal_tool.rs+++ b/crates/agent/src/tools/terminal_tool.rs@@ -1,7 +1,7 @@use agent_client_protocol::schema as acp;use anyhow::Result;use futures::FutureExt as _;-use gpui::{App, Entity, SharedString, Task};+use gpui::{App, AsyncApp, Entity, SharedString, Task};use project::Project;use schemars::JsonSchema;use serde::{Deserialize, Serialize};@@ -29,6 +29,8 @@ const COMMAND_OUTPUT_LIMIT: u64 = 16 * 1024;////// Do not generate terminal commands that use shell substitutions or interpolations such as `$VAR`, `${VAR}`, `$(...)`, backticks, `$((...))`, `<(...)`, or `>(...)`. Resolve those values yourself before calling this tool, or ask the user for the literal value to use.///+/// Do not pipe output to `head`, `tail`, or similar output-filtering commands just to reduce what you receive. Instead, use `head_lines` and/or `tail_lines`; this keeps the terminal output visible to the user in real time while limiting only the final output sent back to you. When both are specified, the first `head_lines` lines are returned, then a blank line, then the last `tail_lines` lines. Avoid requesting too many lines, or the response may waste tokens or exceed the context window.+////// Do not use this tool for commands that run indefinitely, such as servers (like `npm run start`, `npm run dev`, `python -m http.server`, etc) or file watchers that don't terminate on their own.////// For potentially long-running commands, prefer specifying `timeout_ms` to bound runtime and prevent indefinite hangs.@@ -50,6 +52,12 @@ pub struct TerminalToolInput {pub cd: String,/// Optional maximum runtime (in milliseconds). If exceeded, the running terminal task is killed.pub timeout_ms: Option<u64>,+ /// Return only the first N lines of terminal output to the model after the command finishes. Do not pipe output to `head`; use this parameter instead so the user can still see live output. Avoid requesting too many lines, or the response may waste tokens or exceed the context window.+ #[serde(default)]+ pub head_lines: Option<usize>,+ /// Return only the last N lines of terminal output to the model after the command finishes. Do not pipe output to `tail`; use this parameter instead so the user can still see live output. Avoid requesting too many lines, or the response may waste tokens or exceed the context window.+ #[serde(default)]+ pub tail_lines: Option<usize>,/// Request network access for this command.////// Only meaningful when the system prompt's "Terminal sandbox" section@@ -81,6 +89,83 @@ pub struct TerminalToolInput {pub unsandboxed: Option<bool>,}+/// Executes a shell one-liner and returns the combined output.+///+/// This tool spawns a process using the user's shell, reads from stdout and stderr (preserving the order of writes), and returns a string with the combined output result.+///+/// The output results will be shown to the user already, only list it again if necessary, avoid being redundant.+///+/// Make sure you use the `cd` parameter to navigate to one of the root directories of the project. NEVER do it as part of the `command` itself, otherwise it will error.+///+/// Do not generate terminal commands that use shell substitutions or interpolations such as `$VAR`, `${VAR}`, `$(...)`, backticks, `$((...))`, `<(...)`, or `>(...)`. Resolve those values yourself before calling this tool, or ask the user for the literal value to use.+///+/// Do not use this tool for commands that run indefinitely, such as servers (like `npm run start`, `npm run dev`, `python -m http.server`, etc) or file watchers that don't terminate on their own.+///+/// For potentially long-running commands, prefer specifying `timeout_ms` to bound runtime and prevent indefinite hangs.+///+/// Remember that each invocation of this tool will spawn a new shell process, so you can't rely on any state from previous invocations.+///+/// The terminal is an interactive pty, so any command that blocks waiting for input will hang the tool until it times out. To avoid this:+///+/// - Always insert `--no-pager` immediately after `git` for any read-only git command, including `git log`, `git diff`, `git show`, `git blame`, and `git stash show`. Example: `git --no-pager log -n 5` (NOT `git log -n 5`).+/// - Always prepend `GIT_EDITOR=true ` to any git command that may invoke an editor, including `git rebase`, `git commit`, `git merge`, and `git tag`. Example: `GIT_EDITOR=true git rebase origin/main` (NOT `git rebase origin/main`).+/// - For other commands that may open a pager or editor, set `PAGER=cat` and/or `EDITOR=true` similarly.+#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)]+pub struct TerminalToolInputWithoutTail {+ /// The one-liner command to execute. Do not include shell substitutions or interpolations such as `$VAR`, `${VAR}`, `$(...)`, backticks, `$((...))`, `<(...)`, or `>(...)`; resolve those values first or ask the user.+ ///+ /// REMINDER: read-only git commands (`git log`, `git diff`, `git show`, `git blame`) MUST include `--no-pager` (e.g. `git --no-pager log`). Git commands that may open an editor (`git rebase`, `git commit`, `git merge`, `git tag`) MUST be prefixed with `GIT_EDITOR=true ` (e.g. `GIT_EDITOR=true git rebase origin/main`). Otherwise the terminal will hang.+ pub command: String,+ /// Working directory for the command. This must be one of the root directories of the project.+ pub cd: String,+ /// Optional maximum runtime (in milliseconds). If exceeded, the running terminal task is killed.+ pub timeout_ms: Option<u64>,+ /// Request network access for this command.+ ///+ /// Only meaningful when the system prompt's "Terminal sandbox" section+ /// is present — ignored otherwise. By default sandboxed commands+ /// cannot make outbound network connections; set this to `true` only+ /// when the command needs network access. The user will be prompted+ /// to approve before the command runs.+ #[serde(default)]+ pub allow_network: Option<bool>,+ /// Request unrestricted filesystem-write access for this command.+ ///+ /// Only meaningful when the system prompt's "Terminal sandbox" section+ /// is present — ignored otherwise. By default sandboxed commands can+ /// only write to the project worktree directories and a per-command+ /// temporary directory; set this to `true` only when the command+ /// needs to write elsewhere. The user will be prompted to approve+ /// before the command runs.+ #[serde(default)]+ pub allow_fs_write: Option<bool>,+ /// Request to run this command outside the sandbox entirely.+ ///+ /// Only meaningful when the system prompt's "Terminal sandbox" section+ /// is present — ignored otherwise. Prefer `allow_network: true` or+ /// `allow_fs_write: true` when one of those is enough. Set this to+ /// `true` ONLY when the command needs behavior that the sandbox can't+ /// grant on a per-permission basis. The user will be prompted to+ /// approve before the command runs without sandbox restrictions.+ #[serde(default)]+ pub unsandboxed: Option<bool>,+}++impl From<TerminalToolInputWithoutTail> for TerminalToolInput {+ fn from(input: TerminalToolInputWithoutTail) -> Self {+ Self {+ command: input.command,+ cd: input.cd,+ timeout_ms: input.timeout_ms,+ head_lines: None,+ tail_lines: None,+ allow_network: input.allow_network,+ allow_fs_write: input.allow_fs_write,+ unsandboxed: input.unsandboxed,+ }+ }+}+pub struct TerminalTool {project: Entity<Project>,environment: Rc<dyn ThreadEnvironment>,@@ -95,6 +180,20 @@ impl TerminalTool {}}+pub struct TerminalToolWithoutTail {+ project: Entity<Project>,+ environment: Rc<dyn ThreadEnvironment>,+}++impl TerminalToolWithoutTail {+ pub fn new(project: Entity<Project>, environment: Rc<dyn ThreadEnvironment>) -> Self {+ Self {+ project,+ environment,+ }+ }+}+impl AgentTool for TerminalTool {type Input = TerminalToolInput;type Output = String;@@ -110,11 +209,45 @@ impl AgentTool for TerminalTool {input: Result<Self::Input, serde_json::Value>,_cx: &mut App,) -> SharedString {- if let Ok(input) = input {- input.command.into()- } else {- "".into()- }+ terminal_initial_title(input.map(|input| input.command))+ }++ fn run(+ self: Arc<Self>,+ input: ToolInput<Self::Input>,+ event_stream: ToolCallEventStream,+ cx: &mut App,+ ) -> Task<Result<Self::Output, Self::Output>> {+ cx.spawn(async move |cx| {+ let input = input.recv().await.map_err(|e| e.to_string())?;+ run_terminal_tool(+ self.project.clone(),+ self.environment.clone(),+ input,+ event_stream,+ cx,+ )+ .await+ })+ }+}++impl AgentTool for TerminalToolWithoutTail {+ type Input = TerminalToolInputWithoutTail;+ type Output = String;++ const NAME: &'static str = "terminal";++ fn kind() -> acp::ToolKind {+ acp::ToolKind::Execute+ }++ fn initial_title(+ &self,+ input: Result<Self::Input, serde_json::Value>,+ _cx: &mut App,+ ) -> SharedString {+ terminal_initial_title(input.map(|input| input.command))}fn run(@@ -125,167 +258,166 @@ impl AgentTool for TerminalTool {) -> Task<Result<Self::Output, Self::Output>> {cx.spawn(async move |cx| {let input = input.recv().await.map_err(|e| e.to_string())?;+ run_terminal_tool(+ self.project.clone(),+ self.environment.clone(),+ input.into(),+ event_stream,+ cx,+ )+ .await+ })+ }+}- let (working_dir, authorize, sandboxing) = cx.update(|cx| {- let working_dir =- working_dir(&input, &self.project, cx).map_err(|err| err.to_string())?;- let context =- crate::ToolPermissionContext::new(Self::NAME, vec![input.command.clone()]);- let authorize =- event_stream.authorize(self.initial_title(Ok(input.clone()), cx), context, cx);- let sandboxing = sandboxing_enabled(cx);- Result::<_, String>::Ok((working_dir, authorize, sandboxing))- })?;-- authorize.await.map_err(|e| e.to_string())?;-- // Sandbox flags only do anything when sandboxing is on. When- // off, we treat them as `None` so the model can't surreptitiously- // change runtime behavior by setting flags described as a no-op- // in the system prompt.- let want_network = sandboxing && input.allow_network == Some(true);- let want_fs_write = sandboxing && input.allow_fs_write == Some(true);- let want_unsandboxed = sandboxing && input.unsandboxed == Some(true);-- // `unsandboxed: true` bypasses the wrap entirely; per-permission- // requests are only meaningful when the command is still being- // sandboxed.- let escalate = !want_unsandboxed && (want_network || want_fs_write);-- if want_unsandboxed || escalate {- let title = sandbox_approval_title(want_network, want_fs_write, want_unsandboxed);- let approve = cx.update(|cx| {- let context = crate::ToolPermissionContext::new(- Self::NAME,- vec![input.command.clone()],- );- // Sandbox escalations always prompt, even if the user- // has `always_allow` rules for this command — the- // escalation is a stronger trust boundary than the- // baseline command approval.- event_stream.authorize_always_prompt(title, context, cx)- });- if let Err(error) = approve.await {- return Ok(if want_unsandboxed {- format!(- "Command cancelled: user denied permission to run outside the sandbox ({error})."- )- } else {- format!(- "Command cancelled: user denied the requested sandbox permissions ({error})."- )- });- }- }+fn terminal_initial_title(input: Result<String, serde_json::Value>) -> SharedString {+ if let Ok(command) = input {+ command.into()+ } else {+ "".into()+ }+}- // The per-thread scratch directory (and the `$TMPDIR`/`TMP`/- // `TEMP` environment variables pointing at it) is provisioned by- // the thread environment in `create_terminal`, which also adds it- // to the sandbox's writable scope. We must not set `$TMPDIR` here:- // the environment overrides it with the per-thread directory, so a- // per-command directory set here would never be the `$TMPDIR` the- // command actually sees and would be left out of the writable- // scope, breaking writes into `$TMPDIR`.- let extra_env = Vec::new();-- // Build the writable scope from the project's worktrees. The- // per-thread temp directory is appended by the thread environment- // (which owns it and points `$TMPDIR` at it). Crucially we do- // *not* include the resolved `cd` working directory — that's- // model-controlled, and using it as the writable scope would- // let the model widen its own write permissions outside the- // project.- let sandbox_wrap = if sandboxing && !want_unsandboxed {- let writable_paths: Vec<PathBuf> = cx.update(|cx| {- self.project- .read(cx)- .worktrees(cx)- .map(|w| w.read(cx).abs_path().to_path_buf())- .collect::<Vec<_>>()- });- Some(acp_thread::SandboxWrap {- writable_paths,- allow_network: want_network,- allow_fs_write: want_fs_write,- })- } else {- None- };+async fn run_terminal_tool(+ project: Entity<Project>,+ environment: Rc<dyn ThreadEnvironment>,+ input: TerminalToolInput,+ event_stream: ToolCallEventStream,+ cx: &mut AsyncApp,+) -> Result<String, String> {+ let selection = TerminalOutputSelection {+ head_lines: input.head_lines,+ tail_lines: input.tail_lines,+ };- let terminal = self- .environment- .create_terminal(- input.command.clone(),- extra_env,- working_dir,- Some(COMMAND_OUTPUT_LIMIT),- sandbox_wrap,- cx,+ let (working_dir, authorize, sandboxing) = cx.update(|cx| {+ let working_dir = working_dir(&input, &project, cx).map_err(|err| err.to_string())?;+ let context =+ crate::ToolPermissionContext::new(TerminalTool::NAME, vec![input.command.clone()]);+ let authorize =+ event_stream.authorize(SharedString::new(input.command.clone()), context, cx);+ let sandboxing = sandboxing_enabled(cx);+ Result::<_, String>::Ok((working_dir, authorize, sandboxing))+ })?;++ authorize.await.map_err(|e| e.to_string())?;++ let want_network = sandboxing && input.allow_network == Some(true);+ let want_fs_write = sandboxing && input.allow_fs_write == Some(true);+ let want_unsandboxed = sandboxing && input.unsandboxed == Some(true);+ let escalate = !want_unsandboxed && (want_network || want_fs_write);++ if want_unsandboxed || escalate {+ let title = sandbox_approval_title(want_network, want_fs_write, want_unsandboxed);+ let approve = cx.update(|cx| {+ let context =+ crate::ToolPermissionContext::new(TerminalTool::NAME, vec![input.command.clone()]);+ event_stream.authorize_always_prompt(title, context, cx)+ });+ if let Err(error) = approve.await {+ return Ok(if want_unsandboxed {+ format!(+ "Command cancelled: user denied permission to run outside the sandbox ({error})."+ )+ } else {+ format!(+ "Command cancelled: user denied the requested sandbox permissions ({error}).")- .await- .map_err(|e| e.to_string())?;-- let terminal_id = terminal.id(cx).map_err(|e| e.to_string())?;- event_stream.update_fields(acp::ToolCallUpdateFields::new().content(vec![- acp::ToolCallContent::Terminal(acp::Terminal::new(terminal_id)),- ]));-- let timeout = input.timeout_ms.map(Duration::from_millis);-- let mut timed_out = false;- let mut user_stopped_via_signal = false;- let wait_for_exit = terminal.wait_for_exit(cx).map_err(|e| e.to_string())?;-- match timeout {- Some(timeout) => {- let timeout_task = cx.background_executor().timer(timeout);-- futures::select! {- _ = wait_for_exit.clone().fuse() => {},- _ = timeout_task.fuse() => {- timed_out = true;- terminal.kill(cx).map_err(|e| e.to_string())?;- wait_for_exit.await;- }- _ = event_stream.cancelled_by_user().fuse() => {- user_stopped_via_signal = true;- terminal.kill(cx).map_err(|e| e.to_string())?;- wait_for_exit.await;- }- }+ });+ }+ }++ let extra_env = Vec::new();++ let sandbox_wrap = if sandboxing && !want_unsandboxed {+ let writable_paths: Vec<PathBuf> = cx.update(|cx| {+ project+ .read(cx)+ .worktrees(cx)+ .map(|w| w.read(cx).abs_path().to_path_buf())+ .collect::<Vec<_>>()+ });+ Some(acp_thread::SandboxWrap {+ writable_paths,+ allow_network: want_network,+ allow_fs_write: want_fs_write,+ })+ } else {+ None+ };++ let output_byte_limit = if selection.is_enabled() {+ None+ } else {+ Some(COMMAND_OUTPUT_LIMIT)+ };++ let terminal = environment+ .create_terminal(+ input.command.clone(),+ extra_env,+ working_dir,+ output_byte_limit,+ sandbox_wrap,+ cx,+ )+ .await+ .map_err(|e| e.to_string())?;++ let terminal_id = terminal.id(cx).map_err(|e| e.to_string())?;+ event_stream.update_fields(acp::ToolCallUpdateFields::new().content(vec![+ acp::ToolCallContent::Terminal(acp::Terminal::new(terminal_id)),+ ]));++ let timeout = input.timeout_ms.map(Duration::from_millis);++ let mut timed_out = false;+ let mut user_stopped_via_signal = false;+ let wait_for_exit = terminal.wait_for_exit(cx).map_err(|e| e.to_string())?;++ match timeout {+ Some(timeout) => {+ let timeout_task = cx.background_executor().timer(timeout);++ futures::select! {+ _ = wait_for_exit.clone().fuse() => {},+ _ = timeout_task.fuse() => {+ timed_out = true;+ terminal.kill(cx).map_err(|e| e.to_string())?;+ wait_for_exit.await;}- None => {- futures::select! {- _ = wait_for_exit.clone().fuse() => {},- _ = event_stream.cancelled_by_user().fuse() => {- user_stopped_via_signal = true;- terminal.kill(cx).map_err(|e| e.to_string())?;- wait_for_exit.await;- }- }+ _ = event_stream.cancelled_by_user().fuse() => {+ user_stopped_via_signal = true;+ terminal.kill(cx).map_err(|e| e.to_string())?;+ wait_for_exit.await;}- };+ }+ }+ None => {+ futures::select! {+ _ = wait_for_exit.clone().fuse() => {},+ _ = event_stream.cancelled_by_user().fuse() => {+ user_stopped_via_signal = true;+ terminal.kill(cx).map_err(|e| e.to_string())?;+ wait_for_exit.await;+ }+ }+ }+ };- // Check if user stopped - we check both:- // 1. The cancellation signal from RunningTurn::cancel (e.g. user pressed main Stop button)- // 2. The terminal's user_stopped flag (e.g. user clicked Stop on the terminal card)- // Note: user_stopped_via_signal is already set above if we detected cancellation in the select!- // but we also check was_cancelled_by_user() for cases where cancellation happened after wait_for_exit completed- let user_stopped_via_signal =- user_stopped_via_signal || event_stream.was_cancelled_by_user();- let user_stopped_via_terminal = terminal.was_stopped_by_user(cx).unwrap_or(false);- let user_stopped = user_stopped_via_signal || user_stopped_via_terminal;+ let user_stopped_via_signal = user_stopped_via_signal || event_stream.was_cancelled_by_user();+ let user_stopped_via_terminal = terminal.was_stopped_by_user(cx).unwrap_or(false);+ let user_stopped = user_stopped_via_signal || user_stopped_via_terminal;- let output = terminal.current_output(cx).map_err(|e| e.to_string())?;+ let output = terminal.current_output(cx).map_err(|e| e.to_string())?;- Ok(process_content(- output,- &input.command,- timed_out,- user_stopped,- ))- })- }+ Ok(process_content(+ output,+ &input.command,+ timed_out,+ user_stopped,+ selection,+ ))}/// User-facing title for the sandbox-escalation approval prompt.@@ -311,13 +443,55 @@ fn sandbox_approval_title(}}+#[derive(Clone, Copy, Debug, Default)]+struct TerminalOutputSelection {+ head_lines: Option<usize>,+ tail_lines: Option<usize>,+}++impl TerminalOutputSelection {+ fn is_enabled(self) -> bool {+ self.head_lines.is_some() || self.tail_lines.is_some()+ }+}++fn select_terminal_output_lines(output: &str, selection: TerminalOutputSelection) -> String {+ match (selection.head_lines, selection.tail_lines) {+ (None, None) => output.to_string(),+ (Some(head_lines), None) => output+ .lines()+ .take(head_lines)+ .collect::<Vec<_>>()+ .join("\n"),+ (None, Some(tail_lines)) => {+ let lines = output.lines().collect::<Vec<_>>();+ let start = lines.len().saturating_sub(tail_lines);+ lines[start..].join("\n")+ }+ (Some(head_lines), Some(tail_lines)) => {+ let lines = output.lines().collect::<Vec<_>>();+ let head = lines+ .iter()+ .take(head_lines)+ .copied()+ .collect::<Vec<_>>()+ .join("\n");+ let tail_start = lines.len().saturating_sub(tail_lines);+ let tail = lines[tail_start..].join("\n");+ format!("{head}\n\n{tail}")+ }+ }+}+fn process_content(output: acp::TerminalOutputResponse,command: &str,timed_out: bool,user_stopped: bool,+ selection: TerminalOutputSelection,) -> String {let content = output.output.trim();+ let content = select_terminal_output_lines(content, selection);let is_empty = content.is_empty();let content = format!("```\n{content}\n```");@@ -466,7 +640,13 @@ mod tests {fn test_process_content_user_stopped() {let output = acp::TerminalOutputResponse::new("partial output".to_string(), false);- let result = process_content(output, "cargo build", false, true);+ let result = process_content(+ output,+ "cargo build",+ false,+ true,+ TerminalOutputSelection::default(),+ );assert!(result.contains("user stopped"),@@ -586,11 +766,228 @@ mod tests {}}+ #[test]+ fn test_select_terminal_output_head_lines() {+ let output = "one\ntwo\nthree\nfour";+ let result = select_terminal_output_lines(+ output,+ TerminalOutputSelection {+ head_lines: Some(2),+ tail_lines: None,+ },+ );++ assert_eq!(result, "one\ntwo");+ }++ #[test]+ fn test_select_terminal_output_tail_lines() {+ let output = "one\ntwo\nthree\nfour";+ let result = select_terminal_output_lines(+ output,+ TerminalOutputSelection {+ head_lines: None,+ tail_lines: Some(2),+ },+ );++ assert_eq!(result, "three\nfour");+ }++ #[test]+ fn test_select_terminal_output_head_and_tail_lines() {+ let output = "one\ntwo\nthree\nfour\nfive";+ let result = select_terminal_output_lines(+ output,+ TerminalOutputSelection {+ head_lines: Some(2),+ tail_lines: Some(2),+ },+ );++ assert_eq!(result, "one\ntwo\n\nfour\nfive");+ }++ #[test]+ fn test_select_terminal_output_head_and_tail_lines_overlap() {+ let output = "one\ntwo\nthree";+ let result = select_terminal_output_lines(+ output,+ TerminalOutputSelection {+ head_lines: Some(2),+ tail_lines: Some(2),+ },+ );++ assert_eq!(result, "one\ntwo\n\ntwo\nthree");+ }++ #[test]+ fn test_select_terminal_output_allows_zero_lines() {+ let output = "one\ntwo\nthree";++ assert_eq!(+ select_terminal_output_lines(+ output,+ TerminalOutputSelection {+ head_lines: Some(0),+ tail_lines: None,+ },+ ),+ ""+ );+ assert_eq!(+ select_terminal_output_lines(+ output,+ TerminalOutputSelection {+ head_lines: None,+ tail_lines: Some(0),+ },+ ),+ ""+ );+ assert_eq!(+ select_terminal_output_lines(+ output,+ TerminalOutputSelection {+ head_lines: Some(0),+ tail_lines: Some(0),+ },+ ),+ "\n\n"+ );+ }++ #[test]+ fn test_select_terminal_output_handles_unicode_without_trailing_newline() {+ let output = "α\nβ\nγ";+ let result = select_terminal_output_lines(+ output,+ TerminalOutputSelection {+ head_lines: None,+ tail_lines: Some(2),+ },+ );++ assert_eq!(result, "β\nγ");+ }++ #[test]+ fn test_process_content_filters_success_output_for_model() {+ let output = acp::TerminalOutputResponse::new("one\ntwo\nthree\nfour".to_string(), false)+ .exit_status(acp::TerminalExitStatus::new().exit_code(0));++ let result = process_content(+ output,+ "printf lines",+ false,+ false,+ TerminalOutputSelection {+ head_lines: Some(1),+ tail_lines: Some(1),+ },+ );++ assert_eq!(result, "```\none\n\nfour\n```");+ }++ #[test]+ fn test_process_content_filters_failure_output_for_model() {+ let output = acp::TerminalOutputResponse::new("one\ntwo\nthree".to_string(), false)+ .exit_status(acp::TerminalExitStatus::new().exit_code(1));++ let result = process_content(+ output,+ "failing command",+ false,+ false,+ TerminalOutputSelection {+ head_lines: None,+ tail_lines: Some(1),+ },+ );++ assert!(result.contains("failed with exit code 1"));+ assert!(result.contains("three"));+ assert!(!result.contains("one"));+ assert!(!result.contains("two"));+ }++ #[test]+ fn test_process_content_filters_timeout_output_for_model() {+ let output = acp::TerminalOutputResponse::new("one\ntwo\nthree".to_string(), false);++ let result = process_content(+ output,+ "slow command",+ true,+ false,+ TerminalOutputSelection {+ head_lines: Some(1),+ tail_lines: None,+ },+ );++ assert!(result.contains("timed out"));+ assert!(result.contains("one"));+ assert!(!result.contains("two"));+ assert!(!result.contains("three"));+ }++ #[test]+ fn test_process_content_filters_user_stopped_output_for_model() {+ let output = acp::TerminalOutputResponse::new("one\ntwo\nthree".to_string(), false);++ let result = process_content(+ output,+ "stopped command",+ false,+ true,+ TerminalOutputSelection {+ head_lines: None,+ tail_lines: Some(1),+ },+ );++ assert!(result.contains("user stopped"));+ assert!(result.contains("ask them what they would like to do"));+ assert!(result.contains("three"));+ assert!(!result.contains("one"));+ assert!(!result.contains("two"));+ }++ #[test]+ fn test_process_content_selected_output_has_no_explanatory_note() {+ let output = acp::TerminalOutputResponse::new("one\ntwo\nthree".to_string(), false)+ .exit_status(acp::TerminalExitStatus::new().exit_code(0));++ let result = process_content(+ output,+ "printf lines",+ false,+ false,+ TerminalOutputSelection {+ head_lines: Some(1),+ tail_lines: Some(1),+ },+ );++ assert!(!result.contains("Showing"));+ assert!(!result.contains("first"));+ assert!(!result.contains("last"));+ }+#[test]fn test_process_content_user_stopped_empty_output() {let output = acp::TerminalOutputResponse::new("".to_string(), false);- let result = process_content(output, "cargo build", false, true);+ let result = process_content(+ output,+ "cargo build",+ false,+ true,+ TerminalOutputSelection::default(),+ );assert!(result.contains("user stopped"),@@ -608,7 +1005,13 @@ mod tests {fn test_process_content_timed_out() {let output = acp::TerminalOutputResponse::new("build output here".to_string(), false);- let result = process_content(output, "cargo build", true, false);+ let result = process_content(+ output,+ "cargo build",+ true,+ false,+ TerminalOutputSelection::default(),+ );assert!(result.contains("timed out"),@@ -626,7 +1029,13 @@ mod tests {fn test_process_content_timed_out_with_empty_output() {let output = acp::TerminalOutputResponse::new("".to_string(), false);- let result = process_content(output, "sleep 1000", true, false);+ let result = process_content(+ output,+ "sleep 1000",+ true,+ false,+ TerminalOutputSelection::default(),+ );assert!(result.contains("timed out"),@@ -645,7 +1054,13 @@ mod tests {let output = acp::TerminalOutputResponse::new("success output".to_string(), false).exit_status(acp::TerminalExitStatus::new().exit_code(0));- let result = process_content(output, "echo hello", false, false);+ let result = process_content(+ output,+ "echo hello",+ false,+ false,+ TerminalOutputSelection::default(),+ );assert!(result.contains("success output"),@@ -664,7 +1079,13 @@ mod tests {let output = acp::TerminalOutputResponse::new("".to_string(), false).exit_status(acp::TerminalExitStatus::new().exit_code(0));- let result = process_content(output, "true", false, false);+ let result = process_content(+ output,+ "true",+ false,+ false,+ TerminalOutputSelection::default(),+ );assert!(result.contains("executed successfully"),@@ -678,7 +1099,13 @@ mod tests {let output = acp::TerminalOutputResponse::new("error output".to_string(), false).exit_status(acp::TerminalExitStatus::new().exit_code(1));- let result = process_content(output, "false", false, false);+ let result = process_content(+ output,+ "false",+ false,+ false,+ TerminalOutputSelection::default(),+ );assert!(result.contains("failed with exit code 1"),@@ -697,7 +1124,13 @@ mod tests {let output = acp::TerminalOutputResponse::new("".to_string(), false).exit_status(acp::TerminalExitStatus::new().exit_code(1));- let result = process_content(output, "false", false, false);+ let result = process_content(+ output,+ "false",+ false,+ false,+ TerminalOutputSelection::default(),+ );assert!(result.contains("failed with exit code 1"),@@ -710,7 +1143,13 @@ mod tests {fn test_process_content_unexpected_termination() {let output = acp::TerminalOutputResponse::new("some output".to_string(), false);- let result = process_content(output, "some_command", false, false);+ let result = process_content(+ output,+ "some_command",+ false,+ false,+ TerminalOutputSelection::default(),+ );assert!(result.contains("terminated unexpectedly"),@@ -728,7 +1167,13 @@ mod tests {fn test_process_content_unexpected_termination_empty_output() {let output = acp::TerminalOutputResponse::new("".to_string(), false);- let result = process_content(output, "some_command", false, false);+ let result = process_content(+ output,+ "some_command",+ false,+ false,+ TerminalOutputSelection::default(),+ );assert!(result.contains("terminated unexpectedly"),@@ -1004,6 +1449,119 @@ mod tests {);}+ #[gpui::test]+ async fn test_run_filters_model_output_and_bypasses_byte_limit_when_head_or_tail_is_set(+ cx: &mut gpui::TestAppContext,+ ) {+ crate::tests::init_test(cx);++ let fs = fs::FakeFs::new(cx.executor());+ fs.insert_tree("/root", serde_json::json!({})).await;+ let project = project::Project::test(fs, ["/root".as_ref()], cx).await;++ let output =+ acp::TerminalOutputResponse::new("one\ntwo\nthree\nfour\nfive".to_string(), false)+ .exit_status(acp::TerminalExitStatus::new().exit_code(0));+ let environment = std::rc::Rc::new(cx.update(|cx| {+ crate::tests::FakeThreadEnvironment::default().with_terminal(+ crate::tests::FakeTerminalHandle::new_with_immediate_exit(cx, 0)+ .with_output(output),+ )+ }));++ cx.update(|cx| {+ let mut settings = agent_settings::AgentSettings::get_global(cx).clone();+ settings.tool_permissions.default = settings::ToolPermissionMode::Allow;+ settings.tool_permissions.tools.remove(TerminalTool::NAME);+ agent_settings::AgentSettings::override_global(settings, cx);+ });++ #[allow(clippy::arc_with_non_send_sync)]+ let tool = std::sync::Arc::new(TerminalTool::new(project, environment.clone()));+ let (event_stream, mut rx) = crate::ToolCallEventStream::test();++ let task = cx.update(|cx| {+ tool.run(+ crate::ToolInput::resolved(TerminalToolInput {+ command: "printf lines".to_string(),+ cd: "root".to_string(),+ timeout_ms: None,+ head_lines: Some(1),+ tail_lines: Some(1),+ ..Default::default()+ }),+ event_stream,+ cx,+ )+ });++ let update = rx.expect_update_fields().await;+ assert!(+ update.content.iter().any(|blocks| {+ blocks+ .iter()+ .any(|content| matches!(content, acp::ToolCallContent::Terminal(_)))+ }),+ "expected terminal content update"+ );++ let result = task.await.expect("terminal command should succeed");+ assert_eq!(result, "```\none\n\nfive\n```");+ assert_eq!(environment.terminal_output_limits(), vec![None]);+ }++ #[gpui::test]+ async fn test_run_uses_byte_limit_when_head_and_tail_are_not_set(+ cx: &mut gpui::TestAppContext,+ ) {+ crate::tests::init_test(cx);++ let fs = fs::FakeFs::new(cx.executor());+ fs.insert_tree("/root", serde_json::json!({})).await;+ let project = project::Project::test(fs, ["/root".as_ref()], cx).await;++ let output = acp::TerminalOutputResponse::new("command output".to_string(), false)+ .exit_status(acp::TerminalExitStatus::new().exit_code(0));+ let environment = std::rc::Rc::new(cx.update(|cx| {+ crate::tests::FakeThreadEnvironment::default().with_terminal(+ crate::tests::FakeTerminalHandle::new_with_immediate_exit(cx, 0)+ .with_output(output),+ )+ }));++ cx.update(|cx| {+ let mut settings = agent_settings::AgentSettings::get_global(cx).clone();+ settings.tool_permissions.default = settings::ToolPermissionMode::Allow;+ settings.tool_permissions.tools.remove(TerminalTool::NAME);+ agent_settings::AgentSettings::override_global(settings, cx);+ });++ #[allow(clippy::arc_with_non_send_sync)]+ let tool = std::sync::Arc::new(TerminalTool::new(project, environment.clone()));+ let (event_stream, mut rx) = crate::ToolCallEventStream::test();++ let task = cx.update(|cx| {+ tool.run(+ crate::ToolInput::resolved(TerminalToolInput {+ command: "echo output".to_string(),+ cd: "root".to_string(),+ timeout_ms: None,+ ..Default::default()+ }),+ event_stream,+ cx,+ )+ });++ rx.expect_update_fields().await;+ let result = task.await.expect("terminal command should succeed");+ assert_eq!(result, "```\ncommand output\n```");+ assert_eq!(+ environment.terminal_output_limits(),+ vec![Some(COMMAND_OUTPUT_LIMIT)]+ );+ }+#[gpui::test]async fn test_run_old_anchored_git_pattern_no_longer_auto_allows_env_prefix(cx: &mut gpui::TestAppContext,@@ -1126,6 +1684,47 @@ mod tests {);}+ #[test]+ fn test_terminal_tool_description_mentions_head_and_tail_parameters() {+ let description = <TerminalTool as crate::AgentTool>::description().to_string();++ assert!(description.contains("head_lines"));+ assert!(description.contains("tail_lines"));+ assert!(description.contains("Do not pipe output to `head`, `tail`, or similar"));+ assert!(description.contains("visible to the user in real time"));+ assert!(description.contains("waste tokens or exceed the context window"));+ }++ #[test]+ fn test_terminal_tool_input_schema_mentions_head_and_tail_parameters() {+ let schema = <TerminalTool as crate::AgentTool>::input_schema(+ language_model::LanguageModelToolSchemaFormat::JsonSchema,+ );+ let schema_json = serde_json::to_value(schema).expect("schema should serialize");+ let schema_text = schema_json.to_string();++ assert!(schema_text.contains("head_lines"));+ assert!(schema_text.contains("tail_lines"));+ assert!(schema_text.contains("Do not pipe output to `head`"));+ assert!(schema_text.contains("Do not pipe output to `tail`"));+ assert!(schema_text.contains("waste tokens or exceed the context window"));+ }++ #[test]+ fn test_terminal_tool_without_tail_schema_omits_head_and_tail_parameters() {+ let description = <TerminalToolWithoutTail as crate::AgentTool>::description().to_string();+ let schema = <TerminalToolWithoutTail as crate::AgentTool>::input_schema(+ language_model::LanguageModelToolSchemaFormat::JsonSchema,+ );+ let schema_json = serde_json::to_value(schema).expect("schema should serialize");+ let schema_text = schema_json.to_string();++ assert!(!description.contains("head_lines"));+ assert!(!description.contains("tail_lines"));+ assert!(!schema_text.contains("head_lines"));+ assert!(!schema_text.contains("tail_lines"));+ }+async fn assert_rejected_before_terminal_creation(command: &str,cx: &mut gpui::TestAppContext,diff --git a/crates/feature_flags/src/flags.rs b/crates/feature_flags/src/flags.rsindex f6febdc5c4e..4936c66ac14 100644--- a/crates/feature_flags/src/flags.rs+++ b/crates/feature_flags/src/flags.rs@@ -162,3 +162,15 @@ impl FeatureFlag for SandboxingFeatureFlag {}}register_feature_flag!(SandboxingFeatureFlag);++pub struct TerminalTailFeatureFlag;++impl FeatureFlag for TerminalTailFeatureFlag {+ const NAME: &'static str = "terminal-tail";+ type Value = PresenceFlag;++ fn enabled_for_staff() -> bool {+ false+ }+}+register_feature_flag!(TerminalTailFeatureFlag);