Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
acp_thread: Add authoritative terminal display updates (#64976)
Ben Brandtf2cdf3d5bd87
diff --git a/crates/acp_thread/src/acp_thread.rs b/crates/acp_thread/src/acp_thread.rsindex d5aa15ee6a6..832766aec72 100644--- a/crates/acp_thread/src/acp_thread.rs+++ b/crates/acp_thread/src/acp_thread.rs@@ -1357,6 +1357,7 @@ impl ToolCall {terminals: &HashMap<acp_v1::TerminalId, Entity<Terminal>>,cx: &mut App,) -> Result<()> {+ let legacy_terminal_labels = matches!(&patch.meta, ToolMetadataPatch::Legacy(_));let ToolCallPatch {kind,status,@@ -1438,7 +1439,8 @@ impl ToolCall {if !title.is_undefined() {self.title = title.take().map(SharedString::from);- if self.kind() == &acp_v2::ToolKind::Execute+ if legacy_terminal_labels+ && self.kind() == &acp_v2::ToolKind::Execute&& let Some(title) = self.effective_title(){// A missing tool title must not overwrite an actual terminal command.@@ -5178,6 +5180,16 @@ impl AcpThread {update: acp_v2::ToolCallUpdate,cx: &mut Context<Self>,) -> Result<()> {+ if let Some(content) = update.content.value() {+ for content in content {+ if let acp_v2::ToolCallContent::Terminal(terminal) = content {+ self.ensure_display_terminal(+ acp_v1::TerminalId::new(terminal.terminal_id.0.clone()),+ cx,+ );+ }+ }+ }let id = acp_v1::ToolCallId::new(update.tool_call_id.0.clone());let patch = ToolCallPatch::protocol(update);let locations_changed = !patch.locations.is_undefined();@@ -6753,6 +6765,94 @@ impl AcpThread {}}+ pub fn upsert_display_terminal(+ &mut self,+ terminal_id: acp_v2::TerminalId,+ patch: DisplayTerminalPatch,+ cx: &mut Context<Self>,+ ) -> Result<()> {+ let terminal = self.ensure_display_terminal(acp_v1::TerminalId::new(terminal_id.0), cx);+ terminal.update(cx, |terminal, cx| terminal.apply_display_patch(patch, cx))+ }++ pub fn append_display_terminal_output(+ &mut self,+ terminal_id: acp_v2::TerminalId,+ data: &[u8],+ cx: &mut Context<Self>,+ ) -> Result<()> {+ let terminal = self.ensure_display_terminal(acp_v1::TerminalId::new(terminal_id.0), cx);+ terminal.update(cx, |terminal, cx| terminal.append_display_bytes(data, cx))+ }++ fn ensure_display_terminal(+ &mut self,+ terminal_id: acp_v1::TerminalId,+ cx: &mut Context<Self>,+ ) -> Entity<Terminal> {+ if let Some(terminal) = self.terminals.get(&terminal_id) {+ return terminal.clone();+ }+ let builder = ::terminal::TerminalBuilder::new_display_only(+ ::terminal::terminal_settings::CursorShape::default(),+ ::terminal::terminal_settings::AlternateScroll::On,+ None,+ 0,+ cx.background_executor(),+ self.project.read(cx).path_style(cx),+ );+ let terminal = cx.new(|cx| builder.subscribe(cx));+ self.register_display_terminal(terminal_id, None, None, None, terminal, cx)+ }++ fn register_display_terminal(+ &mut self,+ terminal_id: acp_v1::TerminalId,+ command: Option<&str>,+ cwd: Option<PathBuf>,+ output_byte_limit: Option<u64>,+ terminal: Entity<::terminal::Terminal>,+ cx: &mut Context<Self>,+ ) -> Entity<Terminal> {+ let language_registry = self.project.read(cx).languages().clone();+ let entity = cx.new(|cx| {+ Terminal::new_display(+ terminal_id.clone(),+ command,+ cwd,+ output_byte_limit.map(|limit| limit as usize),+ terminal,+ language_registry,+ cx,+ )+ });+ // Provider state can change 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(chunks) = self.pending_terminal_output.remove(&terminal_id) {+ entity.update(cx, |terminal, cx| {+ for data in chunks {+ terminal.write_display_output(&data, cx);+ }+ });+ }+ if let Some(status) = self.pending_terminal_exit.remove(&terminal_id) {+ entity.update(cx, |terminal, cx| terminal.finish_display(status, cx));+ }+ entity+ }+pub fn on_terminal_provider_event(&mut self,event: TerminalProviderEvent,@@ -6766,47 +6866,29 @@ impl AcpThread {output_byte_limit,terminal,} => {- 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(),+ let entity = self+ .terminals+ .get(&terminal_id)+ .cloned()+ .unwrap_or_else(|| {+ self.register_display_terminal(+ terminal_id,+ Some(&label),+ cwd.clone(),+ output_byte_limit,+ terminal,+ cx,+ )+ });+ // A prior reference may already have a view; keep its renderer when metadata arrives.+ entity.update(cx, |terminal, cx| {+ terminal.initialize_legacy_display(&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.write_display_output(&data, cx);- });- }- }-- if let Some(status) = self.pending_terminal_exit.remove(&terminal_id) {- entity.update(cx, |term, cx| term.finish_display(status, cx));- }cx.notify();}@@ -8997,6 +9079,548 @@ mod tests {});}+ #[gpui::test]+ async fn test_v2_terminal_reference_and_output_share_display_identity(cx: &mut TestAppContext) {+ init_test(cx);+ for reference_first in [true, false] {+ let thread = new_test_thread(cx).await;+ let terminal_id = acp_v2::TerminalId::new("shared-terminal");+ let lookup_id = acp_v1::TerminalId::new("shared-terminal");+ let tool_id = acp_v1::ToolCallId::new("terminal-tool");+ let reference = acp_v2::ToolCallUpdate::new("terminal-tool")+ .title("Tool caption")+ .kind(acp_v2::ToolKind::Execute)+ .content(vec![acp_v2::ToolCallContent::Terminal(+ acp_v2::Terminal::new(terminal_id.clone()),+ )]);+ if reference_first {+ thread+ .update(cx, |thread, cx| {+ thread.upsert_tool_call_patch(reference.clone(), cx)+ })+ .expect("reference creates a placeholder");+ } else {+ thread+ .update(cx, |thread, cx| {+ thread.append_display_terminal_output(terminal_id.clone(), b"early\n", cx)+ })+ .expect("output creates a display terminal");+ }+ let terminal = thread.read_with(cx, |thread, _| {+ thread+ .terminal(lookup_id.clone())+ .expect("display terminal")+ });+ let lower = terminal.read_with(cx, |terminal, _| terminal.inner().clone());+ if reference_first {+ thread+ .update(cx, |thread, cx| {+ thread.append_display_terminal_output(terminal_id.clone(), b"early\n", cx)+ })+ .expect("append to placeholder");+ } else {+ thread+ .update(cx, |thread, cx| {+ thread.upsert_tool_call_patch(reference, cx)+ })+ .expect("reference existing display terminal");+ }+ thread+ .update(cx, |thread, cx| {+ thread.upsert_display_terminal(+ terminal_id.clone(),+ DisplayTerminalPatch {+ command: MaybeUndefined::Value("actual command".into()),+ ..Default::default()+ },+ cx,+ )+ })+ .expect("update display terminal");+ thread+ .update(cx, |thread, cx| {+ thread.upsert_tool_call_patch(+ acp_v2::ToolCallUpdate::new("terminal-tool").title("New caption"),+ cx,+ )+ })+ .expect("tool title is not the terminal command");+ thread.read_with(cx, |thread, cx| {+ let reused = thread.terminal(lookup_id).expect("same terminal");+ assert_eq!(reused.entity_id(), terminal.entity_id());+ assert_eq!(reused.read(cx).inner().entity_id(), lower.entity_id());+ assert_eq!(+ reused.read(cx).command().read(cx).source(),+ "```\nactual command\n```"+ );+ assert!(lower.read(cx).get_content().contains("early"));+ let (_, tool) = thread.tool_call(&tool_id).expect("tool");+ assert_eq!(tool.label.read(cx).source(), "New caption");+ assert_eq!(tool.terminals().next(), Some(&terminal));+ });+ thread+ .update(cx, |thread, cx| {+ thread.update_tool_call(+ acp_v1::ToolCallUpdate::new(+ tool_id.clone(),+ acp_v1::ToolCallUpdateFields::new().title("Legacy caption"),+ ),+ cx,+ )+ })+ .expect("legacy caption update");+ terminal.read_with(cx, |terminal, cx| {+ assert_eq!(+ terminal.command().read(cx).source(),+ "```\nactual command\n```"+ );+ });+ thread+ .update(cx, |thread, cx| {+ thread.upsert_display_terminal(+ terminal_id,+ DisplayTerminalPatch {+ command: MaybeUndefined::Null,+ ..Default::default()+ },+ cx,+ )?;+ thread.update_tool_call(+ acp_v1::ToolCallUpdate::new(+ tool_id,+ acp_v1::ToolCallUpdateFields::new().title("Another legacy caption"),+ ),+ cx,+ )+ })+ .expect("explicit command clear remains authoritative");+ terminal.read_with(cx, |terminal, cx| {+ assert_eq!(terminal.command().read(cx).source(), "```\nTerminal\n```");+ });+ thread+ .update(cx, |thread, cx| {+ for (id, content) in [+ (+ "another-tool",+ vec![acp_v2::ToolCallContent::Terminal(acp_v2::Terminal::new(+ "shared-terminal",+ ))],+ ),+ ("unrelated-tool", Vec::new()),+ ] {+ thread.upsert_tool_call_patch(+ acp_v2::ToolCallUpdate::new(id).content(content),+ cx,+ )?;+ }+ anyhow::Ok(())+ })+ .expect("shared and unrelated tool rows");+ cx.run_until_parked();+ let updated_entries = Rc::new(RefCell::new(Vec::new()));+ let _subscription = cx.update(|cx| {+ cx.subscribe(&thread, {+ let updated_entries = updated_entries.clone();+ move |_, event, _| {+ if let AcpThreadEvent::EntryUpdated(index) = event {+ updated_entries.borrow_mut().push(*index);+ }+ }+ })+ });+ thread+ .update(cx, |thread, cx| {+ thread.upsert_display_terminal(+ "shared-terminal".into(),+ DisplayTerminalPatch {+ meta: MaybeUndefined::Value(acp_v2::Meta::new()),+ ..Default::default()+ },+ cx,+ )+ })+ .expect("terminal metadata refresh");+ cx.run_until_parked();+ assert_eq!(&*updated_entries.borrow(), &[0, 1]);+ }+ }++ #[gpui::test]+ async fn test_terminal_placeholder_consumes_legacy_events_in_order(cx: &mut TestAppContext) {+ init_test(cx);+ let thread = new_test_thread(cx).await;+ thread.update(cx, |thread, cx| {+ let terminal_id = acp_v1::TerminalId::new("mixed");+ thread.on_terminal_provider_event(+ TerminalProviderEvent::Output {+ terminal_id: terminal_id.clone(),+ data: b"old\noutput".to_vec(),+ },+ cx,+ );+ thread.on_terminal_provider_event(+ TerminalProviderEvent::Exit {+ terminal_id: terminal_id.clone(),+ status: acp_v1::TerminalExitStatus::new().exit_code(7),+ },+ cx,+ );+ thread+ .upsert_tool_call_patch(+ acp_v2::ToolCallUpdate::new("tool").content(vec![+ acp_v2::ToolCallContent::Terminal(acp_v2::Terminal::new("mixed")),+ ]),+ cx,+ )+ .expect("reference consumes queued legacy output");+ let terminal = thread.terminal(terminal_id.clone()).expect("placeholder");+ let renderer = terminal.read(cx).inner().clone();+ assert!(renderer.read(cx).get_content().contains("old\noutput"));+ let ended_at = terminal.read(cx).output().expect("reported exit").ended_at;+ let meta = acp_v2::Meta::from_iter([("snapshot".into(), true.into())]);+ thread+ .upsert_display_terminal(+ "mixed".into(),+ DisplayTerminalPatch {+ command: MaybeUndefined::Value("reported command".into()),+ output: MaybeUndefined::Value(DisplayTerminalOutput {+ data: b"new output".to_vec(),+ meta: Some(meta.clone()),+ }),+ ..Default::default()+ },+ cx,+ )+ .expect("snapshot supersedes older bytes");+ let incoming_renderer = cx.new(|cx| {+ ::terminal::TerminalBuilder::new_display_only(+ Default::default(),+ ::terminal::terminal_settings::AlternateScroll::On,+ None,+ 0,+ cx.background_executor(),+ PathStyle::local(),+ )+ .subscribe(cx)+ });+ for (label, cwd, output_limit) in [+ ("legacy command", path!("/work"), 3),+ ("ignored duplicate", path!("/ignored"), 1),+ ] {+ thread.on_terminal_provider_event(+ TerminalProviderEvent::Created {+ terminal_id: terminal_id.clone(),+ label: label.into(),+ cwd: Some(PathBuf::from(cwd)),+ output_byte_limit: Some(output_limit),+ terminal: incoming_renderer.clone(),+ },+ cx,+ );+ }+ let reused = thread.terminal(terminal_id).expect("hydrated terminal");+ assert_eq!(reused, terminal);+ let terminal = reused.read(cx);+ assert_eq!(terminal.inner(), &renderer);+ assert_ne!(terminal.inner(), &incoming_renderer);+ assert_eq!(+ terminal.display_state().expect("display").command(),+ Some("reported command")+ );+ assert_eq!(+ terminal+ .display_state()+ .expect("display")+ .output_meta+ .as_ref(),+ Some(&meta)+ );+ assert_eq!(+ terminal.working_dir().as_deref(),+ Some(Path::new(path!("/work")))+ );+ let output = terminal.output().expect("completion preserved");+ assert_eq!(output.ended_at, ended_at);+ assert_eq!(output.exit_status.exit_code, Some(7));+ assert_eq!(output.content, "new");+ assert!(!renderer.read(cx).get_content().contains("old"));+ assert!(thread.pending_terminal_output.is_empty());+ assert!(thread.pending_terminal_exit.is_empty());+ thread+ .upsert_display_terminal(+ "mixed".into(),+ DisplayTerminalPatch {+ exit_status: MaybeUndefined::Null,+ ..Default::default()+ },+ cx,+ )+ .expect("clear completion");+ thread.on_terminal_provider_event(+ TerminalProviderEvent::Exit {+ terminal_id: acp_v1::TerminalId::new("mixed"),+ status: acp_v1::TerminalExitStatus::new().exit_code(0),+ },+ cx,+ );+ assert!(+ reused.read(cx).output().is_none(),+ "duplicate legacy exit must not restore completion"+ );+ });+ }++ #[gpui::test]+ async fn test_v2_terminal_patch_tristate_metadata_and_output_ordering(cx: &mut TestAppContext) {+ init_test(cx);+ let thread = new_test_thread(cx).await;+ let terminal_id = acp_v2::TerminalId::new("snapshot-terminal");+ let lookup_id = acp_v1::TerminalId::new("snapshot-terminal");+ let terminal_meta = acp_v2::Meta::from_iter([("terminal".into(), 1.into())]);+ let output_meta = acp_v2::Meta::from_iter([("output".into(), 2.into())]);+ let status_meta = acp_v2::Meta::from_iter([("exit".into(), 3.into())]);+ thread+ .update(cx, |thread, cx| {+ thread.upsert_display_terminal(+ terminal_id.clone(),+ DisplayTerminalPatch {+ command: MaybeUndefined::Value("first command".into()),+ cwd: MaybeUndefined::Value(acp_v2::AbsolutePath::new(PathBuf::from(+ path!("/work"),+ ))),+ meta: MaybeUndefined::Value(terminal_meta.clone()),+ output: MaybeUndefined::Value(DisplayTerminalOutput {+ data: b"old line\r\n".to_vec(),+ meta: Some(output_meta.clone()),+ }),+ exit_status: MaybeUndefined::Value(+ acp_v2::TerminalExitStatus::new()+ .exit_code(7)+ .meta(status_meta.clone()),+ ),+ },+ cx,+ )+ })+ .expect("initial snapshot");+ let terminal = thread.read_with(cx, |thread, _| {+ thread.terminal(lookup_id.clone()).expect("terminal")+ });+ let ended_at = terminal.read_with(cx, |terminal, _| {+ let state = terminal.display_state().expect("display");+ assert_eq!(state.meta.as_ref(), Some(&terminal_meta));+ assert_eq!(state.output_meta.as_ref(), Some(&output_meta));+ let output = terminal.output().expect("completed");+ assert_eq!(output.exit_status.exit_code, Some(7));+ assert_eq!(output.exit_status.meta.as_ref(), Some(&status_meta));+ output.ended_at+ });+ thread+ .update(cx, |thread, cx| {+ thread.upsert_display_terminal(+ terminal_id.clone(),+ DisplayTerminalPatch {+ output: MaybeUndefined::Value(DisplayTerminalOutput {+ data: b"new line\r\n".to_vec(),+ meta: None,+ }),+ ..Default::default()+ },+ cx,+ )?;+ thread.append_display_terminal_output(terminal_id.clone(), b"appended\r\n", cx)?;+ thread.upsert_display_terminal(+ terminal_id.clone(),+ DisplayTerminalPatch {+ exit_status: MaybeUndefined::Value(acp_v2::TerminalExitStatus::new()),+ ..Default::default()+ },+ cx,+ )+ })+ .expect("replacement, append, and exit correction");+ terminal.read_with(cx, |terminal, cx| {+ let state = terminal.display_state().expect("display state");+ assert_eq!(state.command(), Some("first command"));+ assert_eq!(+ terminal.working_dir().as_deref(),+ Some(Path::new(path!("/work")))+ );+ assert_eq!(state.meta.as_ref(), Some(&terminal_meta));+ assert_eq!(state.output_meta, None);+ let output = terminal.output().expect("completed");+ assert_eq!(output.ended_at, ended_at);+ assert_eq!(output.exit_status.exit_code, None);+ assert_eq!(output.exit_status.signal, None);+ assert_eq!(output.exit_status.meta, None);+ assert!(output.content.contains("new line\nappended"));+ assert!(!output.content.contains("old line"));+ assert_eq!(output.content, terminal.inner().read(cx).get_content());+ });+ thread+ .update(cx, |thread, cx| {+ thread.on_terminal_provider_event(+ TerminalProviderEvent::Exit {+ terminal_id: lookup_id.clone(),+ status: acp_v1::TerminalExitStatus::new().exit_code(5),+ },+ cx,+ );+ thread.upsert_display_terminal(+ terminal_id.clone(),+ DisplayTerminalPatch {+ output: MaybeUndefined::Null,+ exit_status: MaybeUndefined::Null,+ ..Default::default()+ },+ cx,+ )?;+ thread.on_terminal_provider_event(+ TerminalProviderEvent::Exit {+ terminal_id: lookup_id.clone(),+ status: acp_v1::TerminalExitStatus::new().exit_code(6),+ },+ cx,+ );+ anyhow::Ok(())+ })+ .expect("clear snapshot and completion");+ terminal.read_with(cx, |terminal, cx| {+ assert!(terminal.output().is_none());+ assert!(terminal.inner().read(cx).get_content().trim().is_empty());+ assert!(+ terminal+ .display_state()+ .expect("display")+ .output_meta+ .is_none()+ );+ assert_eq!(+ terminal.display_state().expect("display").meta.as_ref(),+ Some(&terminal_meta)+ );+ });+ thread+ .update(cx, |thread, cx| {+ thread.append_display_terminal_output(terminal_id.clone(), b"fresh\n", cx)?;+ thread.upsert_display_terminal(+ terminal_id.clone(),+ DisplayTerminalPatch::default(),+ cx,+ )+ })+ .expect("append and undefined patch");+ terminal.read_with(cx, |terminal, cx| {+ assert!(terminal.output().is_none());+ assert!(terminal.inner().read(cx).get_content().contains("fresh"));+ assert_eq!(+ terminal.command().read(cx).source(),+ "```\nfirst command\n```"+ );+ });+ thread+ .update(cx, |thread, cx| {+ thread.upsert_display_terminal(+ terminal_id,+ DisplayTerminalPatch {+ command: MaybeUndefined::Null,+ cwd: MaybeUndefined::Null,+ meta: MaybeUndefined::Null,+ ..Default::default()+ },+ cx,+ )+ })+ .expect("clear metadata without changing output");+ terminal.read_with(cx, |terminal, cx| {+ let state = terminal.display_state().expect("display");+ assert!(state.command().is_none());+ assert!(state.meta.is_none());+ assert!(terminal.working_dir().is_none());+ assert!(terminal.inner().read(cx).get_content().contains("fresh"));+ });+ thread.read_with(cx, |thread, _| {+ assert_eq!(+ thread.terminal(lookup_id).expect("terminal").entity_id(),+ terminal.entity_id()+ );+ });+ }++ #[gpui::test]+ async fn test_v2_terminal_updates_reject_client_owned_headless_terminal(+ cx: &mut TestAppContext,+ ) {+ init_test(cx);+ let thread = new_test_thread(cx).await;+ let terminal_id = acp_v1::TerminalId::new("native-terminal");+ let lower = cx.new(|cx| {+ ::terminal::TerminalBuilder::new_display_only(+ ::terminal::terminal_settings::CursorShape::default(),+ ::terminal::terminal_settings::AlternateScroll::On,+ None,+ 0,+ cx.background_executor(),+ PathStyle::local(),+ )+ .subscribe(cx)+ });+ let terminal = thread.update(cx, |thread, cx| {+ thread.register_terminal_created(+ terminal_id.clone(),+ "native command".into(),+ None,+ None,+ lower.clone(),+ cx,+ )+ });+ assert!(terminal.read_with(cx, |terminal, _| terminal.is_process_backed()));+ assert!(!lower.read_with(cx, |lower, _| lower.is_pty()));+ let before = lower.read_with(cx, |lower, _| lower.get_content());+ thread.update(cx, |thread, cx| {+ assert!(+ thread+ .upsert_display_terminal(+ acp_v2::TerminalId::new("native-terminal"),+ DisplayTerminalPatch {+ command: MaybeUndefined::Value("wrong command".into()),+ output: MaybeUndefined::Null,+ exit_status: MaybeUndefined::Value(acp_v2::TerminalExitStatus::new()),+ ..Default::default()+ },+ cx,+ )+ .is_err()+ );+ assert!(+ thread+ .append_display_terminal_output(+ acp_v2::TerminalId::new("native-terminal"),+ b"wrong output\n",+ cx+ )+ .is_err()+ );+ assert_eq!(+ thread+ .terminal(terminal_id)+ .expect("native terminal")+ .entity_id(),+ terminal.entity_id()+ );+ });+ terminal.read_with(cx, |terminal, cx| {+ assert!(terminal.display_state().is_none());+ assert_eq!(+ terminal.command().read(cx).source(),+ "```\nnative command\n```"+ );+ assert!(terminal.output().is_none());+ assert_eq!(lower.read(cx).get_content(), before);+ });+ }+#[gpui::test]async fn test_terminal_output_and_exit_buffered_before_created(cx: &mut gpui::TestAppContext) {init_test(cx);@@ -12233,13 +12857,13 @@ mod tests {serde_json::from_value(json!({"toolCallId": "permission","status": "cancelled",- "title": "must not replace valid presentation",+ "title": "Cancelled command","content": [{"type": "terminal", "terminalId": "missing"}]})).expect("cancelled patch"),cx,);- assert!(result.is_err());+ result.expect("a missing v2 terminal creates a placeholder");let (_, call) = thread.tool_call(&id).expect("tool");assert_eq!(call.reported_status,@@ -12248,7 +12872,8 @@ mod tests {assert_eq!(call.status(), ToolCallStatus::Canceled);assert!(call.authorization().is_none());assert_eq!(call.label, original_label);- assert_eq!(call.label.read(cx).source(), "Authorize");+ assert_eq!(call.label.read(cx).source(), "Cancelled command");+ assert!(call.terminals().next().is_some());});assert!(matches!(permission.await,@@ -18506,7 +19131,7 @@ mod tests {}#[gpui::test]- async fn test_failed_v2_terminal_patch_settles_only_its_permission(cx: &mut TestAppContext) {+ async fn test_v2_terminal_reference_settles_only_its_permission(cx: &mut TestAppContext) {init_test(cx);for status in [acp_v2::ToolCallStatus::Completed,@@ -18536,24 +19161,25 @@ mod tests {let first_index = thread.update(cx, |thread, cx| {let (index, first) = thread.tool_call(&first_id).expect("first tool");let original_label = first.label.clone();- assert!(- thread- .upsert_tool_call_patch(- acp_v2::ToolCallUpdate::new("first")- .status(status.clone())- .title("invalid replacement")- .content(vec![acp_v2::ToolCallContent::Terminal(- acp_v2::Terminal::new("missing")- )]),- cx,- )- .is_err()- );+ thread+ .upsert_tool_call_patch(+ acp_v2::ToolCallUpdate::new("first")+ .status(status.clone())+ .title("Terminal result")+ .content(vec![acp_v2::ToolCallContent::Terminal(+ acp_v2::Terminal::new("unseen"),+ )]),+ cx,+ )+ .expect("unseen terminal references create placeholders");let (_, first) = thread.tool_call(&first_id).expect("updated tool");assert_eq!(first.reported_status.as_ref(), Some(&status));assert!(first.authorization().is_none());assert_eq!(first.label, original_label);- assert_eq!(first.label.read(cx).source(), "Needs permission");+ assert_eq!(first.label.read(cx).source(), "Terminal result");+ let terminal = first.terminals().next().expect("terminal placeholder");+ assert_eq!(terminal.read(cx).id(), &acp_v1::TerminalId::new("unseen"));+ assert!(!terminal.read(cx).is_process_backed());assert!(thread.tool_call(&second_id)diff --git a/crates/acp_thread/src/terminal.rs b/crates/acp_thread/src/terminal.rsindex b8ef564ae2c..781b0f0cfde 100644--- a/crates/acp_thread/src/terminal.rs+++ b/crates/acp_thread/src/terminal.rs@@ -1,4 +1,4 @@-use agent_client_protocol::schema::v1 as acp;+use agent_client_protocol::schema::{MaybeUndefined, v1 as acp_v1, v2 as acp_v2};use anyhow::{Result, bail};use collections::HashMap;use futures::{FutureExt as _, future::Shared};@@ -400,7 +400,7 @@ pub(crate) async fn prepare_sandbox_wrap(}pub struct Terminal {- id: acp::TerminalId,+ id: acp_v1::TerminalId,command: Entity<Markdown>,working_dir: Option<PathBuf>,terminal: Entity<terminal::Terminal>,@@ -420,13 +420,57 @@ pub struct Terminal {}enum TerminalExecution {- Process(Shared<Task<acp::TerminalExitStatus>>),- Display,+ Process(Shared<Task<acp_v1::TerminalExitStatus>>),+ Display(DisplayTerminalState),+}++#[derive(Debug, Default)]+pub struct DisplayTerminalState {+ command: DisplayCommand,+ pub meta: Option<acp_v2::Meta>,+ pub output_meta: Option<acp_v2::Meta>,+ legacy_created: bool,+ legacy_exited: bool,+}++#[derive(Debug, Default)]+enum DisplayCommand {+ #[default]+ Unknown,+ LegacyCaption(String),+ Reported(Option<String>),+}++impl DisplayTerminalState {+ pub fn command(&self) -> Option<&str> {+ match &self.command {+ DisplayCommand::LegacyCaption(command) | DisplayCommand::Reported(Some(command)) => {+ Some(command)+ }+ DisplayCommand::Unknown | DisplayCommand::Reported(None) => None,+ }+ }+}++/// Terminal patches use decoded bytes; decoding and validating wire data belongs to the adapter.+#[derive(Debug, Default)]+pub struct DisplayTerminalPatch {+ pub command: MaybeUndefined<String>,+ pub cwd: MaybeUndefined<acp_v2::AbsolutePath>,+ pub output: MaybeUndefined<DisplayTerminalOutput>,+ pub exit_status: MaybeUndefined<acp_v2::TerminalExitStatus>,+ pub meta: MaybeUndefined<acp_v2::Meta>,+}++#[derive(Debug)]+pub struct DisplayTerminalOutput {+ pub data: Vec<u8>,+ pub meta: Option<acp_v2::Meta>,}pub struct TerminalOutput {pub ended_at: Instant,- pub exit_status: acp::TerminalExitStatus,+ pub exit_status: acp_v2::TerminalExitStatus,pub content: String,pub original_content_len: usize,pub content_line_count: usize,@@ -434,7 +478,7 @@ pub struct TerminalOutput {impl Terminal {pub fn new(- id: acp::TerminalId,+ id: acp_v1::TerminalId,command_label: &str,working_dir: Option<PathBuf>,output_byte_limit: Option<usize>,@@ -477,12 +521,16 @@ impl Terminal {execution: TerminalExecution::Process(cx.spawn(async move |this, cx| {let exit_status = command_task.await.map(Self::transform_exit_status);- let exit_status = acp::TerminalExitStatus::new()+ let exit_status = acp_v1::TerminalExitStatus::new().exit_code(exit_status.as_ref().map(|status| status.0)).signal(exit_status.and_then(|status| status.1));this.update(cx, |this, cx| {- this.cache_output(exit_status.clone(), Instant::now(), cx);+ this.cache_output(+ Self::exit_status_from_v1(exit_status.clone()),+ Instant::now(),+ cx,+ );this.terminal.update(cx, |terminal, _cx| {terminal.release_pty_resources();});@@ -507,8 +555,8 @@ impl Terminal {}pub fn new_display(- id: acp::TerminalId,- command_label: &str,+ id: acp_v1::TerminalId,+ command_label: Option<&str>,working_dir: Option<PathBuf>,output_byte_limit: Option<usize>,terminal: Entity<terminal::Terminal>,@@ -519,7 +567,7 @@ impl Terminal {id,command: cx.new(|cx| {Markdown::new(- format!("```\n{}\n```", command_label).into(),+ format!("```\n{}\n```", command_label.unwrap_or("Terminal")).into(),Some(language_registry),None,cx,@@ -530,13 +578,18 @@ impl Terminal {started_at: Instant::now(),output: None,output_byte_limit,- execution: TerminalExecution::Display,+ execution: TerminalExecution::Display(DisplayTerminalState {+ command: command_label+ .map(|command| DisplayCommand::LegacyCaption(command.to_owned()))+ .unwrap_or_default(),+ ..Default::default()+ }),user_stopped: Arc::new(AtomicBool::new(false)),_sandbox: None,}}- pub fn id(&self) -> &acp::TerminalId {+ pub fn id(&self) -> &acp_v1::TerminalId {&self.id}@@ -545,10 +598,10 @@ impl Terminal {matches!(self.execution, TerminalExecution::Process(_))}- pub fn wait_for_exit(&self) -> Result<Shared<Task<acp::TerminalExitStatus>>> {+ pub fn wait_for_exit(&self) -> Result<Shared<Task<acp_v1::TerminalExitStatus>>> {match &self.execution {TerminalExecution::Process(task) => Ok(task.clone()),- TerminalExecution::Display => {+ TerminalExecution::Display(_) => {bail!("Agent-provided terminals have no client-owned process to wait for")}}@@ -578,17 +631,22 @@ impl Terminal {self.user_stopped.load(Ordering::SeqCst)}- pub fn current_output(&self, cx: &App) -> acp::TerminalOutputResponse {+ pub fn current_output(&self, cx: &App) -> acp_v1::TerminalOutputResponse {if let Some(output) = self.output.as_ref() {- acp::TerminalOutputResponse::new(+ acp_v1::TerminalOutputResponse::new(output.content.clone(),output.original_content_len > output.content.len(),)- .exit_status(output.exit_status.clone())+ .exit_status(+ acp_v1::TerminalExitStatus::new()+ .exit_code(output.exit_status.exit_code)+ .signal(output.exit_status.signal.clone())+ .meta(output.exit_status.meta.clone()),+ )} else {let (current_content, original_len) = self.truncated_output(cx);let truncated = current_content.len() < original_len;- acp::TerminalOutputResponse::new(current_content, truncated)+ acp_v1::TerminalOutputResponse::new(current_content, truncated)}}@@ -598,6 +656,10 @@ impl Terminal {}self.terminal.update(cx, |terminal, cx| terminal.write_output(data, cx));+ self.refresh_output(cx);+ }++ fn refresh_output(&mut self, cx: &mut Context<Self>) {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.@@ -607,20 +669,148 @@ impl Terminal {pub(crate) fn finish_display(&mut self,- exit_status: acp::TerminalExitStatus,+ exit_status: acp_v1::TerminalExitStatus,cx: &mut Context<Self>,) {- if self.is_process_backed() || self.output.is_some() {+ let TerminalExecution::Display(state) = &mut self.execution else {+ return;+ };+ if std::mem::replace(&mut state.legacy_exited, true) || self.output.is_some() {return;}self.terminal.update(cx, |terminal, _| terminal.shrink_to_used());- self.cache_output(exit_status, Instant::now(), cx);+ self.cache_output(Self::exit_status_from_v1(exit_status), Instant::now(), cx);+ }++ fn exit_status_from_v1(status: acp_v1::TerminalExitStatus) -> acp_v2::TerminalExitStatus {+ acp_v2::TerminalExitStatus::new()+ .exit_code(status.exit_code)+ .signal(status.signal)+ .meta(status.meta)+ }++ pub fn display_state(&self) -> Option<&DisplayTerminalState> {+ match &self.execution {+ TerminalExecution::Display(state) => Some(state),+ TerminalExecution::Process(_) => None,+ }+ }++ pub(crate) fn initialize_legacy_display(+ &mut self,+ command: &str,+ cwd: Option<PathBuf>,+ output_byte_limit: Option<usize>,+ cx: &mut Context<Self>,+ ) {+ let TerminalExecution::Display(state) = &mut self.execution else {+ return;+ };+ if std::mem::replace(&mut state.legacy_created, true) {+ return;+ }+ self.update_command_label(command, cx);+ self.working_dir = cwd;+ if self.output_byte_limit != output_byte_limit {+ self.output_byte_limit = output_byte_limit;+ self.refresh_output(cx);+ }+ cx.notify();+ }++ pub(crate) fn append_display_bytes(+ &mut self,+ data: &[u8],+ cx: &mut Context<Self>,+ ) -> Result<()> {+ anyhow::ensure!(+ !self.is_process_backed(),+ "Cannot patch a client-owned terminal"+ );+ self.terminal+ .update(cx, |terminal, cx| terminal.write_raw_output(data, cx));+ self.refresh_output(cx);+ cx.notify();+ Ok(())+ }++ pub(crate) fn apply_display_patch(+ &mut self,+ patch: DisplayTerminalPatch,+ cx: &mut Context<Self>,+ ) -> Result<()> {+ anyhow::ensure!(+ !self.is_process_backed(),+ "Cannot patch a client-owned terminal"+ );+ let DisplayTerminalPatch {+ command,+ cwd,+ output,+ exit_status,+ meta,+ } = patch;+ let output_changed = !output.is_undefined();+ let output_meta = match output {+ MaybeUndefined::Undefined => None,+ MaybeUndefined::Null => {+ self.terminal+ .update(cx, |terminal, cx| terminal.replace_display_output(&[], cx))?;+ Some(None)+ }+ MaybeUndefined::Value(output) => {+ self.terminal.update(cx, |terminal, cx| {+ terminal.replace_display_output(&output.data, cx)+ })?;+ Some(output.meta)+ }+ };++ if let TerminalExecution::Display(state) = &mut self.execution {+ if !command.is_undefined() {+ state.command = DisplayCommand::Reported(command.take());+ self.command.update(cx, |markdown, cx| {+ markdown.replace(+ format!("```\n{}\n```", state.command().unwrap_or("Terminal")),+ cx,+ );+ });+ }+ if !meta.is_undefined() {+ state.meta = meta.take();+ }+ if let Some(meta) = output_meta {+ state.output_meta = meta;+ }+ }+ if !cwd.is_undefined() {+ self.working_dir = cwd.take().map(|path| path.0);+ }+ match exit_status {+ MaybeUndefined::Undefined => {+ if output_changed {+ self.refresh_output(cx);+ }+ }+ MaybeUndefined::Null => self.output = None,+ MaybeUndefined::Value(status) => {+ let ended_at = self+ .output+ .as_ref()+ .map_or_else(Instant::now, |output| output.ended_at);+ self.terminal+ .update(cx, |terminal, _| terminal.shrink_to_used());+ self.cache_output(status, ended_at, cx);+ }+ }+ cx.notify();+ Ok(())}fn cache_output(&mut self,- exit_status: acp::TerminalExitStatus,+ exit_status: acp_v2::TerminalExitStatus,ended_at: Instant,cx: &mut Context<Self>,) {@@ -661,7 +851,15 @@ impl Terminal {&self.command}- pub fn update_command_label(&self, label: &str, cx: &mut App) {+ pub fn update_command_label(&mut self, label: &str, cx: &mut App) {+ if let TerminalExecution::Display(state) = &mut self.execution {+ if matches!(state.command, DisplayCommand::Reported(_))+ || state.command() == Some(label)+ {+ return;+ }+ state.command = DisplayCommand::LegacyCaption(label.to_owned());+ }self.command.update(cx, |command, cx| {command.replace(format!("```\n{}\n```", label), cx);});diff --git a/crates/agent_ui/src/agent_panel.rs b/crates/agent_ui/src/agent_panel.rsindex 0d8804757f8..8b50b5e74ca 100644--- a/crates/agent_ui/src/agent_panel.rs+++ b/crates/agent_ui/src/agent_panel.rs@@ -2221,6 +2221,7 @@ impl AgentPanel {this.request_close_terminal_from_terminal_event(terminal_id, cx);}TerminalEvent::BlinkChanged(_)+ | TerminalEvent::OutputReplaced| TerminalEvent::SelectionsChanged| TerminalEvent::NewNavigationTarget(_)| TerminalEvent::Open(_) => {}diff --git a/crates/agent_ui/src/conversation_view.rs b/crates/agent_ui/src/conversation_view.rsindex ee2ac1d5b21..ce890d8fa90 100644--- a/crates/agent_ui/src/conversation_view.rs+++ b/crates/agent_ui/src/conversation_view.rs@@ -12026,6 +12026,137 @@ pub(crate) mod tests {})}+ #[gpui::test]+ async fn test_terminal_snapshots_reuse_the_read_only_tool_view(cx: &mut TestAppContext) {+ init_test(cx);+ 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());+ thread.update(cx, |thread, cx| {+ thread+ .upsert_tool_call_patch(+ acp_v2::ToolCallUpdate::new("tool")+ .title("Run command")+ .kind(acp_v2::ToolKind::Execute)+ .status(acp_v2::ToolCallStatus::Completed)+ .content(vec![acp_v2::ToolCallContent::Terminal(+ acp_v2::Terminal::new("display"),+ )]),+ cx,+ )+ .expect("reference before terminal state");+ });+ 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(acp_v1::ToolCallId::new("tool"));+ cx.notify();+ });+ let terminal = thread.read_with(cx, |thread, _| {+ thread+ .terminal(acp_v1::TerminalId::new("display"))+ .expect("placeholder")+ });+ let renderer = terminal.read_with(cx, |terminal, _| terminal.inner().clone());+ let terminal_view = entry_state.read_with(cx, |state, _| {+ state+ .entry(0)+ .and_then(|entry| entry.terminal(&terminal))+ .expect("terminal view")+ });+ assert!(terminal_view.read_with(cx, |view, _| view.is_read_only()));++ thread.update(cx, |thread, cx| {+ thread+ .upsert_display_terminal(+ "display".into(),+ acp_thread::DisplayTerminalPatch {+ command: agent_client_protocol::schema::MaybeUndefined::Value(+ "actual command".into(),+ ),+ output: agent_client_protocol::schema::MaybeUndefined::Value(+ acp_thread::DisplayTerminalOutput {+ data: b"old output".to_vec(),+ meta: None,+ },+ ),+ exit_status: agent_client_protocol::schema::MaybeUndefined::Value(+ acp_v2::TerminalExitStatus::new().exit_code(7),+ ),+ ..Default::default()+ },+ cx,+ )+ .expect("terminal snapshot");+ });+ cx.run_until_parked();+ assert!(cx.debug_bounds("terminal-tool-failed-Some(7)").is_some());+ assert!(+ renderer+ .read_with(cx, |terminal, _| terminal.get_content())+ .contains("old output")+ );++ thread.update(cx, |thread, cx| {+ thread+ .upsert_display_terminal(+ "display".into(),+ acp_thread::DisplayTerminalPatch {+ output: agent_client_protocol::schema::MaybeUndefined::Value(+ acp_thread::DisplayTerminalOutput {+ data: b"new output".to_vec(),+ meta: None,+ },+ ),+ ..Default::default()+ },+ cx,+ )+ .expect("replace output without changing completion");+ });+ cx.run_until_parked();+ renderer.read_with(cx, |terminal, _| {+ let content = terminal.get_content();+ assert!(content.contains("new output"));+ assert!(!content.contains("old output"));+ });+ assert!(cx.debug_bounds("terminal-tool-failed-Some(7)").is_some());+ assert!(cx.debug_bounds("ICON-Stop").is_none());+ assert_eq!(+ terminal.read_with(cx, |terminal, _| terminal.inner().clone()),+ renderer+ );+ assert_eq!(+ entry_state.read_with(cx, |state, _| state+ .entry(0)+ .and_then(|entry| entry.terminal(&terminal))),+ Some(terminal_view),+ );++ thread.update(cx, |thread, cx| {+ thread+ .upsert_display_terminal(+ "display".into(),+ acp_thread::DisplayTerminalPatch {+ output: agent_client_protocol::schema::MaybeUndefined::Null,+ exit_status: agent_client_protocol::schema::MaybeUndefined::Null,+ ..Default::default()+ },+ cx,+ )+ .expect("clear output and exit information");+ });+ cx.run_until_parked();+ assert!(+ renderer+ .read_with(cx, |terminal, _| terminal.get_content())+ .is_empty()+ );+ assert!(cx.debug_bounds("terminal-tool-failed-Some(7)").is_none());+ }+#[gpui::test]async fn test_display_terminal_does_not_move_to_background_when_tool_completes(cx: &mut TestAppContext,diff --git a/crates/terminal/src/alacritty.rs b/crates/terminal/src/alacritty.rsindex b94e42f12e7..b2e2107da9a 100644--- a/crates/terminal/src/alacritty.rs+++ b/crates/terminal/src/alacritty.rs@@ -55,7 +55,10 @@ pub(super) type AlacrittyGridIterator<'a> = GridIterator<'a, AlacCell>;pub(super) type AlacrittyHyperlink = AlacHyperlink;#[derive(Clone)]-pub(super) struct ZedListener(UnboundedSender<PtyEvent>);+pub(super) struct ZedListener {+ sender: UnboundedSender<PtyEvent>,+ generation: u64,+}#[derive(Clone, Debug)]pub(super) struct AlacrittySearch {@@ -190,8 +193,16 @@ pub(super) fn new_term(bounds: TerminalBounds,events_tx: UnboundedSender<PtyEvent>,alternate_scroll: AlternateScroll,+ generation: u64,) -> Arc<AlacrittyTermLock> {- let mut term = Term::new(config.clone(), &bounds, ZedListener(events_tx));+ let mut term = Term::new(+ config.clone(),+ &bounds,+ ZedListener {+ sender: events_tx,+ generation,+ },+ );if let AlternateScroll::Off = alternate_scroll {term.unset_private_mode(PrivateMode::Named(NamedPrivateMode::AlternateScroll));@@ -206,8 +217,17 @@ pub(super) fn spawn_event_loop(pty: AlacrittyPty,drain_on_exit: bool,) -> Result<PtySender> {- let event_loop = EventLoop::new(term, ZedListener(events_tx), pty, drain_on_exit, false)- .context("failed to create event loop")?;+ let event_loop = EventLoop::new(+ term,+ ZedListener {+ sender: events_tx,+ generation: 0,+ },+ pty,+ drain_on_exit,+ false,+ )+ .context("failed to create event loop")?;let pty_tx = event_loop.channel();let _io_thread = event_loop.spawn();@@ -325,7 +345,9 @@ impl From<AlacTermEvent> for TerminalBackendEvent {impl EventListener for ZedListener {fn send_event(&self, event: AlacTermEvent) {- self.0.unbounded_send(PtyEvent::Event(event.into())).ok();+ self.sender+ .unbounded_send(PtyEvent::Event(event.into(), self.generation))+ .ok();}}@@ -1188,7 +1210,14 @@ mod tests {fn semantic_selection_stops_at_tree_branch() {let config = pty_term_config(1000, SettingsCursorShape::default());let (events_tx, _events_rx) = futures::channel::mpsc::unbounded();- let mut term = Term::new(config, &TerminalBounds::default(), ZedListener(events_tx));+ let mut term = Term::new(+ config,+ &TerminalBounds::default(),+ ZedListener {+ sender: events_tx,+ generation: 0,+ },+ );for character in "└─zms-demo.target".chars() {term.input(character);}diff --git a/crates/terminal/src/terminal.rs b/crates/terminal/src/terminal.rsindex 6bbd5faddac..aee760ec582 100644--- a/crates/terminal/src/terminal.rs+++ b/crates/terminal/src/terminal.rs@@ -669,6 +669,7 @@ pub fn insert_zed_terminal_env(pub enum Event {TitleChanged,BreadcrumbsChanged,+ OutputReplaced,CloseTerminal,Bell,Wakeup,@@ -758,7 +759,7 @@ impl fmt::Debug for TerminalBackendEvent {}enum PtyEvent {- Event(TerminalBackendEvent),+ Event(TerminalBackendEvent, u64),}#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]@@ -1016,7 +1017,13 @@ impl TerminalBuilder {let config = display_only_term_config(scrolling_history, cursor_shape);let (events_tx, events_rx) = unbounded();- let term = new_term(&config, terminal_bounds, events_tx, alternate_scroll);+ let term = new_term(+ &config,+ terminal_bounds,+ events_tx.clone(),+ alternate_scroll,+ 0,+ );let terminal = Terminal {task: None,@@ -1026,6 +1033,8 @@ impl TerminalBuilder {term,term_config: config,output_processor: None,+ output_events_tx: Some(events_tx),+ output_generation: 0,title_override: None,events: VecDeque::with_capacity(10),last_content: Content {@@ -1220,6 +1229,7 @@ impl TerminalBuilder {TerminalBounds::default(),events_tx.clone(),alternate_scroll,+ 0,);// When `no_pty` is set (headless hosts), run the task as a plain@@ -1313,6 +1323,8 @@ impl TerminalBuilder {term,term_config: config,output_processor: None,+ output_events_tx: None,+ output_generation: 0,title_override: terminal_title_override,events: VecDeque::with_capacity(10), //Should never get this high.last_content: Default::default(),@@ -1425,17 +1437,17 @@ impl TerminalBuilder {.timer(std::time::Duration::from_millis(4)).fuse();- let mut wakeup = false;+ let mut wakeup = None;loop {futures::select_biased! {_ = timer => break,event = self.events_rx.next() => {if let Some(event) = event {- if matches!(event, PtyEvent::Event(TerminalBackendEvent::Wakeup))- {- wakeup = true;- } else {- events.push(event);+ match event {+ PtyEvent::Event(TerminalBackendEvent::Wakeup, generation) => {+ wakeup = Some(generation);+ }+ event => events.push(event),}if events.len() > 100 {@@ -1448,14 +1460,17 @@ impl TerminalBuilder {}}- if events.is_empty() && !wakeup {+ if events.is_empty() && wakeup.is_none() {yield_now().await;break 'outer;}terminal.update(cx, |this, cx| {- if wakeup {- this.process_event(TerminalBackendEvent::Wakeup, cx);+ if let Some(generation) = wakeup {+ this.process_pty_event(+ PtyEvent::Event(TerminalBackendEvent::Wakeup, generation),+ cx,+ );}for event in events {@@ -1513,6 +1528,8 @@ pub struct Terminal {term: Arc<AlacrittyTermLock>,term_config: AlacrittyTermConfig,output_processor: Option<Processor<StdSyncHandler>>,+ output_events_tx: Option<futures::channel::mpsc::UnboundedSender<PtyEvent>>,+ output_generation: u64,events: VecDeque<InternalEvent>,/// This is only used for mouse mode cell change detectionlast_mouse: Option<(Point, SelectionSide)>,@@ -1622,7 +1639,11 @@ const SELECTION_DRAG_THRESHOLD: f64 = 2.0;impl Terminal {fn process_pty_event(&mut self, event: PtyEvent, cx: &mut Context<Self>) {match event {- PtyEvent::Event(event) => self.process_event(event, cx),+ PtyEvent::Event(event, generation) => {+ if self.output_events_tx.is_none() || generation == self.output_generation {+ self.process_event(event, cx);+ }+ }}}@@ -1972,7 +1993,7 @@ impl Terminal {}/// Terminal byte streams already contain their control sequences and must not be normalized.- fn write_raw_output(&mut self, bytes: &[u8], cx: &mut Context<Self>) {+ pub fn write_raw_output(&mut self, bytes: &[u8], cx: &mut Context<Self>) {let mut term = self.term.lock();self.output_processor.get_or_insert_with(Processor::<StdSyncHandler>::new)@@ -1982,6 +2003,61 @@ impl Terminal {cx.emit(Event::Wakeup);}+ /// Replaces all display-only output while retaining the terminal entity and its dimensions.+ pub fn replace_display_output(&mut self, bytes: &[u8], cx: &mut Context<Self>) -> Result<()> {+ if !matches!(self.terminal_type, TerminalType::DisplayOnly) || self.subprocess.is_some() {+ bail!("cannot replace output of a process-backed terminal");+ }+ let Some(events_tx) = &self.output_events_tx else {+ bail!("display-only terminal has no output event channel");+ };+ let Some(generation) = self.output_generation.checked_add(1) else {+ bail!("display output generation exhausted");+ };+ let bounds = self.last_content.terminal_bounds;+ let term = new_term(+ &self.term_config,+ bounds,+ events_tx.clone(),+ self.template.alternate_scroll,+ generation,+ );+ self.output_generation = generation;+ self.term = term;+ self.output_processor = None;+ // The new emulator already has the latest requested size; older resizes can truncate it.+ self.events.clear();+ self.last_content = Content {+ terminal_bounds: bounds,+ ..Default::default()+ };+ self.last_mouse = None;+ self.mouse_down_position = None;+ self.matches.clear();+ self.selection_head = None;+ self.breadcrumb_text.clear();+ self.scroll_px = px(0.);+ self.next_link_id = 0;+ self.selection_phase = SelectionPhase::Ended;+ self.hyperlink_regex_searches = RegexSearches::new(+ &self.template.path_hyperlink_regexes,+ self.template.path_hyperlink_timeout,+ );+ self.vi_mode_enabled = false;+ self.last_hyperlink_search_position = None;+ self.mouse_down_hyperlink = None;+ self.cwd_history.clear();+ self.pending_cwd_boundary = None;+ self.write_raw_output(bytes, cx);+ cx.emit(Event::BlinkChanged(+ self.term.lock().cursor_style().blinking,+ ));+ cx.emit(Event::BreadcrumbsChanged);+ cx.emit(Event::NewNavigationTarget(None));+ cx.emit(Event::OutputReplaced);+ Ok(())+ }+pub fn total_lines(&self) -> usize {total_lines(&self.term.lock_unfair())}@@ -3365,7 +3441,10 @@ fn spawn_task_subprocess(processor.advance(&mut *term, &converted);}events_tx- .unbounded_send(PtyEvent::Event(TerminalBackendEvent::Wakeup))+ .unbounded_send(PtyEvent::Event(+ TerminalBackendEvent::Wakeup,+ 0,+ )).ok();}}@@ -3399,7 +3478,7 @@ fn spawn_task_subprocess(Some(status) => TerminalBackendEvent::ChildExit(status),None => TerminalBackendEvent::Exit,};- events_tx.unbounded_send(PtyEvent::Event(event)).ok();+ events_tx.unbounded_send(PtyEvent::Event(event, 0)).ok();}});@@ -3861,6 +3940,10 @@ mod tests {terminal.read_with(cx, |terminal, cx| terminal.wait_for_completed_task(cx));assert_eq!(exit_status.await, Some(ExitStatus::default()));assert_content_eventually(&terminal, "hello-from-subprocess", cx).await;+ terminal.update(cx, |terminal, cx| {+ assert!(terminal.replace_display_output(b"replacement", cx).is_err());+ assert!(terminal.get_content().contains("hello-from-subprocess"));+ });}fn init_terminal_test(cx: &mut TestAppContext, output: &[u8]) -> Entity<Terminal> {@@ -4903,6 +4986,128 @@ mod tests {})}+ #[gpui::test]+ async fn test_replace_display_output_rebuilds_screen_and_accepts_appends(+ cx: &mut TestAppContext,+ ) {+ let bounds = TerminalBounds::new(+ px(20.),+ px(10.),+ bounds(point(px(0.), px(0.)), size(px(300.), px(160.))),+ );+ let terminal = cx.new(|cx| {+ TerminalBuilder::new_display_only_with_bounds(+ SettingsCursorShape::default(),+ AlternateScroll::On,+ None,+ 0,+ cx.background_executor(),+ PathStyle::local(),+ bounds,+ )+ .subscribe(cx)+ });+ let entity_id = terminal.entity_id();+ terminal.update(cx, |terminal, cx| {+ terminal.write_raw_output(b"old history\r\n\x1b[?1049h\x1b[Hold alternate", cx);+ {+ let mut term = terminal.term.lock();+ alacritty::set_selection(+ &mut term,+ Some(&Selection::simple_range(Range::new(+ Point::new(0, 0),+ Point::new(0, 2),+ ))),+ );+ terminal.last_content = make_content(&term, &terminal.last_content);+ }+ assert_eq!(terminal.last_content.selection_text.as_deref(), Some("old"));+ terminal.events.push_back(InternalEvent::Copy(None));+ terminal+ .events+ .push_back(InternalEvent::ScrollToPoint(Point::new(0, 0)));+ terminal+ .matches+ .push(Range::new(Point::new(0, 0), Point::new(0, 3)));+ terminal+ .replace_display_output(b"new", cx)+ .expect("replace");+ terminal.write_raw_output(b" content", cx);+ });+ terminal.read_with(cx, |terminal, _| {+ assert_eq!(terminal.get_content().trim(), "new content");+ assert_eq!(terminal.last_content.terminal_bounds, bounds);+ assert_eq!(terminal.viewport_lines(), bounds.num_lines());+ assert!(terminal.matches.is_empty());+ assert!(terminal.last_content.selection_text.is_none());+ assert!(terminal.events.is_empty());+ assert!(+ !terminal+ .term+ .lock_unfair()+ .mode()+ .contains(alacritty_terminal::term::TermMode::ALT_SCREEN)+ );+ });+ assert_eq!(terminal.entity_id(), entity_id);+ }++ #[gpui::test]+ async fn test_replace_display_output_discards_superseded_resizes(cx: &mut TestAppContext) {+ let (terminal, cx) = init_terminal_test_with_window(cx, b"");+ terminal.update_in(cx, |terminal, window, cx| {+ let wide = TerminalBounds::new(+ px(20.),+ px(10.),+ bounds(point(px(0.), px(0.)), size(px(400.), px(160.))),+ );+ let narrow = TerminalBounds::new(+ px(20.),+ px(10.),+ bounds(point(px(0.), px(0.)), size(px(50.), px(160.))),+ );+ terminal.set_size(wide);+ terminal.sync(window, cx);+ terminal.set_size(narrow);+ terminal.scroll_up_by(1);+ terminal.set_size(wide);+ terminal+ .replace_display_output(b"\x1b[?1049habcdefghijklmnop", cx)+ .expect("snapshot at latest dimensions");+ assert_eq!(terminal.get_content().trim(), "abcdefghijklmnop");+ terminal.sync(window, cx);+ assert_eq!(terminal.get_content().trim(), "abcdefghijklmnop");+ assert_eq!(terminal.last_content.terminal_bounds, wide);+ });+ }++ #[gpui::test]+ async fn test_replace_display_output_resets_parser_and_queued_title(cx: &mut TestAppContext) {+ let terminal = display_only_terminal(cx);+ terminal.update(cx, |terminal, cx| {+ terminal.write_raw_output(b"\x1b]0;stale\x07\x1b[", cx);+ terminal+ .replace_display_output(b"fresh", cx)+ .expect("replace");+ terminal.write_raw_output(b"!", cx);+ });+ cx.run_until_parked();+ terminal.read_with(cx, |terminal, _| {+ assert_eq!(terminal.get_content().trim(), "fresh!");+ assert!(terminal.breadcrumb_text.is_empty());+ });+ terminal.update(cx, |terminal, cx| {+ terminal.write_raw_output(b"\xc3", cx);+ terminal.replace_display_output(b"", cx).expect("clear");+ terminal.write_raw_output(b"\x1b]0;current\x07ok", cx);+ });+ cx.run_until_parked();+ terminal.read_with(cx, |terminal, _| {+ assert_eq!(terminal.get_content().trim(), "ok");+ assert_eq!(terminal.breadcrumb_text, "current");+ });+ }+#[gpui::test]async fn test_write_raw_output_preserves_line_control_semantics(cx: &mut TestAppContext) {let bytes = b"a\nb\rc\r\nd";diff --git a/crates/terminal_view/src/terminal_view.rs b/crates/terminal_view/src/terminal_view.rsindex ac054702d46..c821c4b0f3f 100644--- a/crates/terminal_view/src/terminal_view.rs+++ b/crates/terminal_view/src/terminal_view.rs@@ -1208,6 +1208,20 @@ fn subscribe_for_terminal_events(cx.emit(SearchEvent::MatchesInvalidated);}+ Event::OutputReplaced => {+ terminal_view.hover = None;+ terminal_view.hover_tooltip_update = Task::ready(());+ terminal_view.scroll_top = Pixels::ZERO;+ terminal_view.scroll_handle.future_display_offset.set(None);+ terminal_view.scroll_handle.update(terminal.read(cx));+ terminal_view.block_below_cursor = None;+ window.invalidate_character_coordinates();+ cx.emit(SearchEvent::MatchesInvalidated);+ cx.emit(SearchEvent::ActiveMatchChanged);+ cx.emit(ItemEvent::UpdateTab);+ cx.notify();+ }+Event::Bell => {terminal_view.has_bell = true;if let TerminalBell::System = TerminalSettings::get_global(cx).bell {@@ -2314,6 +2328,56 @@ mod tests {// CSI `1;2A` = cursor-up with the xterm Shift modifier (`1 + 1` for Shift).const SHIFT_UP_ESCAPE: &[u8] = b"\x1b[1;2A";+ #[gpui::test]+ async fn replacing_output_resets_view_scrolling_hover_and_search(cx: &mut TestAppContext) {+ let (project, _workspace, window_handle) = init_test_with_window(cx).await;+ let (_pane, terminal, terminal_view) =+ add_display_only_terminal(&project, window_handle, false, true, cx);+ let mut cx = VisualTestContext::from_window(window_handle.into(), cx);+ terminal.update(&mut cx, |terminal, cx| {+ terminal.write_raw_output(b"\x1b[1 q", cx);+ });+ cx.run_until_parked();+ assert!(terminal_view.read_with(&cx, |view, _| view.blinking_terminal_enabled));+ cx.update(|_, cx| {+ terminal_view.update(cx, |view, _| {+ view.scroll_top = px(25.);+ view.scroll_handle.future_display_offset.set(Some(3));+ view.hover = Some(HoverTarget {+ tooltip: "stale".into(),+ hovered_word: HoveredWord {+ word: "stale".into(),+ word_match: Range::new(+ terminal::Point::new(0, 0),+ terminal::Point::new(0, 5),+ ),+ id: 0,+ },+ });+ });+ terminal.update(cx, |terminal, cx| {+ terminal.write_raw_output(b"old", cx);+ terminal.matches.push(Range::new(+ terminal::Point::new(0, 0),+ terminal::Point::new(0, 3),+ ));+ terminal+ .replace_display_output(b"new", cx)+ .expect("replace");+ });+ });+ cx.run_until_parked();+ cx.update(|_, cx| {+ let view = terminal_view.read(cx);+ assert_eq!(view.scroll_top, Pixels::ZERO);+ assert!(view.scroll_handle.future_display_offset.get().is_none());+ assert!(view.hover.is_none());+ assert!(view.is_read_only());+ assert!(!view.blinking_terminal_enabled);+ assert!(terminal.read(cx).matches.is_empty());+ });+ }+#[gpui::test]async fn edit_menu_copy_and_paste_are_available_when_terminal_is_focused(cx: &mut TestAppContext,