1mod connection;
2mod diff;
3mod mention;
4mod terminal;
5use action_log::{ActionLog, ActionLogTelemetry};
6use agent_client_protocol::{self as acp};
7use anyhow::{Context as _, Result, anyhow};
8use collections::HashSet;
9pub use connection::*;
10pub use diff::*;
11use futures::{FutureExt, channel::oneshot, future::BoxFuture};
12use gpui::{AppContext, AsyncApp, Context, Entity, EventEmitter, SharedString, Task, WeakEntity};
13use itertools::Itertools;
14use language::language_settings::FormatOnSave;
15use language::{Anchor, Buffer, BufferSnapshot, LanguageRegistry, Point, ToPoint, text_diff};
16use markdown::Markdown;
17pub use mention::*;
18use project::lsp_store::{FormatTrigger, LspFormatTarget};
19use project::{AgentLocation, Project, git_store::GitStoreCheckpoint};
20use serde::{Deserialize, Serialize};
21use serde_json::to_string_pretty;
22use std::collections::HashMap;
23use std::error::Error;
24use std::fmt::{Formatter, Write};
25use std::ops::Range;
26use std::process::ExitStatus;
27use std::rc::Rc;
28use std::time::{Duration, Instant};
29use std::{fmt::Display, mem, path::PathBuf, sync::Arc};
30use task::{Shell, ShellBuilder};
31pub use terminal::*;
32use text::Bias;
33use ui::App;
34use util::{ResultExt, get_default_system_shell_preferring_bash, paths::PathStyle};
35use uuid::Uuid;
36
37/// Key used in ACP ToolCall meta to store the tool's programmatic name.
38/// This is a workaround since ACP's ToolCall doesn't have a dedicated name field.
39pub const TOOL_NAME_META_KEY: &str = "tool_name";
40
41/// Helper to extract tool name from ACP meta
42pub fn tool_name_from_meta(meta: &Option<acp::Meta>) -> Option<SharedString> {
43 meta.as_ref()
44 .and_then(|m| m.get(TOOL_NAME_META_KEY))
45 .and_then(|v| v.as_str())
46 .map(|s| SharedString::from(s.to_owned()))
47}
48
49/// Helper to create meta with tool name
50pub fn meta_with_tool_name(tool_name: &str) -> acp::Meta {
51 acp::Meta::from_iter([(TOOL_NAME_META_KEY.into(), tool_name.into())])
52}
53
54/// Key used in ACP ToolCall meta to store the session id and message indexes
55pub const SUBAGENT_SESSION_INFO_META_KEY: &str = "subagent_session_info";
56
57#[derive(Clone, Debug, Deserialize, Serialize)]
58pub struct SubagentSessionInfo {
59 /// The session id of the subagent sessiont that was spawned
60 pub session_id: acp::SessionId,
61 /// The index of the message of the start of the "turn" run by this tool call
62 pub message_start_index: usize,
63 /// The index of the output of the message that the subagent has returned
64 #[serde(skip_serializing_if = "Option::is_none")]
65 pub message_end_index: Option<usize>,
66}
67
68/// Helper to extract subagent session id from ACP meta
69pub fn subagent_session_info_from_meta(meta: &Option<acp::Meta>) -> Option<SubagentSessionInfo> {
70 meta.as_ref()
71 .and_then(|m| m.get(SUBAGENT_SESSION_INFO_META_KEY))
72 .and_then(|v| serde_json::from_value(v.clone()).ok())
73}
74
75#[derive(Debug)]
76pub struct UserMessage {
77 pub id: Option<UserMessageId>,
78 pub content: ContentBlock,
79 pub chunks: Vec<acp::ContentBlock>,
80 pub checkpoint: Option<Checkpoint>,
81 pub indented: bool,
82}
83
84#[derive(Debug)]
85pub struct Checkpoint {
86 git_checkpoint: GitStoreCheckpoint,
87 pub show: bool,
88}
89
90impl UserMessage {
91 fn to_markdown(&self, cx: &App) -> String {
92 let mut markdown = String::new();
93 if self
94 .checkpoint
95 .as_ref()
96 .is_some_and(|checkpoint| checkpoint.show)
97 {
98 writeln!(markdown, "## User (checkpoint)").unwrap();
99 } else {
100 writeln!(markdown, "## User").unwrap();
101 }
102 writeln!(markdown).unwrap();
103 writeln!(markdown, "{}", self.content.to_markdown(cx)).unwrap();
104 writeln!(markdown).unwrap();
105 markdown
106 }
107}
108
109#[derive(Debug, PartialEq)]
110pub struct AssistantMessage {
111 pub chunks: Vec<AssistantMessageChunk>,
112 pub indented: bool,
113 pub is_subagent_output: bool,
114}
115
116impl AssistantMessage {
117 pub fn to_markdown(&self, cx: &App) -> String {
118 format!(
119 "## Assistant\n\n{}\n\n",
120 self.chunks
121 .iter()
122 .map(|chunk| chunk.to_markdown(cx))
123 .join("\n\n")
124 )
125 }
126}
127
128#[derive(Debug, PartialEq)]
129pub enum AssistantMessageChunk {
130 Message { block: ContentBlock },
131 Thought { block: ContentBlock },
132}
133
134impl AssistantMessageChunk {
135 pub fn from_str(
136 chunk: &str,
137 language_registry: &Arc<LanguageRegistry>,
138 path_style: PathStyle,
139 cx: &mut App,
140 ) -> Self {
141 Self::Message {
142 block: ContentBlock::new(chunk.into(), language_registry, path_style, cx),
143 }
144 }
145
146 fn to_markdown(&self, cx: &App) -> String {
147 match self {
148 Self::Message { block } => block.to_markdown(cx).to_string(),
149 Self::Thought { block } => {
150 format!("<thinking>\n{}\n</thinking>", block.to_markdown(cx))
151 }
152 }
153 }
154}
155
156#[derive(Debug)]
157pub enum AgentThreadEntry {
158 UserMessage(UserMessage),
159 AssistantMessage(AssistantMessage),
160 ToolCall(ToolCall),
161}
162
163impl AgentThreadEntry {
164 pub fn is_indented(&self) -> bool {
165 match self {
166 Self::UserMessage(message) => message.indented,
167 Self::AssistantMessage(message) => message.indented,
168 Self::ToolCall(_) => false,
169 }
170 }
171
172 pub fn to_markdown(&self, cx: &App) -> String {
173 match self {
174 Self::UserMessage(message) => message.to_markdown(cx),
175 Self::AssistantMessage(message) => message.to_markdown(cx),
176 Self::ToolCall(tool_call) => tool_call.to_markdown(cx),
177 }
178 }
179
180 pub fn user_message(&self) -> Option<&UserMessage> {
181 if let AgentThreadEntry::UserMessage(message) = self {
182 Some(message)
183 } else {
184 None
185 }
186 }
187
188 pub fn diffs(&self) -> impl Iterator<Item = &Entity<Diff>> {
189 if let AgentThreadEntry::ToolCall(call) = self {
190 itertools::Either::Left(call.diffs())
191 } else {
192 itertools::Either::Right(std::iter::empty())
193 }
194 }
195
196 pub fn terminals(&self) -> impl Iterator<Item = &Entity<Terminal>> {
197 if let AgentThreadEntry::ToolCall(call) = self {
198 itertools::Either::Left(call.terminals())
199 } else {
200 itertools::Either::Right(std::iter::empty())
201 }
202 }
203
204 pub fn location(&self, ix: usize) -> Option<(acp::ToolCallLocation, AgentLocation)> {
205 if let AgentThreadEntry::ToolCall(ToolCall {
206 locations,
207 resolved_locations,
208 ..
209 }) = self
210 {
211 Some((
212 locations.get(ix)?.clone(),
213 resolved_locations.get(ix)?.clone()?,
214 ))
215 } else {
216 None
217 }
218 }
219}
220
221#[derive(Debug)]
222pub struct ToolCall {
223 pub id: acp::ToolCallId,
224 pub label: Entity<Markdown>,
225 pub kind: acp::ToolKind,
226 pub content: Vec<ToolCallContent>,
227 pub status: ToolCallStatus,
228 pub locations: Vec<acp::ToolCallLocation>,
229 pub resolved_locations: Vec<Option<AgentLocation>>,
230 pub raw_input: Option<serde_json::Value>,
231 pub raw_input_markdown: Option<Entity<Markdown>>,
232 pub raw_output: Option<serde_json::Value>,
233 pub tool_name: Option<SharedString>,
234 pub subagent_session_info: Option<SubagentSessionInfo>,
235}
236
237impl ToolCall {
238 fn from_acp(
239 tool_call: acp::ToolCall,
240 status: ToolCallStatus,
241 language_registry: Arc<LanguageRegistry>,
242 path_style: PathStyle,
243 terminals: &HashMap<acp::TerminalId, Entity<Terminal>>,
244 cx: &mut App,
245 ) -> Result<Self> {
246 let title = if tool_call.kind == acp::ToolKind::Execute {
247 tool_call.title
248 } else if let Some((first_line, _)) = tool_call.title.split_once("\n") {
249 first_line.to_owned() + "…"
250 } else {
251 tool_call.title
252 };
253 let mut content = Vec::with_capacity(tool_call.content.len());
254 for item in tool_call.content {
255 if let Some(item) = ToolCallContent::from_acp(
256 item,
257 language_registry.clone(),
258 path_style,
259 terminals,
260 cx,
261 )? {
262 content.push(item);
263 }
264 }
265
266 let raw_input_markdown = tool_call
267 .raw_input
268 .as_ref()
269 .and_then(|input| markdown_for_raw_output(input, &language_registry, cx));
270
271 let tool_name = tool_name_from_meta(&tool_call.meta);
272
273 let subagent_session_info = subagent_session_info_from_meta(&tool_call.meta);
274
275 let result = Self {
276 id: tool_call.tool_call_id,
277 label: cx
278 .new(|cx| Markdown::new(title.into(), Some(language_registry.clone()), None, cx)),
279 kind: tool_call.kind,
280 content,
281 locations: tool_call.locations,
282 resolved_locations: Vec::default(),
283 status,
284 raw_input: tool_call.raw_input,
285 raw_input_markdown,
286 raw_output: tool_call.raw_output,
287 tool_name,
288 subagent_session_info,
289 };
290 Ok(result)
291 }
292
293 fn update_fields(
294 &mut self,
295 fields: acp::ToolCallUpdateFields,
296 meta: Option<acp::Meta>,
297 language_registry: Arc<LanguageRegistry>,
298 path_style: PathStyle,
299 terminals: &HashMap<acp::TerminalId, Entity<Terminal>>,
300 cx: &mut App,
301 ) -> Result<()> {
302 let acp::ToolCallUpdateFields {
303 kind,
304 status,
305 title,
306 content,
307 locations,
308 raw_input,
309 raw_output,
310 ..
311 } = fields;
312
313 if let Some(kind) = kind {
314 self.kind = kind;
315 }
316
317 if let Some(status) = status {
318 self.status = status.into();
319 }
320
321 if let Some(subagent_session_info) = subagent_session_info_from_meta(&meta) {
322 self.subagent_session_info = Some(subagent_session_info);
323 }
324
325 if let Some(title) = title {
326 if self.kind == acp::ToolKind::Execute {
327 for terminal in self.terminals() {
328 terminal.update(cx, |terminal, cx| {
329 terminal.update_command_label(&title, cx);
330 });
331 }
332 }
333 self.label.update(cx, |label, cx| {
334 if self.kind == acp::ToolKind::Execute {
335 label.replace(title, cx);
336 } else if let Some((first_line, _)) = title.split_once("\n") {
337 label.replace(first_line.to_owned() + "…", cx);
338 } else {
339 label.replace(title, cx);
340 }
341 });
342 }
343
344 if let Some(content) = content {
345 let mut new_content_len = content.len();
346 let mut content = content.into_iter();
347
348 // Reuse existing content if we can
349 for (old, new) in self.content.iter_mut().zip(content.by_ref()) {
350 let valid_content =
351 old.update_from_acp(new, language_registry.clone(), path_style, terminals, cx)?;
352 if !valid_content {
353 new_content_len -= 1;
354 }
355 }
356 for new in content {
357 if let Some(new) = ToolCallContent::from_acp(
358 new,
359 language_registry.clone(),
360 path_style,
361 terminals,
362 cx,
363 )? {
364 self.content.push(new);
365 } else {
366 new_content_len -= 1;
367 }
368 }
369 self.content.truncate(new_content_len);
370 }
371
372 if let Some(locations) = locations {
373 self.locations = locations;
374 }
375
376 if let Some(raw_input) = raw_input {
377 self.raw_input_markdown = markdown_for_raw_output(&raw_input, &language_registry, cx);
378 self.raw_input = Some(raw_input);
379 }
380
381 if let Some(raw_output) = raw_output {
382 if self.content.is_empty()
383 && let Some(markdown) = markdown_for_raw_output(&raw_output, &language_registry, cx)
384 {
385 self.content
386 .push(ToolCallContent::ContentBlock(ContentBlock::Markdown {
387 markdown,
388 }));
389 }
390 self.raw_output = Some(raw_output);
391 }
392 Ok(())
393 }
394
395 pub fn diffs(&self) -> impl Iterator<Item = &Entity<Diff>> {
396 self.content.iter().filter_map(|content| match content {
397 ToolCallContent::Diff(diff) => Some(diff),
398 ToolCallContent::ContentBlock(_) => None,
399 ToolCallContent::Terminal(_) => None,
400 })
401 }
402
403 pub fn terminals(&self) -> impl Iterator<Item = &Entity<Terminal>> {
404 self.content.iter().filter_map(|content| match content {
405 ToolCallContent::Terminal(terminal) => Some(terminal),
406 ToolCallContent::ContentBlock(_) => None,
407 ToolCallContent::Diff(_) => None,
408 })
409 }
410
411 pub fn is_subagent(&self) -> bool {
412 self.tool_name.as_ref().is_some_and(|s| s == "spawn_agent")
413 || self.subagent_session_info.is_some()
414 }
415
416 pub fn to_markdown(&self, cx: &App) -> String {
417 let mut markdown = format!(
418 "**Tool Call: {}**\nStatus: {}\n\n",
419 self.label.read(cx).source(),
420 self.status
421 );
422 for content in &self.content {
423 markdown.push_str(content.to_markdown(cx).as_str());
424 markdown.push_str("\n\n");
425 }
426 markdown
427 }
428
429 async fn resolve_location(
430 location: acp::ToolCallLocation,
431 project: WeakEntity<Project>,
432 cx: &mut AsyncApp,
433 ) -> Option<ResolvedLocation> {
434 let buffer = project
435 .update(cx, |project, cx| {
436 project
437 .project_path_for_absolute_path(&location.path, cx)
438 .map(|path| project.open_buffer(path, cx))
439 })
440 .ok()??;
441 let buffer = buffer.await.log_err()?;
442 let position = buffer.update(cx, |buffer, _| {
443 let snapshot = buffer.snapshot();
444 if let Some(row) = location.line {
445 let column = snapshot.indent_size_for_line(row).len;
446 let point = snapshot.clip_point(Point::new(row, column), Bias::Left);
447 snapshot.anchor_before(point)
448 } else {
449 Anchor::min_for_buffer(snapshot.remote_id())
450 }
451 });
452
453 Some(ResolvedLocation { buffer, position })
454 }
455
456 fn resolve_locations(
457 &self,
458 project: Entity<Project>,
459 cx: &mut App,
460 ) -> Task<Vec<Option<ResolvedLocation>>> {
461 let locations = self.locations.clone();
462 project.update(cx, |_, cx| {
463 cx.spawn(async move |project, cx| {
464 let mut new_locations = Vec::new();
465 for location in locations {
466 new_locations.push(Self::resolve_location(location, project.clone(), cx).await);
467 }
468 new_locations
469 })
470 })
471 }
472}
473
474// Separate so we can hold a strong reference to the buffer
475// for saving on the thread
476#[derive(Clone, Debug, PartialEq, Eq)]
477struct ResolvedLocation {
478 buffer: Entity<Buffer>,
479 position: Anchor,
480}
481
482impl From<&ResolvedLocation> for AgentLocation {
483 fn from(value: &ResolvedLocation) -> Self {
484 Self {
485 buffer: value.buffer.downgrade(),
486 position: value.position,
487 }
488 }
489}
490
491#[derive(Debug)]
492pub enum ToolCallStatus {
493 /// The tool call hasn't started running yet, but we start showing it to
494 /// the user.
495 Pending,
496 /// The tool call is waiting for confirmation from the user.
497 WaitingForConfirmation {
498 options: PermissionOptions,
499 respond_tx: oneshot::Sender<acp::PermissionOptionId>,
500 },
501 /// The tool call is currently running.
502 InProgress,
503 /// The tool call completed successfully.
504 Completed,
505 /// The tool call failed.
506 Failed,
507 /// The user rejected the tool call.
508 Rejected,
509 /// The user canceled generation so the tool call was canceled.
510 Canceled,
511}
512
513impl From<acp::ToolCallStatus> for ToolCallStatus {
514 fn from(status: acp::ToolCallStatus) -> Self {
515 match status {
516 acp::ToolCallStatus::Pending => Self::Pending,
517 acp::ToolCallStatus::InProgress => Self::InProgress,
518 acp::ToolCallStatus::Completed => Self::Completed,
519 acp::ToolCallStatus::Failed => Self::Failed,
520 _ => Self::Pending,
521 }
522 }
523}
524
525impl Display for ToolCallStatus {
526 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
527 write!(
528 f,
529 "{}",
530 match self {
531 ToolCallStatus::Pending => "Pending",
532 ToolCallStatus::WaitingForConfirmation { .. } => "Waiting for confirmation",
533 ToolCallStatus::InProgress => "In Progress",
534 ToolCallStatus::Completed => "Completed",
535 ToolCallStatus::Failed => "Failed",
536 ToolCallStatus::Rejected => "Rejected",
537 ToolCallStatus::Canceled => "Canceled",
538 }
539 )
540 }
541}
542
543#[derive(Debug, PartialEq, Clone)]
544pub enum ContentBlock {
545 Empty,
546 Markdown { markdown: Entity<Markdown> },
547 ResourceLink { resource_link: acp::ResourceLink },
548 Image { image: Arc<gpui::Image> },
549}
550
551impl ContentBlock {
552 pub fn new(
553 block: acp::ContentBlock,
554 language_registry: &Arc<LanguageRegistry>,
555 path_style: PathStyle,
556 cx: &mut App,
557 ) -> Self {
558 let mut this = Self::Empty;
559 this.append(block, language_registry, path_style, cx);
560 this
561 }
562
563 pub fn new_combined(
564 blocks: impl IntoIterator<Item = acp::ContentBlock>,
565 language_registry: Arc<LanguageRegistry>,
566 path_style: PathStyle,
567 cx: &mut App,
568 ) -> Self {
569 let mut this = Self::Empty;
570 for block in blocks {
571 this.append(block, &language_registry, path_style, cx);
572 }
573 this
574 }
575
576 pub fn append(
577 &mut self,
578 block: acp::ContentBlock,
579 language_registry: &Arc<LanguageRegistry>,
580 path_style: PathStyle,
581 cx: &mut App,
582 ) {
583 match (&mut *self, &block) {
584 (ContentBlock::Empty, acp::ContentBlock::ResourceLink(resource_link)) => {
585 *self = ContentBlock::ResourceLink {
586 resource_link: resource_link.clone(),
587 };
588 }
589 (ContentBlock::Empty, acp::ContentBlock::Image(image_content)) => {
590 if let Some(image) = Self::decode_image(image_content) {
591 *self = ContentBlock::Image { image };
592 } else {
593 let new_content = Self::image_md(image_content);
594 *self = Self::create_markdown_block(new_content, language_registry, cx);
595 }
596 }
597 (ContentBlock::Empty, _) => {
598 let new_content = Self::block_string_contents(&block, path_style);
599 *self = Self::create_markdown_block(new_content, language_registry, cx);
600 }
601 (ContentBlock::Markdown { markdown }, _) => {
602 let new_content = Self::block_string_contents(&block, path_style);
603 markdown.update(cx, |markdown, cx| markdown.append(&new_content, cx));
604 }
605 (ContentBlock::ResourceLink { resource_link }, _) => {
606 let existing_content = Self::resource_link_md(&resource_link.uri, path_style);
607 let new_content = Self::block_string_contents(&block, path_style);
608 let combined = format!("{}\n{}", existing_content, new_content);
609 *self = Self::create_markdown_block(combined, language_registry, cx);
610 }
611 (ContentBlock::Image { .. }, _) => {
612 let new_content = Self::block_string_contents(&block, path_style);
613 let combined = format!("`Image`\n{}", new_content);
614 *self = Self::create_markdown_block(combined, language_registry, cx);
615 }
616 }
617 }
618
619 fn decode_image(image_content: &acp::ImageContent) -> Option<Arc<gpui::Image>> {
620 use base64::Engine as _;
621
622 let bytes = base64::engine::general_purpose::STANDARD
623 .decode(image_content.data.as_bytes())
624 .ok()?;
625 let format = gpui::ImageFormat::from_mime_type(&image_content.mime_type)?;
626 Some(Arc::new(gpui::Image::from_bytes(format, bytes)))
627 }
628
629 fn create_markdown_block(
630 content: String,
631 language_registry: &Arc<LanguageRegistry>,
632 cx: &mut App,
633 ) -> ContentBlock {
634 ContentBlock::Markdown {
635 markdown: cx
636 .new(|cx| Markdown::new(content.into(), Some(language_registry.clone()), None, cx)),
637 }
638 }
639
640 fn block_string_contents(block: &acp::ContentBlock, path_style: PathStyle) -> String {
641 match block {
642 acp::ContentBlock::Text(text_content) => text_content.text.clone(),
643 acp::ContentBlock::ResourceLink(resource_link) => {
644 Self::resource_link_md(&resource_link.uri, path_style)
645 }
646 acp::ContentBlock::Resource(acp::EmbeddedResource {
647 resource:
648 acp::EmbeddedResourceResource::TextResourceContents(acp::TextResourceContents {
649 uri,
650 ..
651 }),
652 ..
653 }) => Self::resource_link_md(uri, path_style),
654 acp::ContentBlock::Image(image) => Self::image_md(image),
655 _ => String::new(),
656 }
657 }
658
659 fn resource_link_md(uri: &str, path_style: PathStyle) -> String {
660 if let Some(uri) = MentionUri::parse(uri, path_style).log_err() {
661 uri.as_link().to_string()
662 } else {
663 uri.to_string()
664 }
665 }
666
667 fn image_md(_image: &acp::ImageContent) -> String {
668 "`Image`".into()
669 }
670
671 pub fn to_markdown<'a>(&'a self, cx: &'a App) -> &'a str {
672 match self {
673 ContentBlock::Empty => "",
674 ContentBlock::Markdown { markdown } => markdown.read(cx).source(),
675 ContentBlock::ResourceLink { resource_link } => &resource_link.uri,
676 ContentBlock::Image { .. } => "`Image`",
677 }
678 }
679
680 pub fn markdown(&self) -> Option<&Entity<Markdown>> {
681 match self {
682 ContentBlock::Empty => None,
683 ContentBlock::Markdown { markdown } => Some(markdown),
684 ContentBlock::ResourceLink { .. } => None,
685 ContentBlock::Image { .. } => None,
686 }
687 }
688
689 pub fn resource_link(&self) -> Option<&acp::ResourceLink> {
690 match self {
691 ContentBlock::ResourceLink { resource_link } => Some(resource_link),
692 _ => None,
693 }
694 }
695
696 pub fn image(&self) -> Option<&Arc<gpui::Image>> {
697 match self {
698 ContentBlock::Image { image } => Some(image),
699 _ => None,
700 }
701 }
702}
703
704#[derive(Debug)]
705pub enum ToolCallContent {
706 ContentBlock(ContentBlock),
707 Diff(Entity<Diff>),
708 Terminal(Entity<Terminal>),
709}
710
711impl ToolCallContent {
712 pub fn from_acp(
713 content: acp::ToolCallContent,
714 language_registry: Arc<LanguageRegistry>,
715 path_style: PathStyle,
716 terminals: &HashMap<acp::TerminalId, Entity<Terminal>>,
717 cx: &mut App,
718 ) -> Result<Option<Self>> {
719 match content {
720 acp::ToolCallContent::Content(acp::Content { content, .. }) => {
721 Ok(Some(Self::ContentBlock(ContentBlock::new(
722 content,
723 &language_registry,
724 path_style,
725 cx,
726 ))))
727 }
728 acp::ToolCallContent::Diff(diff) => Ok(Some(Self::Diff(cx.new(|cx| {
729 Diff::finalized(
730 diff.path.to_string_lossy().into_owned(),
731 diff.old_text,
732 diff.new_text,
733 language_registry,
734 cx,
735 )
736 })))),
737 acp::ToolCallContent::Terminal(acp::Terminal { terminal_id, .. }) => terminals
738 .get(&terminal_id)
739 .cloned()
740 .map(|terminal| Some(Self::Terminal(terminal)))
741 .ok_or_else(|| anyhow::anyhow!("Terminal with id `{}` not found", terminal_id)),
742 _ => Ok(None),
743 }
744 }
745
746 pub fn update_from_acp(
747 &mut self,
748 new: acp::ToolCallContent,
749 language_registry: Arc<LanguageRegistry>,
750 path_style: PathStyle,
751 terminals: &HashMap<acp::TerminalId, Entity<Terminal>>,
752 cx: &mut App,
753 ) -> Result<bool> {
754 let needs_update = match (&self, &new) {
755 (Self::Diff(old_diff), acp::ToolCallContent::Diff(new_diff)) => {
756 old_diff.read(cx).needs_update(
757 new_diff.old_text.as_deref().unwrap_or(""),
758 &new_diff.new_text,
759 cx,
760 )
761 }
762 _ => true,
763 };
764
765 if let Some(update) = Self::from_acp(new, language_registry, path_style, terminals, cx)? {
766 if needs_update {
767 *self = update;
768 }
769 Ok(true)
770 } else {
771 Ok(false)
772 }
773 }
774
775 pub fn to_markdown(&self, cx: &App) -> String {
776 match self {
777 Self::ContentBlock(content) => content.to_markdown(cx).to_string(),
778 Self::Diff(diff) => diff.read(cx).to_markdown(cx),
779 Self::Terminal(terminal) => terminal.read(cx).to_markdown(cx),
780 }
781 }
782
783 pub fn image(&self) -> Option<&Arc<gpui::Image>> {
784 match self {
785 Self::ContentBlock(content) => content.image(),
786 _ => None,
787 }
788 }
789}
790
791#[derive(Debug, PartialEq)]
792pub enum ToolCallUpdate {
793 UpdateFields(acp::ToolCallUpdate),
794 UpdateDiff(ToolCallUpdateDiff),
795 UpdateTerminal(ToolCallUpdateTerminal),
796}
797
798impl ToolCallUpdate {
799 fn id(&self) -> &acp::ToolCallId {
800 match self {
801 Self::UpdateFields(update) => &update.tool_call_id,
802 Self::UpdateDiff(diff) => &diff.id,
803 Self::UpdateTerminal(terminal) => &terminal.id,
804 }
805 }
806}
807
808impl From<acp::ToolCallUpdate> for ToolCallUpdate {
809 fn from(update: acp::ToolCallUpdate) -> Self {
810 Self::UpdateFields(update)
811 }
812}
813
814impl From<ToolCallUpdateDiff> for ToolCallUpdate {
815 fn from(diff: ToolCallUpdateDiff) -> Self {
816 Self::UpdateDiff(diff)
817 }
818}
819
820#[derive(Debug, PartialEq)]
821pub struct ToolCallUpdateDiff {
822 pub id: acp::ToolCallId,
823 pub diff: Entity<Diff>,
824}
825
826impl From<ToolCallUpdateTerminal> for ToolCallUpdate {
827 fn from(terminal: ToolCallUpdateTerminal) -> Self {
828 Self::UpdateTerminal(terminal)
829 }
830}
831
832#[derive(Debug, PartialEq)]
833pub struct ToolCallUpdateTerminal {
834 pub id: acp::ToolCallId,
835 pub terminal: Entity<Terminal>,
836}
837
838#[derive(Debug, Default)]
839pub struct Plan {
840 pub entries: Vec<PlanEntry>,
841}
842
843#[derive(Debug)]
844pub struct PlanStats<'a> {
845 pub in_progress_entry: Option<&'a PlanEntry>,
846 pub pending: u32,
847 pub completed: u32,
848}
849
850impl Plan {
851 pub fn is_empty(&self) -> bool {
852 self.entries.is_empty()
853 }
854
855 pub fn stats(&self) -> PlanStats<'_> {
856 let mut stats = PlanStats {
857 in_progress_entry: None,
858 pending: 0,
859 completed: 0,
860 };
861
862 for entry in &self.entries {
863 match &entry.status {
864 acp::PlanEntryStatus::Pending => {
865 stats.pending += 1;
866 }
867 acp::PlanEntryStatus::InProgress => {
868 stats.in_progress_entry = stats.in_progress_entry.or(Some(entry));
869 }
870 acp::PlanEntryStatus::Completed => {
871 stats.completed += 1;
872 }
873 _ => {}
874 }
875 }
876
877 stats
878 }
879}
880
881#[derive(Debug)]
882pub struct PlanEntry {
883 pub content: Entity<Markdown>,
884 pub priority: acp::PlanEntryPriority,
885 pub status: acp::PlanEntryStatus,
886}
887
888impl PlanEntry {
889 pub fn from_acp(entry: acp::PlanEntry, cx: &mut App) -> Self {
890 Self {
891 content: cx.new(|cx| Markdown::new(entry.content.into(), None, None, cx)),
892 priority: entry.priority,
893 status: entry.status,
894 }
895 }
896}
897
898#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
899pub struct TokenUsage {
900 pub max_tokens: u64,
901 pub used_tokens: u64,
902 pub input_tokens: u64,
903 pub output_tokens: u64,
904 pub max_output_tokens: Option<u64>,
905}
906
907pub const TOKEN_USAGE_WARNING_THRESHOLD: f32 = 0.8;
908
909impl TokenUsage {
910 pub fn ratio(&self) -> TokenUsageRatio {
911 #[cfg(debug_assertions)]
912 let warning_threshold: f32 = std::env::var("ZED_THREAD_WARNING_THRESHOLD")
913 .unwrap_or(TOKEN_USAGE_WARNING_THRESHOLD.to_string())
914 .parse()
915 .unwrap();
916 #[cfg(not(debug_assertions))]
917 let warning_threshold: f32 = TOKEN_USAGE_WARNING_THRESHOLD;
918
919 // When the maximum is unknown because there is no selected model,
920 // avoid showing the token limit warning.
921 if self.max_tokens == 0 {
922 TokenUsageRatio::Normal
923 } else if self.used_tokens >= self.max_tokens {
924 TokenUsageRatio::Exceeded
925 } else if self.used_tokens as f32 / self.max_tokens as f32 >= warning_threshold {
926 TokenUsageRatio::Warning
927 } else {
928 TokenUsageRatio::Normal
929 }
930 }
931}
932
933#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
934pub enum TokenUsageRatio {
935 Normal,
936 Warning,
937 Exceeded,
938}
939
940#[derive(Debug, Clone)]
941pub struct RetryStatus {
942 pub last_error: SharedString,
943 pub attempt: usize,
944 pub max_attempts: usize,
945 pub started_at: Instant,
946 pub duration: Duration,
947}
948
949struct RunningTurn {
950 id: u32,
951 send_task: Task<()>,
952}
953
954pub struct AcpThread {
955 session_id: acp::SessionId,
956 cwd: Option<PathBuf>,
957 parent_session_id: Option<acp::SessionId>,
958 title: SharedString,
959 provisional_title: Option<SharedString>,
960 entries: Vec<AgentThreadEntry>,
961 plan: Plan,
962 project: Entity<Project>,
963 action_log: Entity<ActionLog>,
964 shared_buffers: HashMap<Entity<Buffer>, BufferSnapshot>,
965 turn_id: u32,
966 running_turn: Option<RunningTurn>,
967 connection: Rc<dyn AgentConnection>,
968 token_usage: Option<TokenUsage>,
969 prompt_capabilities: acp::PromptCapabilities,
970 _observe_prompt_capabilities: Task<anyhow::Result<()>>,
971 terminals: HashMap<acp::TerminalId, Entity<Terminal>>,
972 pending_terminal_output: HashMap<acp::TerminalId, Vec<Vec<u8>>>,
973 pending_terminal_exit: HashMap<acp::TerminalId, acp::TerminalExitStatus>,
974 had_error: bool,
975 /// The user's unsent prompt text, persisted so it can be restored when reloading the thread.
976 draft_prompt: Option<Vec<acp::ContentBlock>>,
977 /// The initial scroll position for the thread view, set during session registration.
978 ui_scroll_position: Option<gpui::ListOffset>,
979}
980
981impl From<&AcpThread> for ActionLogTelemetry {
982 fn from(value: &AcpThread) -> Self {
983 Self {
984 agent_telemetry_id: value.connection().telemetry_id(),
985 session_id: value.session_id.0.clone(),
986 }
987 }
988}
989
990#[derive(Debug)]
991pub enum AcpThreadEvent {
992 NewEntry,
993 TitleUpdated,
994 TokenUsageUpdated,
995 EntryUpdated(usize),
996 EntriesRemoved(Range<usize>),
997 ToolAuthorizationRequested(acp::ToolCallId),
998 ToolAuthorizationReceived(acp::ToolCallId),
999 Retry(RetryStatus),
1000 SubagentSpawned(acp::SessionId),
1001 Stopped(acp::StopReason),
1002 Error,
1003 LoadError(LoadError),
1004 PromptCapabilitiesUpdated,
1005 Refusal,
1006 AvailableCommandsUpdated(Vec<acp::AvailableCommand>),
1007 ModeUpdated(acp::SessionModeId),
1008 ConfigOptionsUpdated(Vec<acp::SessionConfigOption>),
1009}
1010
1011impl EventEmitter<AcpThreadEvent> for AcpThread {}
1012
1013#[derive(Debug, Clone)]
1014pub enum TerminalProviderEvent {
1015 Created {
1016 terminal_id: acp::TerminalId,
1017 label: String,
1018 cwd: Option<PathBuf>,
1019 output_byte_limit: Option<u64>,
1020 terminal: Entity<::terminal::Terminal>,
1021 },
1022 Output {
1023 terminal_id: acp::TerminalId,
1024 data: Vec<u8>,
1025 },
1026 TitleChanged {
1027 terminal_id: acp::TerminalId,
1028 title: String,
1029 },
1030 Exit {
1031 terminal_id: acp::TerminalId,
1032 status: acp::TerminalExitStatus,
1033 },
1034}
1035
1036#[derive(Debug, Clone)]
1037pub enum TerminalProviderCommand {
1038 WriteInput {
1039 terminal_id: acp::TerminalId,
1040 bytes: Vec<u8>,
1041 },
1042 Resize {
1043 terminal_id: acp::TerminalId,
1044 cols: u16,
1045 rows: u16,
1046 },
1047 Close {
1048 terminal_id: acp::TerminalId,
1049 },
1050}
1051
1052#[derive(PartialEq, Eq, Debug)]
1053pub enum ThreadStatus {
1054 Idle,
1055 Generating,
1056}
1057
1058#[derive(Debug, Clone)]
1059pub enum LoadError {
1060 Unsupported {
1061 command: SharedString,
1062 current_version: SharedString,
1063 minimum_version: SharedString,
1064 },
1065 FailedToInstall(SharedString),
1066 Exited {
1067 status: ExitStatus,
1068 },
1069 Other(SharedString),
1070}
1071
1072impl Display for LoadError {
1073 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
1074 match self {
1075 LoadError::Unsupported {
1076 command: path,
1077 current_version,
1078 minimum_version,
1079 } => {
1080 write!(
1081 f,
1082 "version {current_version} from {path} is not supported (need at least {minimum_version})"
1083 )
1084 }
1085 LoadError::FailedToInstall(msg) => write!(f, "Failed to install: {msg}"),
1086 LoadError::Exited { status } => write!(f, "Server exited with status {status}"),
1087 LoadError::Other(msg) => write!(f, "{msg}"),
1088 }
1089 }
1090}
1091
1092impl Error for LoadError {}
1093
1094impl AcpThread {
1095 pub fn new(
1096 parent_session_id: Option<acp::SessionId>,
1097 title: impl Into<SharedString>,
1098 cwd: Option<PathBuf>,
1099 connection: Rc<dyn AgentConnection>,
1100 project: Entity<Project>,
1101 action_log: Entity<ActionLog>,
1102 session_id: acp::SessionId,
1103 mut prompt_capabilities_rx: watch::Receiver<acp::PromptCapabilities>,
1104 cx: &mut Context<Self>,
1105 ) -> Self {
1106 let prompt_capabilities = prompt_capabilities_rx.borrow().clone();
1107 let task = cx.spawn::<_, anyhow::Result<()>>(async move |this, cx| {
1108 loop {
1109 let caps = prompt_capabilities_rx.recv().await?;
1110 this.update(cx, |this, cx| {
1111 this.prompt_capabilities = caps;
1112 cx.emit(AcpThreadEvent::PromptCapabilitiesUpdated);
1113 })?;
1114 }
1115 });
1116
1117 Self {
1118 parent_session_id,
1119 cwd,
1120 action_log,
1121 shared_buffers: Default::default(),
1122 entries: Default::default(),
1123 plan: Default::default(),
1124 title: title.into(),
1125 provisional_title: None,
1126 project,
1127 running_turn: None,
1128 turn_id: 0,
1129 connection,
1130 session_id,
1131 token_usage: None,
1132 prompt_capabilities,
1133 _observe_prompt_capabilities: task,
1134 terminals: HashMap::default(),
1135 pending_terminal_output: HashMap::default(),
1136 pending_terminal_exit: HashMap::default(),
1137 had_error: false,
1138 draft_prompt: None,
1139 ui_scroll_position: None,
1140 }
1141 }
1142
1143 pub fn parent_session_id(&self) -> Option<&acp::SessionId> {
1144 self.parent_session_id.as_ref()
1145 }
1146
1147 pub fn prompt_capabilities(&self) -> acp::PromptCapabilities {
1148 self.prompt_capabilities.clone()
1149 }
1150
1151 pub fn draft_prompt(&self) -> Option<&[acp::ContentBlock]> {
1152 self.draft_prompt.as_deref()
1153 }
1154
1155 pub fn set_draft_prompt(&mut self, prompt: Option<Vec<acp::ContentBlock>>) {
1156 self.draft_prompt = prompt;
1157 }
1158
1159 pub fn ui_scroll_position(&self) -> Option<gpui::ListOffset> {
1160 self.ui_scroll_position
1161 }
1162
1163 pub fn set_ui_scroll_position(&mut self, position: Option<gpui::ListOffset>) {
1164 self.ui_scroll_position = position;
1165 }
1166
1167 pub fn connection(&self) -> &Rc<dyn AgentConnection> {
1168 &self.connection
1169 }
1170
1171 pub fn action_log(&self) -> &Entity<ActionLog> {
1172 &self.action_log
1173 }
1174
1175 pub fn project(&self) -> &Entity<Project> {
1176 &self.project
1177 }
1178
1179 pub fn title(&self) -> SharedString {
1180 self.provisional_title
1181 .clone()
1182 .unwrap_or_else(|| self.title.clone())
1183 }
1184
1185 pub fn entries(&self) -> &[AgentThreadEntry] {
1186 &self.entries
1187 }
1188
1189 pub fn session_id(&self) -> &acp::SessionId {
1190 &self.session_id
1191 }
1192
1193 pub fn cwd(&self) -> Option<&PathBuf> {
1194 self.cwd.as_ref()
1195 }
1196
1197 pub fn status(&self) -> ThreadStatus {
1198 if self.running_turn.is_some() {
1199 ThreadStatus::Generating
1200 } else {
1201 ThreadStatus::Idle
1202 }
1203 }
1204
1205 pub fn had_error(&self) -> bool {
1206 self.had_error
1207 }
1208
1209 pub fn is_waiting_for_confirmation(&self) -> bool {
1210 for entry in self.entries.iter().rev() {
1211 match entry {
1212 AgentThreadEntry::UserMessage(_) => return false,
1213 AgentThreadEntry::ToolCall(ToolCall {
1214 status: ToolCallStatus::WaitingForConfirmation { .. },
1215 ..
1216 }) => return true,
1217 AgentThreadEntry::ToolCall(_) | AgentThreadEntry::AssistantMessage(_) => {}
1218 }
1219 }
1220 false
1221 }
1222
1223 pub fn token_usage(&self) -> Option<&TokenUsage> {
1224 self.token_usage.as_ref()
1225 }
1226
1227 pub fn has_pending_edit_tool_calls(&self) -> bool {
1228 for entry in self.entries.iter().rev() {
1229 match entry {
1230 AgentThreadEntry::UserMessage(_) => return false,
1231 AgentThreadEntry::ToolCall(
1232 call @ ToolCall {
1233 status: ToolCallStatus::InProgress | ToolCallStatus::Pending,
1234 ..
1235 },
1236 ) if call.diffs().next().is_some() => {
1237 return true;
1238 }
1239 AgentThreadEntry::ToolCall(_) | AgentThreadEntry::AssistantMessage(_) => {}
1240 }
1241 }
1242
1243 false
1244 }
1245
1246 pub fn has_in_progress_tool_calls(&self) -> bool {
1247 for entry in self.entries.iter().rev() {
1248 match entry {
1249 AgentThreadEntry::UserMessage(_) => return false,
1250 AgentThreadEntry::ToolCall(ToolCall {
1251 status: ToolCallStatus::InProgress | ToolCallStatus::Pending,
1252 ..
1253 }) => {
1254 return true;
1255 }
1256 AgentThreadEntry::ToolCall(_) | AgentThreadEntry::AssistantMessage(_) => {}
1257 }
1258 }
1259
1260 false
1261 }
1262
1263 pub fn used_tools_since_last_user_message(&self) -> bool {
1264 for entry in self.entries.iter().rev() {
1265 match entry {
1266 AgentThreadEntry::UserMessage(..) => return false,
1267 AgentThreadEntry::AssistantMessage(..) => continue,
1268 AgentThreadEntry::ToolCall(..) => return true,
1269 }
1270 }
1271
1272 false
1273 }
1274
1275 pub fn handle_session_update(
1276 &mut self,
1277 update: acp::SessionUpdate,
1278 cx: &mut Context<Self>,
1279 ) -> Result<(), acp::Error> {
1280 match update {
1281 acp::SessionUpdate::UserMessageChunk(acp::ContentChunk { content, .. }) => {
1282 self.push_user_content_block(None, content, cx);
1283 }
1284 acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk { content, .. }) => {
1285 self.push_assistant_content_block(content, false, cx);
1286 }
1287 acp::SessionUpdate::AgentThoughtChunk(acp::ContentChunk { content, .. }) => {
1288 self.push_assistant_content_block(content, true, cx);
1289 }
1290 acp::SessionUpdate::ToolCall(tool_call) => {
1291 self.upsert_tool_call(tool_call, cx)?;
1292 }
1293 acp::SessionUpdate::ToolCallUpdate(tool_call_update) => {
1294 self.update_tool_call(tool_call_update, cx)?;
1295 }
1296 acp::SessionUpdate::Plan(plan) => {
1297 self.update_plan(plan, cx);
1298 }
1299 acp::SessionUpdate::AvailableCommandsUpdate(acp::AvailableCommandsUpdate {
1300 available_commands,
1301 ..
1302 }) => cx.emit(AcpThreadEvent::AvailableCommandsUpdated(available_commands)),
1303 acp::SessionUpdate::CurrentModeUpdate(acp::CurrentModeUpdate {
1304 current_mode_id,
1305 ..
1306 }) => cx.emit(AcpThreadEvent::ModeUpdated(current_mode_id)),
1307 acp::SessionUpdate::ConfigOptionUpdate(acp::ConfigOptionUpdate {
1308 config_options,
1309 ..
1310 }) => cx.emit(AcpThreadEvent::ConfigOptionsUpdated(config_options)),
1311 _ => {}
1312 }
1313 Ok(())
1314 }
1315
1316 pub fn push_user_content_block(
1317 &mut self,
1318 message_id: Option<UserMessageId>,
1319 chunk: acp::ContentBlock,
1320 cx: &mut Context<Self>,
1321 ) {
1322 self.push_user_content_block_with_indent(message_id, chunk, false, cx)
1323 }
1324
1325 pub fn push_user_content_block_with_indent(
1326 &mut self,
1327 message_id: Option<UserMessageId>,
1328 chunk: acp::ContentBlock,
1329 indented: bool,
1330 cx: &mut Context<Self>,
1331 ) {
1332 let language_registry = self.project.read(cx).languages().clone();
1333 let path_style = self.project.read(cx).path_style(cx);
1334 let entries_len = self.entries.len();
1335
1336 if let Some(last_entry) = self.entries.last_mut()
1337 && let AgentThreadEntry::UserMessage(UserMessage {
1338 id,
1339 content,
1340 chunks,
1341 indented: existing_indented,
1342 ..
1343 }) = last_entry
1344 && *existing_indented == indented
1345 {
1346 *id = message_id.or(id.take());
1347 content.append(chunk.clone(), &language_registry, path_style, cx);
1348 chunks.push(chunk);
1349 let idx = entries_len - 1;
1350 cx.emit(AcpThreadEvent::EntryUpdated(idx));
1351 } else {
1352 let content = ContentBlock::new(chunk.clone(), &language_registry, path_style, cx);
1353 self.push_entry(
1354 AgentThreadEntry::UserMessage(UserMessage {
1355 id: message_id,
1356 content,
1357 chunks: vec![chunk],
1358 checkpoint: None,
1359 indented,
1360 }),
1361 cx,
1362 );
1363 }
1364 }
1365
1366 pub fn push_assistant_content_block(
1367 &mut self,
1368 chunk: acp::ContentBlock,
1369 is_thought: bool,
1370 cx: &mut Context<Self>,
1371 ) {
1372 self.push_assistant_content_block_with_indent(chunk, is_thought, false, cx)
1373 }
1374
1375 pub fn push_assistant_content_block_with_indent(
1376 &mut self,
1377 chunk: acp::ContentBlock,
1378 is_thought: bool,
1379 indented: bool,
1380 cx: &mut Context<Self>,
1381 ) {
1382 let language_registry = self.project.read(cx).languages().clone();
1383 let path_style = self.project.read(cx).path_style(cx);
1384 let entries_len = self.entries.len();
1385 if let Some(last_entry) = self.entries.last_mut()
1386 && let AgentThreadEntry::AssistantMessage(AssistantMessage {
1387 chunks,
1388 indented: existing_indented,
1389 is_subagent_output: _,
1390 }) = last_entry
1391 && *existing_indented == indented
1392 {
1393 let idx = entries_len - 1;
1394 cx.emit(AcpThreadEvent::EntryUpdated(idx));
1395 match (chunks.last_mut(), is_thought) {
1396 (Some(AssistantMessageChunk::Message { block }), false)
1397 | (Some(AssistantMessageChunk::Thought { block }), true) => {
1398 block.append(chunk, &language_registry, path_style, cx)
1399 }
1400 _ => {
1401 let block = ContentBlock::new(chunk, &language_registry, path_style, cx);
1402 if is_thought {
1403 chunks.push(AssistantMessageChunk::Thought { block })
1404 } else {
1405 chunks.push(AssistantMessageChunk::Message { block })
1406 }
1407 }
1408 }
1409 } else {
1410 let block = ContentBlock::new(chunk, &language_registry, path_style, cx);
1411 let chunk = if is_thought {
1412 AssistantMessageChunk::Thought { block }
1413 } else {
1414 AssistantMessageChunk::Message { block }
1415 };
1416
1417 self.push_entry(
1418 AgentThreadEntry::AssistantMessage(AssistantMessage {
1419 chunks: vec![chunk],
1420 indented,
1421 is_subagent_output: false,
1422 }),
1423 cx,
1424 );
1425 }
1426 }
1427
1428 fn push_entry(&mut self, entry: AgentThreadEntry, cx: &mut Context<Self>) {
1429 self.entries.push(entry);
1430 cx.emit(AcpThreadEvent::NewEntry);
1431 }
1432
1433 pub fn can_set_title(&mut self, cx: &mut Context<Self>) -> bool {
1434 self.connection.set_title(&self.session_id, cx).is_some()
1435 }
1436
1437 pub fn set_title(&mut self, title: SharedString, cx: &mut Context<Self>) -> Task<Result<()>> {
1438 let had_provisional = self.provisional_title.take().is_some();
1439 if title != self.title {
1440 self.title = title.clone();
1441 cx.emit(AcpThreadEvent::TitleUpdated);
1442 if let Some(set_title) = self.connection.set_title(&self.session_id, cx) {
1443 return set_title.run(title, cx);
1444 }
1445 } else if had_provisional {
1446 cx.emit(AcpThreadEvent::TitleUpdated);
1447 }
1448 Task::ready(Ok(()))
1449 }
1450
1451 /// Sets a provisional display title without propagating back to the
1452 /// underlying agent connection. This is used for quick preview titles
1453 /// (e.g. first 20 chars of the user message) that should be shown
1454 /// immediately but replaced once the LLM generates a proper title via
1455 /// `set_title`.
1456 pub fn set_provisional_title(&mut self, title: SharedString, cx: &mut Context<Self>) {
1457 self.provisional_title = Some(title);
1458 cx.emit(AcpThreadEvent::TitleUpdated);
1459 }
1460
1461 pub fn subagent_spawned(&mut self, session_id: acp::SessionId, cx: &mut Context<Self>) {
1462 cx.emit(AcpThreadEvent::SubagentSpawned(session_id));
1463 }
1464
1465 pub fn update_token_usage(&mut self, usage: Option<TokenUsage>, cx: &mut Context<Self>) {
1466 self.token_usage = usage;
1467 cx.emit(AcpThreadEvent::TokenUsageUpdated);
1468 }
1469
1470 pub fn update_retry_status(&mut self, status: RetryStatus, cx: &mut Context<Self>) {
1471 cx.emit(AcpThreadEvent::Retry(status));
1472 }
1473
1474 pub fn update_tool_call(
1475 &mut self,
1476 update: impl Into<ToolCallUpdate>,
1477 cx: &mut Context<Self>,
1478 ) -> Result<()> {
1479 let update = update.into();
1480 let languages = self.project.read(cx).languages().clone();
1481 let path_style = self.project.read(cx).path_style(cx);
1482
1483 let ix = match self.index_for_tool_call(update.id()) {
1484 Some(ix) => ix,
1485 None => {
1486 // Tool call not found - create a failed tool call entry
1487 let failed_tool_call = ToolCall {
1488 id: update.id().clone(),
1489 label: cx.new(|cx| Markdown::new("Tool call not found".into(), None, None, cx)),
1490 kind: acp::ToolKind::Fetch,
1491 content: vec![ToolCallContent::ContentBlock(ContentBlock::new(
1492 "Tool call not found".into(),
1493 &languages,
1494 path_style,
1495 cx,
1496 ))],
1497 status: ToolCallStatus::Failed,
1498 locations: Vec::new(),
1499 resolved_locations: Vec::new(),
1500 raw_input: None,
1501 raw_input_markdown: None,
1502 raw_output: None,
1503 tool_name: None,
1504 subagent_session_info: None,
1505 };
1506 self.push_entry(AgentThreadEntry::ToolCall(failed_tool_call), cx);
1507 return Ok(());
1508 }
1509 };
1510 let AgentThreadEntry::ToolCall(call) = &mut self.entries[ix] else {
1511 unreachable!()
1512 };
1513
1514 match update {
1515 ToolCallUpdate::UpdateFields(update) => {
1516 let location_updated = update.fields.locations.is_some();
1517 call.update_fields(
1518 update.fields,
1519 update.meta,
1520 languages,
1521 path_style,
1522 &self.terminals,
1523 cx,
1524 )?;
1525 if location_updated {
1526 self.resolve_locations(update.tool_call_id, cx);
1527 }
1528 }
1529 ToolCallUpdate::UpdateDiff(update) => {
1530 call.content.clear();
1531 call.content.push(ToolCallContent::Diff(update.diff));
1532 }
1533 ToolCallUpdate::UpdateTerminal(update) => {
1534 call.content.clear();
1535 call.content
1536 .push(ToolCallContent::Terminal(update.terminal));
1537 }
1538 }
1539
1540 cx.emit(AcpThreadEvent::EntryUpdated(ix));
1541
1542 Ok(())
1543 }
1544
1545 /// Updates a tool call if id matches an existing entry, otherwise inserts a new one.
1546 pub fn upsert_tool_call(
1547 &mut self,
1548 tool_call: acp::ToolCall,
1549 cx: &mut Context<Self>,
1550 ) -> Result<(), acp::Error> {
1551 let status = tool_call.status.into();
1552 self.upsert_tool_call_inner(tool_call.into(), status, cx)
1553 }
1554
1555 /// Fails if id does not match an existing entry.
1556 pub fn upsert_tool_call_inner(
1557 &mut self,
1558 update: acp::ToolCallUpdate,
1559 status: ToolCallStatus,
1560 cx: &mut Context<Self>,
1561 ) -> Result<(), acp::Error> {
1562 let language_registry = self.project.read(cx).languages().clone();
1563 let path_style = self.project.read(cx).path_style(cx);
1564 let id = update.tool_call_id.clone();
1565
1566 let agent_telemetry_id = self.connection().telemetry_id();
1567 let session = self.session_id();
1568 let parent_session_id = self.parent_session_id();
1569 if let ToolCallStatus::Completed | ToolCallStatus::Failed = status {
1570 let status = if matches!(status, ToolCallStatus::Completed) {
1571 "completed"
1572 } else {
1573 "failed"
1574 };
1575 telemetry::event!(
1576 "Agent Tool Call Completed",
1577 agent_telemetry_id,
1578 session,
1579 parent_session_id,
1580 status
1581 );
1582 }
1583
1584 if let Some(ix) = self.index_for_tool_call(&id) {
1585 let AgentThreadEntry::ToolCall(call) = &mut self.entries[ix] else {
1586 unreachable!()
1587 };
1588
1589 call.update_fields(
1590 update.fields,
1591 update.meta,
1592 language_registry,
1593 path_style,
1594 &self.terminals,
1595 cx,
1596 )?;
1597 call.status = status;
1598
1599 cx.emit(AcpThreadEvent::EntryUpdated(ix));
1600 } else {
1601 let call = ToolCall::from_acp(
1602 update.try_into()?,
1603 status,
1604 language_registry,
1605 self.project.read(cx).path_style(cx),
1606 &self.terminals,
1607 cx,
1608 )?;
1609 self.push_entry(AgentThreadEntry::ToolCall(call), cx);
1610 };
1611
1612 self.resolve_locations(id, cx);
1613 Ok(())
1614 }
1615
1616 fn index_for_tool_call(&self, id: &acp::ToolCallId) -> Option<usize> {
1617 self.entries
1618 .iter()
1619 .enumerate()
1620 .rev()
1621 .find_map(|(index, entry)| {
1622 if let AgentThreadEntry::ToolCall(tool_call) = entry
1623 && &tool_call.id == id
1624 {
1625 Some(index)
1626 } else {
1627 None
1628 }
1629 })
1630 }
1631
1632 fn tool_call_mut(&mut self, id: &acp::ToolCallId) -> Option<(usize, &mut ToolCall)> {
1633 // The tool call we are looking for is typically the last one, or very close to the end.
1634 // At the moment, it doesn't seem like a hashmap would be a good fit for this use case.
1635 self.entries
1636 .iter_mut()
1637 .enumerate()
1638 .rev()
1639 .find_map(|(index, tool_call)| {
1640 if let AgentThreadEntry::ToolCall(tool_call) = tool_call
1641 && &tool_call.id == id
1642 {
1643 Some((index, tool_call))
1644 } else {
1645 None
1646 }
1647 })
1648 }
1649
1650 pub fn tool_call(&self, id: &acp::ToolCallId) -> Option<(usize, &ToolCall)> {
1651 self.entries
1652 .iter()
1653 .enumerate()
1654 .rev()
1655 .find_map(|(index, tool_call)| {
1656 if let AgentThreadEntry::ToolCall(tool_call) = tool_call
1657 && &tool_call.id == id
1658 {
1659 Some((index, tool_call))
1660 } else {
1661 None
1662 }
1663 })
1664 }
1665
1666 pub fn tool_call_for_subagent(&self, session_id: &acp::SessionId) -> Option<&ToolCall> {
1667 self.entries.iter().find_map(|entry| match entry {
1668 AgentThreadEntry::ToolCall(tool_call) => {
1669 if let Some(subagent_session_info) = &tool_call.subagent_session_info
1670 && &subagent_session_info.session_id == session_id
1671 {
1672 Some(tool_call)
1673 } else {
1674 None
1675 }
1676 }
1677 _ => None,
1678 })
1679 }
1680
1681 pub fn resolve_locations(&mut self, id: acp::ToolCallId, cx: &mut Context<Self>) {
1682 let project = self.project.clone();
1683 let should_update_agent_location = self.parent_session_id.is_none();
1684 let Some((_, tool_call)) = self.tool_call_mut(&id) else {
1685 return;
1686 };
1687 let task = tool_call.resolve_locations(project, cx);
1688 cx.spawn(async move |this, cx| {
1689 let resolved_locations = task.await;
1690
1691 this.update(cx, |this, cx| {
1692 let project = this.project.clone();
1693
1694 for location in resolved_locations.iter().flatten() {
1695 this.shared_buffers
1696 .insert(location.buffer.clone(), location.buffer.read(cx).snapshot());
1697 }
1698 let Some((ix, tool_call)) = this.tool_call_mut(&id) else {
1699 return;
1700 };
1701
1702 if let Some(Some(location)) = resolved_locations.last() {
1703 project.update(cx, |project, cx| {
1704 let should_ignore = if let Some(agent_location) = project
1705 .agent_location()
1706 .filter(|agent_location| agent_location.buffer == location.buffer)
1707 {
1708 let snapshot = location.buffer.read(cx).snapshot();
1709 let old_position = agent_location.position.to_point(&snapshot);
1710 let new_position = location.position.to_point(&snapshot);
1711
1712 // ignore this so that when we get updates from the edit tool
1713 // the position doesn't reset to the startof line
1714 old_position.row == new_position.row
1715 && old_position.column > new_position.column
1716 } else {
1717 false
1718 };
1719 if !should_ignore && should_update_agent_location {
1720 project.set_agent_location(Some(location.into()), cx);
1721 }
1722 });
1723 }
1724
1725 let resolved_locations = resolved_locations
1726 .iter()
1727 .map(|l| l.as_ref().map(|l| AgentLocation::from(l)))
1728 .collect::<Vec<_>>();
1729
1730 if tool_call.resolved_locations != resolved_locations {
1731 tool_call.resolved_locations = resolved_locations;
1732 cx.emit(AcpThreadEvent::EntryUpdated(ix));
1733 }
1734 })
1735 })
1736 .detach();
1737 }
1738
1739 pub fn request_tool_call_authorization(
1740 &mut self,
1741 tool_call: acp::ToolCallUpdate,
1742 options: PermissionOptions,
1743 cx: &mut Context<Self>,
1744 ) -> Result<Task<acp::RequestPermissionOutcome>> {
1745 let (tx, rx) = oneshot::channel();
1746
1747 let status = ToolCallStatus::WaitingForConfirmation {
1748 options,
1749 respond_tx: tx,
1750 };
1751
1752 let tool_call_id = tool_call.tool_call_id.clone();
1753 self.upsert_tool_call_inner(tool_call, status, cx)?;
1754 cx.emit(AcpThreadEvent::ToolAuthorizationRequested(
1755 tool_call_id.clone(),
1756 ));
1757
1758 Ok(cx.spawn(async move |this, cx| {
1759 let outcome = match rx.await {
1760 Ok(option) => acp::RequestPermissionOutcome::Selected(
1761 acp::SelectedPermissionOutcome::new(option),
1762 ),
1763 Err(oneshot::Canceled) => acp::RequestPermissionOutcome::Cancelled,
1764 };
1765 this.update(cx, |_this, cx| {
1766 cx.emit(AcpThreadEvent::ToolAuthorizationReceived(tool_call_id))
1767 })
1768 .ok();
1769 outcome
1770 }))
1771 }
1772
1773 pub fn authorize_tool_call(
1774 &mut self,
1775 id: acp::ToolCallId,
1776 option_id: acp::PermissionOptionId,
1777 option_kind: acp::PermissionOptionKind,
1778 cx: &mut Context<Self>,
1779 ) {
1780 let Some((ix, call)) = self.tool_call_mut(&id) else {
1781 return;
1782 };
1783
1784 let new_status = match option_kind {
1785 acp::PermissionOptionKind::RejectOnce | acp::PermissionOptionKind::RejectAlways => {
1786 ToolCallStatus::Rejected
1787 }
1788 acp::PermissionOptionKind::AllowOnce | acp::PermissionOptionKind::AllowAlways => {
1789 ToolCallStatus::InProgress
1790 }
1791 _ => ToolCallStatus::InProgress,
1792 };
1793
1794 let curr_status = mem::replace(&mut call.status, new_status);
1795
1796 if let ToolCallStatus::WaitingForConfirmation { respond_tx, .. } = curr_status {
1797 respond_tx.send(option_id).log_err();
1798 } else if cfg!(debug_assertions) {
1799 panic!("tried to authorize an already authorized tool call");
1800 }
1801
1802 cx.emit(AcpThreadEvent::EntryUpdated(ix));
1803 }
1804
1805 pub fn plan(&self) -> &Plan {
1806 &self.plan
1807 }
1808
1809 pub fn update_plan(&mut self, request: acp::Plan, cx: &mut Context<Self>) {
1810 let new_entries_len = request.entries.len();
1811 let mut new_entries = request.entries.into_iter();
1812
1813 // Reuse existing markdown to prevent flickering
1814 for (old, new) in self.plan.entries.iter_mut().zip(new_entries.by_ref()) {
1815 let PlanEntry {
1816 content,
1817 priority,
1818 status,
1819 } = old;
1820 content.update(cx, |old, cx| {
1821 old.replace(new.content, cx);
1822 });
1823 *priority = new.priority;
1824 *status = new.status;
1825 }
1826 for new in new_entries {
1827 self.plan.entries.push(PlanEntry::from_acp(new, cx))
1828 }
1829 self.plan.entries.truncate(new_entries_len);
1830
1831 cx.notify();
1832 }
1833
1834 fn clear_completed_plan_entries(&mut self, cx: &mut Context<Self>) {
1835 self.plan
1836 .entries
1837 .retain(|entry| !matches!(entry.status, acp::PlanEntryStatus::Completed));
1838 cx.notify();
1839 }
1840
1841 #[cfg(any(test, feature = "test-support"))]
1842 pub fn send_raw(
1843 &mut self,
1844 message: &str,
1845 cx: &mut Context<Self>,
1846 ) -> BoxFuture<'static, Result<Option<acp::PromptResponse>>> {
1847 self.send(vec![message.into()], cx)
1848 }
1849
1850 pub fn send(
1851 &mut self,
1852 message: Vec<acp::ContentBlock>,
1853 cx: &mut Context<Self>,
1854 ) -> BoxFuture<'static, Result<Option<acp::PromptResponse>>> {
1855 let block = ContentBlock::new_combined(
1856 message.clone(),
1857 self.project.read(cx).languages().clone(),
1858 self.project.read(cx).path_style(cx),
1859 cx,
1860 );
1861 let request = acp::PromptRequest::new(self.session_id.clone(), message.clone());
1862 let git_store = self.project.read(cx).git_store().clone();
1863
1864 let message_id = if self.connection.truncate(&self.session_id, cx).is_some() {
1865 Some(UserMessageId::new())
1866 } else {
1867 None
1868 };
1869
1870 self.run_turn(cx, async move |this, cx| {
1871 this.update(cx, |this, cx| {
1872 this.push_entry(
1873 AgentThreadEntry::UserMessage(UserMessage {
1874 id: message_id.clone(),
1875 content: block,
1876 chunks: message,
1877 checkpoint: None,
1878 indented: false,
1879 }),
1880 cx,
1881 );
1882 })
1883 .ok();
1884
1885 let old_checkpoint = git_store
1886 .update(cx, |git, cx| git.checkpoint(cx))
1887 .await
1888 .context("failed to get old checkpoint")
1889 .log_err();
1890 this.update(cx, |this, cx| {
1891 if let Some((_ix, message)) = this.last_user_message() {
1892 message.checkpoint = old_checkpoint.map(|git_checkpoint| Checkpoint {
1893 git_checkpoint,
1894 show: false,
1895 });
1896 }
1897 this.connection.prompt(message_id, request, cx)
1898 })?
1899 .await
1900 })
1901 }
1902
1903 pub fn can_retry(&self, cx: &App) -> bool {
1904 self.connection.retry(&self.session_id, cx).is_some()
1905 }
1906
1907 pub fn retry(
1908 &mut self,
1909 cx: &mut Context<Self>,
1910 ) -> BoxFuture<'static, Result<Option<acp::PromptResponse>>> {
1911 self.run_turn(cx, async move |this, cx| {
1912 this.update(cx, |this, cx| {
1913 this.connection
1914 .retry(&this.session_id, cx)
1915 .map(|retry| retry.run(cx))
1916 })?
1917 .context("retrying a session is not supported")?
1918 .await
1919 })
1920 }
1921
1922 fn run_turn(
1923 &mut self,
1924 cx: &mut Context<Self>,
1925 f: impl 'static + AsyncFnOnce(WeakEntity<Self>, &mut AsyncApp) -> Result<acp::PromptResponse>,
1926 ) -> BoxFuture<'static, Result<Option<acp::PromptResponse>>> {
1927 self.clear_completed_plan_entries(cx);
1928 self.had_error = false;
1929
1930 let (tx, rx) = oneshot::channel();
1931 let cancel_task = self.cancel(cx);
1932
1933 self.turn_id += 1;
1934 let turn_id = self.turn_id;
1935 self.running_turn = Some(RunningTurn {
1936 id: turn_id,
1937 send_task: cx.spawn(async move |this, cx| {
1938 cancel_task.await;
1939 tx.send(f(this, cx).await).ok();
1940 }),
1941 });
1942
1943 cx.spawn(async move |this, cx| {
1944 let response = rx.await;
1945
1946 this.update(cx, |this, cx| this.update_last_checkpoint(cx))?
1947 .await?;
1948
1949 this.update(cx, |this, cx| {
1950 if this.parent_session_id.is_none() {
1951 this.project
1952 .update(cx, |project, cx| project.set_agent_location(None, cx));
1953 }
1954 let Ok(response) = response else {
1955 // tx dropped, just return
1956 return Ok(None);
1957 };
1958
1959 let is_same_turn = this
1960 .running_turn
1961 .as_ref()
1962 .is_some_and(|turn| turn_id == turn.id);
1963
1964 // If the user submitted a follow up message, running_turn might
1965 // already point to a different turn. Therefore we only want to
1966 // take the task if it's the same turn.
1967 if is_same_turn {
1968 this.running_turn.take();
1969 }
1970
1971 match response {
1972 Ok(r) => {
1973 if r.stop_reason == acp::StopReason::MaxTokens {
1974 this.had_error = true;
1975 cx.emit(AcpThreadEvent::Error);
1976 log::error!("Max tokens reached. Usage: {:?}", this.token_usage);
1977 return Err(anyhow!("Max tokens reached"));
1978 }
1979
1980 let canceled = matches!(r.stop_reason, acp::StopReason::Cancelled);
1981 if canceled {
1982 this.mark_pending_tools_as_canceled();
1983 }
1984
1985 // Handle refusal - distinguish between user prompt and tool call refusals
1986 if let acp::StopReason::Refusal = r.stop_reason {
1987 this.had_error = true;
1988 if let Some((user_msg_ix, _)) = this.last_user_message() {
1989 // Check if there's a completed tool call with results after the last user message
1990 // This indicates the refusal is in response to tool output, not the user's prompt
1991 let has_completed_tool_call_after_user_msg =
1992 this.entries.iter().skip(user_msg_ix + 1).any(|entry| {
1993 if let AgentThreadEntry::ToolCall(tool_call) = entry {
1994 // Check if the tool call has completed and has output
1995 matches!(tool_call.status, ToolCallStatus::Completed)
1996 && tool_call.raw_output.is_some()
1997 } else {
1998 false
1999 }
2000 });
2001
2002 if has_completed_tool_call_after_user_msg {
2003 // Refusal is due to tool output - don't truncate, just notify
2004 // The model refused based on what the tool returned
2005 cx.emit(AcpThreadEvent::Refusal);
2006 } else {
2007 // User prompt was refused - truncate back to before the user message
2008 let range = user_msg_ix..this.entries.len();
2009 if range.start < range.end {
2010 this.entries.truncate(user_msg_ix);
2011 cx.emit(AcpThreadEvent::EntriesRemoved(range));
2012 }
2013 cx.emit(AcpThreadEvent::Refusal);
2014 }
2015 } else {
2016 // No user message found, treat as general refusal
2017 cx.emit(AcpThreadEvent::Refusal);
2018 }
2019 }
2020
2021 cx.emit(AcpThreadEvent::Stopped(r.stop_reason));
2022 Ok(Some(r))
2023 }
2024 Err(e) => {
2025 this.had_error = true;
2026 cx.emit(AcpThreadEvent::Error);
2027 log::error!("Error in run turn: {:?}", e);
2028 Err(e)
2029 }
2030 }
2031 })?
2032 })
2033 .boxed()
2034 }
2035
2036 pub fn cancel(&mut self, cx: &mut Context<Self>) -> Task<()> {
2037 let Some(turn) = self.running_turn.take() else {
2038 return Task::ready(());
2039 };
2040 self.connection.cancel(&self.session_id, cx);
2041
2042 self.mark_pending_tools_as_canceled();
2043
2044 // Wait for the send task to complete
2045 cx.background_spawn(turn.send_task)
2046 }
2047
2048 fn mark_pending_tools_as_canceled(&mut self) {
2049 for entry in self.entries.iter_mut() {
2050 if let AgentThreadEntry::ToolCall(call) = entry {
2051 let cancel = matches!(
2052 call.status,
2053 ToolCallStatus::Pending
2054 | ToolCallStatus::WaitingForConfirmation { .. }
2055 | ToolCallStatus::InProgress
2056 );
2057
2058 if cancel {
2059 call.status = ToolCallStatus::Canceled;
2060 }
2061 }
2062 }
2063 }
2064
2065 /// Restores the git working tree to the state at the given checkpoint (if one exists)
2066 pub fn restore_checkpoint(
2067 &mut self,
2068 id: UserMessageId,
2069 cx: &mut Context<Self>,
2070 ) -> Task<Result<()>> {
2071 let Some((_, message)) = self.user_message_mut(&id) else {
2072 return Task::ready(Err(anyhow!("message not found")));
2073 };
2074
2075 let checkpoint = message
2076 .checkpoint
2077 .as_ref()
2078 .map(|c| c.git_checkpoint.clone());
2079
2080 // Cancel any in-progress generation before restoring
2081 let cancel_task = self.cancel(cx);
2082 let rewind = self.rewind(id.clone(), cx);
2083 let git_store = self.project.read(cx).git_store().clone();
2084
2085 cx.spawn(async move |_, cx| {
2086 cancel_task.await;
2087 rewind.await?;
2088 if let Some(checkpoint) = checkpoint {
2089 git_store
2090 .update(cx, |git, cx| git.restore_checkpoint(checkpoint, cx))
2091 .await?;
2092 }
2093
2094 Ok(())
2095 })
2096 }
2097
2098 /// Rewinds this thread to before the entry at `index`, removing it and all
2099 /// subsequent entries while rejecting any action_log changes made from that point.
2100 /// Unlike `restore_checkpoint`, this method does not restore from git.
2101 pub fn rewind(&mut self, id: UserMessageId, cx: &mut Context<Self>) -> Task<Result<()>> {
2102 let Some(truncate) = self.connection.truncate(&self.session_id, cx) else {
2103 return Task::ready(Err(anyhow!("not supported")));
2104 };
2105
2106 let telemetry = ActionLogTelemetry::from(&*self);
2107 cx.spawn(async move |this, cx| {
2108 cx.update(|cx| truncate.run(id.clone(), cx)).await?;
2109 this.update(cx, |this, cx| {
2110 if let Some((ix, _)) = this.user_message_mut(&id) {
2111 // Collect all terminals from entries that will be removed
2112 let terminals_to_remove: Vec<acp::TerminalId> = this.entries[ix..]
2113 .iter()
2114 .flat_map(|entry| entry.terminals())
2115 .filter_map(|terminal| terminal.read(cx).id().clone().into())
2116 .collect();
2117
2118 let range = ix..this.entries.len();
2119 this.entries.truncate(ix);
2120 cx.emit(AcpThreadEvent::EntriesRemoved(range));
2121
2122 // Kill and remove the terminals
2123 for terminal_id in terminals_to_remove {
2124 if let Some(terminal) = this.terminals.remove(&terminal_id) {
2125 terminal.update(cx, |terminal, cx| {
2126 terminal.kill(cx);
2127 });
2128 }
2129 }
2130 }
2131 this.action_log().update(cx, |action_log, cx| {
2132 action_log.reject_all_edits(Some(telemetry), cx)
2133 })
2134 })?
2135 .await;
2136 Ok(())
2137 })
2138 }
2139
2140 fn update_last_checkpoint(&mut self, cx: &mut Context<Self>) -> Task<Result<()>> {
2141 let git_store = self.project.read(cx).git_store().clone();
2142
2143 let Some((_, message)) = self.last_user_message() else {
2144 return Task::ready(Ok(()));
2145 };
2146 let Some(user_message_id) = message.id.clone() else {
2147 return Task::ready(Ok(()));
2148 };
2149 let Some(checkpoint) = message.checkpoint.as_ref() else {
2150 return Task::ready(Ok(()));
2151 };
2152 let old_checkpoint = checkpoint.git_checkpoint.clone();
2153
2154 let new_checkpoint = git_store.update(cx, |git, cx| git.checkpoint(cx));
2155 cx.spawn(async move |this, cx| {
2156 let Some(new_checkpoint) = new_checkpoint
2157 .await
2158 .context("failed to get new checkpoint")
2159 .log_err()
2160 else {
2161 return Ok(());
2162 };
2163
2164 let equal = git_store
2165 .update(cx, |git, cx| {
2166 git.compare_checkpoints(old_checkpoint.clone(), new_checkpoint, cx)
2167 })
2168 .await
2169 .unwrap_or(true);
2170
2171 this.update(cx, |this, cx| {
2172 if let Some((ix, message)) = this.user_message_mut(&user_message_id) {
2173 if let Some(checkpoint) = message.checkpoint.as_mut() {
2174 checkpoint.show = !equal;
2175 cx.emit(AcpThreadEvent::EntryUpdated(ix));
2176 }
2177 }
2178 })?;
2179
2180 Ok(())
2181 })
2182 }
2183
2184 fn last_user_message(&mut self) -> Option<(usize, &mut UserMessage)> {
2185 self.entries
2186 .iter_mut()
2187 .enumerate()
2188 .rev()
2189 .find_map(|(ix, entry)| {
2190 if let AgentThreadEntry::UserMessage(message) = entry {
2191 Some((ix, message))
2192 } else {
2193 None
2194 }
2195 })
2196 }
2197
2198 fn user_message_mut(&mut self, id: &UserMessageId) -> Option<(usize, &mut UserMessage)> {
2199 self.entries.iter_mut().enumerate().find_map(|(ix, entry)| {
2200 if let AgentThreadEntry::UserMessage(message) = entry {
2201 if message.id.as_ref() == Some(id) {
2202 Some((ix, message))
2203 } else {
2204 None
2205 }
2206 } else {
2207 None
2208 }
2209 })
2210 }
2211
2212 pub fn read_text_file(
2213 &self,
2214 path: PathBuf,
2215 line: Option<u32>,
2216 limit: Option<u32>,
2217 reuse_shared_snapshot: bool,
2218 cx: &mut Context<Self>,
2219 ) -> Task<Result<String, acp::Error>> {
2220 // Args are 1-based, move to 0-based
2221 let line = line.unwrap_or_default().saturating_sub(1);
2222 let limit = limit.unwrap_or(u32::MAX);
2223 let project = self.project.clone();
2224 let action_log = self.action_log.clone();
2225 let should_update_agent_location = self.parent_session_id.is_none();
2226 cx.spawn(async move |this, cx| {
2227 let load = project.update(cx, |project, cx| {
2228 let path = project
2229 .project_path_for_absolute_path(&path, cx)
2230 .ok_or_else(|| {
2231 acp::Error::resource_not_found(Some(path.display().to_string()))
2232 })?;
2233 Ok::<_, acp::Error>(project.open_buffer(path, cx))
2234 })?;
2235
2236 let buffer = load.await?;
2237
2238 let snapshot = if reuse_shared_snapshot {
2239 this.read_with(cx, |this, _| {
2240 this.shared_buffers.get(&buffer.clone()).cloned()
2241 })
2242 .log_err()
2243 .flatten()
2244 } else {
2245 None
2246 };
2247
2248 let snapshot = if let Some(snapshot) = snapshot {
2249 snapshot
2250 } else {
2251 action_log.update(cx, |action_log, cx| {
2252 action_log.buffer_read(buffer.clone(), cx);
2253 });
2254
2255 let snapshot = buffer.update(cx, |buffer, _| buffer.snapshot());
2256 this.update(cx, |this, _| {
2257 this.shared_buffers.insert(buffer.clone(), snapshot.clone());
2258 })?;
2259 snapshot
2260 };
2261
2262 let max_point = snapshot.max_point();
2263 let start_position = Point::new(line, 0);
2264
2265 if start_position > max_point {
2266 return Err(acp::Error::invalid_params().data(format!(
2267 "Attempting to read beyond the end of the file, line {}:{}",
2268 max_point.row + 1,
2269 max_point.column
2270 )));
2271 }
2272
2273 let start = snapshot.anchor_before(start_position);
2274 let end = snapshot.anchor_before(Point::new(line.saturating_add(limit), 0));
2275
2276 if should_update_agent_location {
2277 project.update(cx, |project, cx| {
2278 project.set_agent_location(
2279 Some(AgentLocation {
2280 buffer: buffer.downgrade(),
2281 position: start,
2282 }),
2283 cx,
2284 );
2285 });
2286 }
2287
2288 Ok(snapshot.text_for_range(start..end).collect::<String>())
2289 })
2290 }
2291
2292 pub fn write_text_file(
2293 &self,
2294 path: PathBuf,
2295 content: String,
2296 cx: &mut Context<Self>,
2297 ) -> Task<Result<()>> {
2298 let project = self.project.clone();
2299 let action_log = self.action_log.clone();
2300 let should_update_agent_location = self.parent_session_id.is_none();
2301 cx.spawn(async move |this, cx| {
2302 let load = project.update(cx, |project, cx| {
2303 let path = project
2304 .project_path_for_absolute_path(&path, cx)
2305 .context("invalid path")?;
2306 anyhow::Ok(project.open_buffer(path, cx))
2307 });
2308 let buffer = load?.await?;
2309 let snapshot = this.update(cx, |this, cx| {
2310 this.shared_buffers
2311 .get(&buffer)
2312 .cloned()
2313 .unwrap_or_else(|| buffer.read(cx).snapshot())
2314 })?;
2315 let edits = cx
2316 .background_executor()
2317 .spawn(async move {
2318 let old_text = snapshot.text();
2319 text_diff(old_text.as_str(), &content)
2320 .into_iter()
2321 .map(|(range, replacement)| {
2322 (snapshot.anchor_range_around(range), replacement)
2323 })
2324 .collect::<Vec<_>>()
2325 })
2326 .await;
2327
2328 if should_update_agent_location {
2329 project.update(cx, |project, cx| {
2330 project.set_agent_location(
2331 Some(AgentLocation {
2332 buffer: buffer.downgrade(),
2333 position: edits
2334 .last()
2335 .map(|(range, _)| range.end)
2336 .unwrap_or(Anchor::min_for_buffer(buffer.read(cx).remote_id())),
2337 }),
2338 cx,
2339 );
2340 });
2341 }
2342
2343 let format_on_save = cx.update(|cx| {
2344 action_log.update(cx, |action_log, cx| {
2345 action_log.buffer_read(buffer.clone(), cx);
2346 });
2347
2348 let format_on_save = buffer.update(cx, |buffer, cx| {
2349 buffer.edit(edits, None, cx);
2350
2351 let settings =
2352 language::language_settings::LanguageSettings::for_buffer(buffer, cx);
2353
2354 settings.format_on_save != FormatOnSave::Off
2355 });
2356 action_log.update(cx, |action_log, cx| {
2357 action_log.buffer_edited(buffer.clone(), cx);
2358 });
2359 format_on_save
2360 });
2361
2362 if format_on_save {
2363 let format_task = project.update(cx, |project, cx| {
2364 project.format(
2365 HashSet::from_iter([buffer.clone()]),
2366 LspFormatTarget::Buffers,
2367 false,
2368 FormatTrigger::Save,
2369 cx,
2370 )
2371 });
2372 format_task.await.log_err();
2373
2374 action_log.update(cx, |action_log, cx| {
2375 action_log.buffer_edited(buffer.clone(), cx);
2376 });
2377 }
2378
2379 project
2380 .update(cx, |project, cx| project.save_buffer(buffer, cx))
2381 .await
2382 })
2383 }
2384
2385 pub fn create_terminal(
2386 &self,
2387 command: String,
2388 args: Vec<String>,
2389 extra_env: Vec<acp::EnvVariable>,
2390 cwd: Option<PathBuf>,
2391 output_byte_limit: Option<u64>,
2392 cx: &mut Context<Self>,
2393 ) -> Task<Result<Entity<Terminal>>> {
2394 let env = match &cwd {
2395 Some(dir) => self.project.update(cx, |project, cx| {
2396 project.environment().update(cx, |env, cx| {
2397 env.directory_environment(dir.as_path().into(), cx)
2398 })
2399 }),
2400 None => Task::ready(None).shared(),
2401 };
2402 let env = cx.spawn(async move |_, _| {
2403 let mut env = env.await.unwrap_or_default();
2404 // Disables paging for `git` and hopefully other commands
2405 env.insert("PAGER".into(), "".into());
2406 for var in extra_env {
2407 env.insert(var.name, var.value);
2408 }
2409 env
2410 });
2411
2412 let project = self.project.clone();
2413 let language_registry = project.read(cx).languages().clone();
2414 let is_windows = project.read(cx).path_style(cx).is_windows();
2415
2416 let terminal_id = acp::TerminalId::new(Uuid::new_v4().to_string());
2417 let terminal_task = cx.spawn({
2418 let terminal_id = terminal_id.clone();
2419 async move |_this, cx| {
2420 let env = env.await;
2421 let shell = project
2422 .update(cx, |project, cx| {
2423 project
2424 .remote_client()
2425 .and_then(|r| r.read(cx).default_system_shell())
2426 })
2427 .unwrap_or_else(|| get_default_system_shell_preferring_bash());
2428 let (task_command, task_args) =
2429 ShellBuilder::new(&Shell::Program(shell), is_windows)
2430 .redirect_stdin_to_dev_null()
2431 .build(Some(command.clone()), &args);
2432 let terminal = project
2433 .update(cx, |project, cx| {
2434 project.create_terminal_task(
2435 task::SpawnInTerminal {
2436 command: Some(task_command),
2437 args: task_args,
2438 cwd: cwd.clone(),
2439 env,
2440 ..Default::default()
2441 },
2442 cx,
2443 )
2444 })
2445 .await?;
2446
2447 anyhow::Ok(cx.new(|cx| {
2448 Terminal::new(
2449 terminal_id,
2450 &format!("{} {}", command, args.join(" ")),
2451 cwd,
2452 output_byte_limit.map(|l| l as usize),
2453 terminal,
2454 language_registry,
2455 cx,
2456 )
2457 }))
2458 }
2459 });
2460
2461 cx.spawn(async move |this, cx| {
2462 let terminal = terminal_task.await?;
2463 this.update(cx, |this, _cx| {
2464 this.terminals.insert(terminal_id, terminal.clone());
2465 terminal
2466 })
2467 })
2468 }
2469
2470 pub fn kill_terminal(
2471 &mut self,
2472 terminal_id: acp::TerminalId,
2473 cx: &mut Context<Self>,
2474 ) -> Result<()> {
2475 self.terminals
2476 .get(&terminal_id)
2477 .context("Terminal not found")?
2478 .update(cx, |terminal, cx| {
2479 terminal.kill(cx);
2480 });
2481
2482 Ok(())
2483 }
2484
2485 pub fn release_terminal(
2486 &mut self,
2487 terminal_id: acp::TerminalId,
2488 cx: &mut Context<Self>,
2489 ) -> Result<()> {
2490 self.terminals
2491 .remove(&terminal_id)
2492 .context("Terminal not found")?
2493 .update(cx, |terminal, cx| {
2494 terminal.kill(cx);
2495 });
2496
2497 Ok(())
2498 }
2499
2500 pub fn terminal(&self, terminal_id: acp::TerminalId) -> Result<Entity<Terminal>> {
2501 self.terminals
2502 .get(&terminal_id)
2503 .context("Terminal not found")
2504 .cloned()
2505 }
2506
2507 pub fn to_markdown(&self, cx: &App) -> String {
2508 self.entries.iter().map(|e| e.to_markdown(cx)).collect()
2509 }
2510
2511 pub fn emit_load_error(&mut self, error: LoadError, cx: &mut Context<Self>) {
2512 cx.emit(AcpThreadEvent::LoadError(error));
2513 }
2514
2515 pub fn register_terminal_created(
2516 &mut self,
2517 terminal_id: acp::TerminalId,
2518 command_label: String,
2519 working_dir: Option<PathBuf>,
2520 output_byte_limit: Option<u64>,
2521 terminal: Entity<::terminal::Terminal>,
2522 cx: &mut Context<Self>,
2523 ) -> Entity<Terminal> {
2524 let language_registry = self.project.read(cx).languages().clone();
2525
2526 let entity = cx.new(|cx| {
2527 Terminal::new(
2528 terminal_id.clone(),
2529 &command_label,
2530 working_dir.clone(),
2531 output_byte_limit.map(|l| l as usize),
2532 terminal,
2533 language_registry,
2534 cx,
2535 )
2536 });
2537 self.terminals.insert(terminal_id.clone(), entity.clone());
2538 entity
2539 }
2540
2541 pub fn mark_as_subagent_output(&mut self, cx: &mut Context<Self>) {
2542 for entry in self.entries.iter_mut().rev() {
2543 if let AgentThreadEntry::AssistantMessage(assistant_message) = entry {
2544 assistant_message.is_subagent_output = true;
2545 cx.notify();
2546 return;
2547 }
2548 }
2549 }
2550
2551 pub fn on_terminal_provider_event(
2552 &mut self,
2553 event: TerminalProviderEvent,
2554 cx: &mut Context<Self>,
2555 ) {
2556 match event {
2557 TerminalProviderEvent::Created {
2558 terminal_id,
2559 label,
2560 cwd,
2561 output_byte_limit,
2562 terminal,
2563 } => {
2564 let entity = self.register_terminal_created(
2565 terminal_id.clone(),
2566 label,
2567 cwd,
2568 output_byte_limit,
2569 terminal,
2570 cx,
2571 );
2572
2573 if let Some(mut chunks) = self.pending_terminal_output.remove(&terminal_id) {
2574 for data in chunks.drain(..) {
2575 entity.update(cx, |term, cx| {
2576 term.inner().update(cx, |inner, cx| {
2577 inner.write_output(&data, cx);
2578 })
2579 });
2580 }
2581 }
2582
2583 if let Some(_status) = self.pending_terminal_exit.remove(&terminal_id) {
2584 entity.update(cx, |_term, cx| {
2585 cx.notify();
2586 });
2587 }
2588
2589 cx.notify();
2590 }
2591 TerminalProviderEvent::Output { terminal_id, data } => {
2592 if let Some(entity) = self.terminals.get(&terminal_id) {
2593 entity.update(cx, |term, cx| {
2594 term.inner().update(cx, |inner, cx| {
2595 inner.write_output(&data, cx);
2596 })
2597 });
2598 } else {
2599 self.pending_terminal_output
2600 .entry(terminal_id)
2601 .or_default()
2602 .push(data);
2603 }
2604 }
2605 TerminalProviderEvent::TitleChanged { terminal_id, title } => {
2606 if let Some(entity) = self.terminals.get(&terminal_id) {
2607 entity.update(cx, |term, cx| {
2608 term.inner().update(cx, |inner, cx| {
2609 inner.breadcrumb_text = title;
2610 cx.emit(::terminal::Event::BreadcrumbsChanged);
2611 })
2612 });
2613 }
2614 }
2615 TerminalProviderEvent::Exit {
2616 terminal_id,
2617 status,
2618 } => {
2619 if let Some(entity) = self.terminals.get(&terminal_id) {
2620 entity.update(cx, |_term, cx| {
2621 cx.notify();
2622 });
2623 } else {
2624 self.pending_terminal_exit.insert(terminal_id, status);
2625 }
2626 }
2627 }
2628 }
2629}
2630
2631fn markdown_for_raw_output(
2632 raw_output: &serde_json::Value,
2633 language_registry: &Arc<LanguageRegistry>,
2634 cx: &mut App,
2635) -> Option<Entity<Markdown>> {
2636 match raw_output {
2637 serde_json::Value::Null => None,
2638 serde_json::Value::Bool(value) => Some(cx.new(|cx| {
2639 Markdown::new(
2640 value.to_string().into(),
2641 Some(language_registry.clone()),
2642 None,
2643 cx,
2644 )
2645 })),
2646 serde_json::Value::Number(value) => Some(cx.new(|cx| {
2647 Markdown::new(
2648 value.to_string().into(),
2649 Some(language_registry.clone()),
2650 None,
2651 cx,
2652 )
2653 })),
2654 serde_json::Value::String(value) => Some(cx.new(|cx| {
2655 Markdown::new(
2656 value.clone().into(),
2657 Some(language_registry.clone()),
2658 None,
2659 cx,
2660 )
2661 })),
2662 value => Some(cx.new(|cx| {
2663 let pretty_json = to_string_pretty(value).unwrap_or_else(|_| value.to_string());
2664
2665 Markdown::new(
2666 format!("```json\n{}\n```", pretty_json).into(),
2667 Some(language_registry.clone()),
2668 None,
2669 cx,
2670 )
2671 })),
2672 }
2673}
2674
2675#[cfg(test)]
2676mod tests {
2677 use super::*;
2678 use anyhow::anyhow;
2679 use futures::{channel::mpsc, future::LocalBoxFuture, select};
2680 use gpui::{App, AsyncApp, TestAppContext, WeakEntity};
2681 use indoc::indoc;
2682 use project::{FakeFs, Fs};
2683 use rand::{distr, prelude::*};
2684 use serde_json::json;
2685 use settings::SettingsStore;
2686 use smol::stream::StreamExt as _;
2687 use std::{
2688 any::Any,
2689 cell::RefCell,
2690 path::Path,
2691 rc::Rc,
2692 sync::atomic::{AtomicBool, AtomicUsize, Ordering::SeqCst},
2693 time::Duration,
2694 };
2695 use util::path;
2696
2697 fn init_test(cx: &mut TestAppContext) {
2698 env_logger::try_init().ok();
2699 cx.update(|cx| {
2700 let settings_store = SettingsStore::test(cx);
2701 cx.set_global(settings_store);
2702 });
2703 }
2704
2705 #[gpui::test]
2706 async fn test_terminal_output_buffered_before_created_renders(cx: &mut gpui::TestAppContext) {
2707 init_test(cx);
2708
2709 let fs = FakeFs::new(cx.executor());
2710 let project = Project::test(fs, [], cx).await;
2711 let connection = Rc::new(FakeAgentConnection::new());
2712 let thread = cx
2713 .update(|cx| connection.new_session(project, std::path::Path::new(path!("/test")), cx))
2714 .await
2715 .unwrap();
2716
2717 let terminal_id = acp::TerminalId::new(uuid::Uuid::new_v4().to_string());
2718
2719 // Send Output BEFORE Created - should be buffered by acp_thread
2720 thread.update(cx, |thread, cx| {
2721 thread.on_terminal_provider_event(
2722 TerminalProviderEvent::Output {
2723 terminal_id: terminal_id.clone(),
2724 data: b"hello buffered".to_vec(),
2725 },
2726 cx,
2727 );
2728 });
2729
2730 // Create a display-only terminal and then send Created
2731 let lower = cx.new(|cx| {
2732 let builder = ::terminal::TerminalBuilder::new_display_only(
2733 ::terminal::terminal_settings::CursorShape::default(),
2734 ::terminal::terminal_settings::AlternateScroll::On,
2735 None,
2736 0,
2737 cx.background_executor(),
2738 PathStyle::local(),
2739 )
2740 .unwrap();
2741 builder.subscribe(cx)
2742 });
2743
2744 thread.update(cx, |thread, cx| {
2745 thread.on_terminal_provider_event(
2746 TerminalProviderEvent::Created {
2747 terminal_id: terminal_id.clone(),
2748 label: "Buffered Test".to_string(),
2749 cwd: None,
2750 output_byte_limit: None,
2751 terminal: lower.clone(),
2752 },
2753 cx,
2754 );
2755 });
2756
2757 // After Created, buffered Output should have been flushed into the renderer
2758 let content = thread.read_with(cx, |thread, cx| {
2759 let term = thread.terminal(terminal_id.clone()).unwrap();
2760 term.read_with(cx, |t, cx| t.inner().read(cx).get_content())
2761 });
2762
2763 assert!(
2764 content.contains("hello buffered"),
2765 "expected buffered output to render, got: {content}"
2766 );
2767 }
2768
2769 #[gpui::test]
2770 async fn test_terminal_output_and_exit_buffered_before_created(cx: &mut gpui::TestAppContext) {
2771 init_test(cx);
2772
2773 let fs = FakeFs::new(cx.executor());
2774 let project = Project::test(fs, [], cx).await;
2775 let connection = Rc::new(FakeAgentConnection::new());
2776 let thread = cx
2777 .update(|cx| connection.new_session(project, std::path::Path::new(path!("/test")), cx))
2778 .await
2779 .unwrap();
2780
2781 let terminal_id = acp::TerminalId::new(uuid::Uuid::new_v4().to_string());
2782
2783 // Send Output BEFORE Created
2784 thread.update(cx, |thread, cx| {
2785 thread.on_terminal_provider_event(
2786 TerminalProviderEvent::Output {
2787 terminal_id: terminal_id.clone(),
2788 data: b"pre-exit data".to_vec(),
2789 },
2790 cx,
2791 );
2792 });
2793
2794 // Send Exit BEFORE Created
2795 thread.update(cx, |thread, cx| {
2796 thread.on_terminal_provider_event(
2797 TerminalProviderEvent::Exit {
2798 terminal_id: terminal_id.clone(),
2799 status: acp::TerminalExitStatus::new().exit_code(0),
2800 },
2801 cx,
2802 );
2803 });
2804
2805 // Now create a display-only lower-level terminal and send Created
2806 let lower = cx.new(|cx| {
2807 let builder = ::terminal::TerminalBuilder::new_display_only(
2808 ::terminal::terminal_settings::CursorShape::default(),
2809 ::terminal::terminal_settings::AlternateScroll::On,
2810 None,
2811 0,
2812 cx.background_executor(),
2813 PathStyle::local(),
2814 )
2815 .unwrap();
2816 builder.subscribe(cx)
2817 });
2818
2819 thread.update(cx, |thread, cx| {
2820 thread.on_terminal_provider_event(
2821 TerminalProviderEvent::Created {
2822 terminal_id: terminal_id.clone(),
2823 label: "Buffered Exit Test".to_string(),
2824 cwd: None,
2825 output_byte_limit: None,
2826 terminal: lower.clone(),
2827 },
2828 cx,
2829 );
2830 });
2831
2832 // Output should be present after Created (flushed from buffer)
2833 let content = thread.read_with(cx, |thread, cx| {
2834 let term = thread.terminal(terminal_id.clone()).unwrap();
2835 term.read_with(cx, |t, cx| t.inner().read(cx).get_content())
2836 });
2837
2838 assert!(
2839 content.contains("pre-exit data"),
2840 "expected pre-exit data to render, got: {content}"
2841 );
2842 }
2843
2844 /// Test that killing a terminal via Terminal::kill properly:
2845 /// 1. Causes wait_for_exit to complete (doesn't hang forever)
2846 /// 2. The underlying terminal still has the output that was written before the kill
2847 ///
2848 /// This test verifies that the fix to kill_active_task (which now also kills
2849 /// the shell process in addition to the foreground process) properly allows
2850 /// wait_for_exit to complete instead of hanging indefinitely.
2851 #[cfg(unix)]
2852 #[gpui::test]
2853 async fn test_terminal_kill_allows_wait_for_exit_to_complete(cx: &mut gpui::TestAppContext) {
2854 use std::collections::HashMap;
2855 use task::Shell;
2856 use util::shell_builder::ShellBuilder;
2857
2858 init_test(cx);
2859 cx.executor().allow_parking();
2860
2861 let fs = FakeFs::new(cx.executor());
2862 let project = Project::test(fs, [], cx).await;
2863 let connection = Rc::new(FakeAgentConnection::new());
2864 let thread = cx
2865 .update(|cx| connection.new_session(project.clone(), Path::new(path!("/test")), cx))
2866 .await
2867 .unwrap();
2868
2869 let terminal_id = acp::TerminalId::new(uuid::Uuid::new_v4().to_string());
2870
2871 // Create a real PTY terminal that runs a command which prints output then sleeps
2872 // We use printf instead of echo and chain with && sleep to ensure proper execution
2873 let (completion_tx, _completion_rx) = smol::channel::unbounded();
2874 let (program, args) = ShellBuilder::new(&Shell::System, false).build(
2875 Some("printf 'output_before_kill\\n' && sleep 60".to_owned()),
2876 &[],
2877 );
2878
2879 let builder = cx
2880 .update(|cx| {
2881 ::terminal::TerminalBuilder::new(
2882 None,
2883 None,
2884 task::Shell::WithArguments {
2885 program,
2886 args,
2887 title_override: None,
2888 },
2889 HashMap::default(),
2890 ::terminal::terminal_settings::CursorShape::default(),
2891 ::terminal::terminal_settings::AlternateScroll::On,
2892 None,
2893 vec![],
2894 0,
2895 false,
2896 0,
2897 Some(completion_tx),
2898 cx,
2899 vec![],
2900 PathStyle::local(),
2901 )
2902 })
2903 .await
2904 .unwrap();
2905
2906 let lower_terminal = cx.new(|cx| builder.subscribe(cx));
2907
2908 // Create the acp_thread Terminal wrapper
2909 thread.update(cx, |thread, cx| {
2910 thread.on_terminal_provider_event(
2911 TerminalProviderEvent::Created {
2912 terminal_id: terminal_id.clone(),
2913 label: "printf output_before_kill && sleep 60".to_string(),
2914 cwd: None,
2915 output_byte_limit: None,
2916 terminal: lower_terminal.clone(),
2917 },
2918 cx,
2919 );
2920 });
2921
2922 // Wait for the printf command to execute and produce output
2923 // Use real time since parking is enabled
2924 cx.executor().timer(Duration::from_millis(500)).await;
2925
2926 // Get the acp_thread Terminal and kill it
2927 let wait_for_exit = thread.update(cx, |thread, cx| {
2928 let term = thread.terminals.get(&terminal_id).unwrap();
2929 let wait_for_exit = term.read(cx).wait_for_exit();
2930 term.update(cx, |term, cx| {
2931 term.kill(cx);
2932 });
2933 wait_for_exit
2934 });
2935
2936 // KEY ASSERTION: wait_for_exit should complete within a reasonable time (not hang).
2937 // Before the fix to kill_active_task, this would hang forever because
2938 // only the foreground process was killed, not the shell, so the PTY
2939 // child never exited and wait_for_completed_task never completed.
2940 let exit_result = futures::select! {
2941 result = futures::FutureExt::fuse(wait_for_exit) => Some(result),
2942 _ = futures::FutureExt::fuse(cx.background_executor.timer(Duration::from_secs(5))) => None,
2943 };
2944
2945 assert!(
2946 exit_result.is_some(),
2947 "wait_for_exit should complete after kill, but it timed out. \
2948 This indicates kill_active_task is not properly killing the shell process."
2949 );
2950
2951 // Give the system a chance to process any pending updates
2952 cx.run_until_parked();
2953
2954 // Verify that the underlying terminal still has the output that was
2955 // written before the kill. This verifies that killing doesn't lose output.
2956 let inner_content = thread.read_with(cx, |thread, cx| {
2957 let term = thread.terminals.get(&terminal_id).unwrap();
2958 term.read(cx).inner().read(cx).get_content()
2959 });
2960
2961 assert!(
2962 inner_content.contains("output_before_kill"),
2963 "Underlying terminal should contain output from before kill, got: {}",
2964 inner_content
2965 );
2966 }
2967
2968 #[gpui::test]
2969 async fn test_push_user_content_block(cx: &mut gpui::TestAppContext) {
2970 init_test(cx);
2971
2972 let fs = FakeFs::new(cx.executor());
2973 let project = Project::test(fs, [], cx).await;
2974 let connection = Rc::new(FakeAgentConnection::new());
2975 let thread = cx
2976 .update(|cx| connection.new_session(project, Path::new(path!("/test")), cx))
2977 .await
2978 .unwrap();
2979
2980 // Test creating a new user message
2981 thread.update(cx, |thread, cx| {
2982 thread.push_user_content_block(None, "Hello, ".into(), cx);
2983 });
2984
2985 thread.update(cx, |thread, cx| {
2986 assert_eq!(thread.entries.len(), 1);
2987 if let AgentThreadEntry::UserMessage(user_msg) = &thread.entries[0] {
2988 assert_eq!(user_msg.id, None);
2989 assert_eq!(user_msg.content.to_markdown(cx), "Hello, ");
2990 } else {
2991 panic!("Expected UserMessage");
2992 }
2993 });
2994
2995 // Test appending to existing user message
2996 let message_1_id = UserMessageId::new();
2997 thread.update(cx, |thread, cx| {
2998 thread.push_user_content_block(Some(message_1_id.clone()), "world!".into(), cx);
2999 });
3000
3001 thread.update(cx, |thread, cx| {
3002 assert_eq!(thread.entries.len(), 1);
3003 if let AgentThreadEntry::UserMessage(user_msg) = &thread.entries[0] {
3004 assert_eq!(user_msg.id, Some(message_1_id));
3005 assert_eq!(user_msg.content.to_markdown(cx), "Hello, world!");
3006 } else {
3007 panic!("Expected UserMessage");
3008 }
3009 });
3010
3011 // Test creating new user message after assistant message
3012 thread.update(cx, |thread, cx| {
3013 thread.push_assistant_content_block("Assistant response".into(), false, cx);
3014 });
3015
3016 let message_2_id = UserMessageId::new();
3017 thread.update(cx, |thread, cx| {
3018 thread.push_user_content_block(
3019 Some(message_2_id.clone()),
3020 "New user message".into(),
3021 cx,
3022 );
3023 });
3024
3025 thread.update(cx, |thread, cx| {
3026 assert_eq!(thread.entries.len(), 3);
3027 if let AgentThreadEntry::UserMessage(user_msg) = &thread.entries[2] {
3028 assert_eq!(user_msg.id, Some(message_2_id));
3029 assert_eq!(user_msg.content.to_markdown(cx), "New user message");
3030 } else {
3031 panic!("Expected UserMessage at index 2");
3032 }
3033 });
3034 }
3035
3036 #[gpui::test]
3037 async fn test_thinking_concatenation(cx: &mut gpui::TestAppContext) {
3038 init_test(cx);
3039
3040 let fs = FakeFs::new(cx.executor());
3041 let project = Project::test(fs, [], cx).await;
3042 let connection = Rc::new(FakeAgentConnection::new().on_user_message(
3043 |_, thread, mut cx| {
3044 async move {
3045 thread.update(&mut cx, |thread, cx| {
3046 thread
3047 .handle_session_update(
3048 acp::SessionUpdate::AgentThoughtChunk(acp::ContentChunk::new(
3049 "Thinking ".into(),
3050 )),
3051 cx,
3052 )
3053 .unwrap();
3054 thread
3055 .handle_session_update(
3056 acp::SessionUpdate::AgentThoughtChunk(acp::ContentChunk::new(
3057 "hard!".into(),
3058 )),
3059 cx,
3060 )
3061 .unwrap();
3062 })?;
3063 Ok(acp::PromptResponse::new(acp::StopReason::EndTurn))
3064 }
3065 .boxed_local()
3066 },
3067 ));
3068
3069 let thread = cx
3070 .update(|cx| connection.new_session(project, Path::new(path!("/test")), cx))
3071 .await
3072 .unwrap();
3073
3074 thread
3075 .update(cx, |thread, cx| thread.send_raw("Hello from Zed!", cx))
3076 .await
3077 .unwrap();
3078
3079 let output = thread.read_with(cx, |thread, cx| thread.to_markdown(cx));
3080 assert_eq!(
3081 output,
3082 indoc! {r#"
3083 ## User
3084
3085 Hello from Zed!
3086
3087 ## Assistant
3088
3089 <thinking>
3090 Thinking hard!
3091 </thinking>
3092
3093 "#}
3094 );
3095 }
3096
3097 #[gpui::test]
3098 async fn test_edits_concurrently_to_user(cx: &mut TestAppContext) {
3099 init_test(cx);
3100
3101 let fs = FakeFs::new(cx.executor());
3102 fs.insert_tree(path!("/tmp"), json!({"foo": "one\ntwo\nthree\n"}))
3103 .await;
3104 let project = Project::test(fs.clone(), [], cx).await;
3105 let (read_file_tx, read_file_rx) = oneshot::channel::<()>();
3106 let read_file_tx = Rc::new(RefCell::new(Some(read_file_tx)));
3107 let connection = Rc::new(FakeAgentConnection::new().on_user_message(
3108 move |_, thread, mut cx| {
3109 let read_file_tx = read_file_tx.clone();
3110 async move {
3111 let content = thread
3112 .update(&mut cx, |thread, cx| {
3113 thread.read_text_file(path!("/tmp/foo").into(), None, None, false, cx)
3114 })
3115 .unwrap()
3116 .await
3117 .unwrap();
3118 assert_eq!(content, "one\ntwo\nthree\n");
3119 read_file_tx.take().unwrap().send(()).unwrap();
3120 thread
3121 .update(&mut cx, |thread, cx| {
3122 thread.write_text_file(
3123 path!("/tmp/foo").into(),
3124 "one\ntwo\nthree\nfour\nfive\n".to_string(),
3125 cx,
3126 )
3127 })
3128 .unwrap()
3129 .await
3130 .unwrap();
3131 Ok(acp::PromptResponse::new(acp::StopReason::EndTurn))
3132 }
3133 .boxed_local()
3134 },
3135 ));
3136
3137 let (worktree, pathbuf) = project
3138 .update(cx, |project, cx| {
3139 project.find_or_create_worktree(path!("/tmp/foo"), true, cx)
3140 })
3141 .await
3142 .unwrap();
3143 let buffer = project
3144 .update(cx, |project, cx| {
3145 project.open_buffer((worktree.read(cx).id(), pathbuf), cx)
3146 })
3147 .await
3148 .unwrap();
3149
3150 let thread = cx
3151 .update(|cx| connection.new_session(project, Path::new(path!("/tmp")), cx))
3152 .await
3153 .unwrap();
3154
3155 let request = thread.update(cx, |thread, cx| {
3156 thread.send_raw("Extend the count in /tmp/foo", cx)
3157 });
3158 read_file_rx.await.ok();
3159 buffer.update(cx, |buffer, cx| {
3160 buffer.edit([(0..0, "zero\n".to_string())], None, cx);
3161 });
3162 cx.run_until_parked();
3163 assert_eq!(
3164 buffer.read_with(cx, |buffer, _| buffer.text()),
3165 "zero\none\ntwo\nthree\nfour\nfive\n"
3166 );
3167 assert_eq!(
3168 String::from_utf8(fs.read_file_sync(path!("/tmp/foo")).unwrap()).unwrap(),
3169 "zero\none\ntwo\nthree\nfour\nfive\n"
3170 );
3171 request.await.unwrap();
3172 }
3173
3174 #[gpui::test]
3175 async fn test_reading_from_line(cx: &mut TestAppContext) {
3176 init_test(cx);
3177
3178 let fs = FakeFs::new(cx.executor());
3179 fs.insert_tree(path!("/tmp"), json!({"foo": "one\ntwo\nthree\nfour\n"}))
3180 .await;
3181 let project = Project::test(fs.clone(), [], cx).await;
3182 project
3183 .update(cx, |project, cx| {
3184 project.find_or_create_worktree(path!("/tmp/foo"), true, cx)
3185 })
3186 .await
3187 .unwrap();
3188
3189 let connection = Rc::new(FakeAgentConnection::new());
3190
3191 let thread = cx
3192 .update(|cx| connection.new_session(project, Path::new(path!("/tmp")), cx))
3193 .await
3194 .unwrap();
3195
3196 // Whole file
3197 let content = thread
3198 .update(cx, |thread, cx| {
3199 thread.read_text_file(path!("/tmp/foo").into(), None, None, false, cx)
3200 })
3201 .await
3202 .unwrap();
3203
3204 assert_eq!(content, "one\ntwo\nthree\nfour\n");
3205
3206 // Only start line
3207 let content = thread
3208 .update(cx, |thread, cx| {
3209 thread.read_text_file(path!("/tmp/foo").into(), Some(3), None, false, cx)
3210 })
3211 .await
3212 .unwrap();
3213
3214 assert_eq!(content, "three\nfour\n");
3215
3216 // Only limit
3217 let content = thread
3218 .update(cx, |thread, cx| {
3219 thread.read_text_file(path!("/tmp/foo").into(), None, Some(2), false, cx)
3220 })
3221 .await
3222 .unwrap();
3223
3224 assert_eq!(content, "one\ntwo\n");
3225
3226 // Range
3227 let content = thread
3228 .update(cx, |thread, cx| {
3229 thread.read_text_file(path!("/tmp/foo").into(), Some(2), Some(2), false, cx)
3230 })
3231 .await
3232 .unwrap();
3233
3234 assert_eq!(content, "two\nthree\n");
3235
3236 // Invalid
3237 let err = thread
3238 .update(cx, |thread, cx| {
3239 thread.read_text_file(path!("/tmp/foo").into(), Some(6), Some(2), false, cx)
3240 })
3241 .await
3242 .unwrap_err();
3243
3244 assert_eq!(
3245 err.to_string(),
3246 "Invalid params: \"Attempting to read beyond the end of the file, line 5:0\""
3247 );
3248 }
3249
3250 #[gpui::test]
3251 async fn test_reading_empty_file(cx: &mut TestAppContext) {
3252 init_test(cx);
3253
3254 let fs = FakeFs::new(cx.executor());
3255 fs.insert_tree(path!("/tmp"), json!({"foo": ""})).await;
3256 let project = Project::test(fs.clone(), [], cx).await;
3257 project
3258 .update(cx, |project, cx| {
3259 project.find_or_create_worktree(path!("/tmp/foo"), true, cx)
3260 })
3261 .await
3262 .unwrap();
3263
3264 let connection = Rc::new(FakeAgentConnection::new());
3265
3266 let thread = cx
3267 .update(|cx| connection.new_session(project, Path::new(path!("/tmp")), cx))
3268 .await
3269 .unwrap();
3270
3271 // Whole file
3272 let content = thread
3273 .update(cx, |thread, cx| {
3274 thread.read_text_file(path!("/tmp/foo").into(), None, None, false, cx)
3275 })
3276 .await
3277 .unwrap();
3278
3279 assert_eq!(content, "");
3280
3281 // Only start line
3282 let content = thread
3283 .update(cx, |thread, cx| {
3284 thread.read_text_file(path!("/tmp/foo").into(), Some(1), None, false, cx)
3285 })
3286 .await
3287 .unwrap();
3288
3289 assert_eq!(content, "");
3290
3291 // Only limit
3292 let content = thread
3293 .update(cx, |thread, cx| {
3294 thread.read_text_file(path!("/tmp/foo").into(), None, Some(2), false, cx)
3295 })
3296 .await
3297 .unwrap();
3298
3299 assert_eq!(content, "");
3300
3301 // Range
3302 let content = thread
3303 .update(cx, |thread, cx| {
3304 thread.read_text_file(path!("/tmp/foo").into(), Some(1), Some(1), false, cx)
3305 })
3306 .await
3307 .unwrap();
3308
3309 assert_eq!(content, "");
3310
3311 // Invalid
3312 let err = thread
3313 .update(cx, |thread, cx| {
3314 thread.read_text_file(path!("/tmp/foo").into(), Some(5), Some(2), false, cx)
3315 })
3316 .await
3317 .unwrap_err();
3318
3319 assert_eq!(
3320 err.to_string(),
3321 "Invalid params: \"Attempting to read beyond the end of the file, line 1:0\""
3322 );
3323 }
3324 #[gpui::test]
3325 async fn test_reading_non_existing_file(cx: &mut TestAppContext) {
3326 init_test(cx);
3327
3328 let fs = FakeFs::new(cx.executor());
3329 fs.insert_tree(path!("/tmp"), json!({})).await;
3330 let project = Project::test(fs.clone(), [], cx).await;
3331 project
3332 .update(cx, |project, cx| {
3333 project.find_or_create_worktree(path!("/tmp"), true, cx)
3334 })
3335 .await
3336 .unwrap();
3337
3338 let connection = Rc::new(FakeAgentConnection::new());
3339
3340 let thread = cx
3341 .update(|cx| connection.new_session(project, Path::new(path!("/tmp")), cx))
3342 .await
3343 .unwrap();
3344
3345 // Out of project file
3346 let err = thread
3347 .update(cx, |thread, cx| {
3348 thread.read_text_file(path!("/foo").into(), None, None, false, cx)
3349 })
3350 .await
3351 .unwrap_err();
3352
3353 assert_eq!(err.code, acp::ErrorCode::ResourceNotFound);
3354 }
3355
3356 #[gpui::test]
3357 async fn test_succeeding_canceled_toolcall(cx: &mut TestAppContext) {
3358 init_test(cx);
3359
3360 let fs = FakeFs::new(cx.executor());
3361 let project = Project::test(fs, [], cx).await;
3362 let id = acp::ToolCallId::new("test");
3363
3364 let connection = Rc::new(FakeAgentConnection::new().on_user_message({
3365 let id = id.clone();
3366 move |_, thread, mut cx| {
3367 let id = id.clone();
3368 async move {
3369 thread
3370 .update(&mut cx, |thread, cx| {
3371 thread.handle_session_update(
3372 acp::SessionUpdate::ToolCall(
3373 acp::ToolCall::new(id.clone(), "Label")
3374 .kind(acp::ToolKind::Fetch)
3375 .status(acp::ToolCallStatus::InProgress),
3376 ),
3377 cx,
3378 )
3379 })
3380 .unwrap()
3381 .unwrap();
3382 Ok(acp::PromptResponse::new(acp::StopReason::EndTurn))
3383 }
3384 .boxed_local()
3385 }
3386 }));
3387
3388 let thread = cx
3389 .update(|cx| connection.new_session(project, Path::new(path!("/test")), cx))
3390 .await
3391 .unwrap();
3392
3393 let request = thread.update(cx, |thread, cx| {
3394 thread.send_raw("Fetch https://example.com", cx)
3395 });
3396
3397 run_until_first_tool_call(&thread, cx).await;
3398
3399 thread.read_with(cx, |thread, _| {
3400 assert!(matches!(
3401 thread.entries[1],
3402 AgentThreadEntry::ToolCall(ToolCall {
3403 status: ToolCallStatus::InProgress,
3404 ..
3405 })
3406 ));
3407 });
3408
3409 thread.update(cx, |thread, cx| thread.cancel(cx)).await;
3410
3411 thread.read_with(cx, |thread, _| {
3412 assert!(matches!(
3413 &thread.entries[1],
3414 AgentThreadEntry::ToolCall(ToolCall {
3415 status: ToolCallStatus::Canceled,
3416 ..
3417 })
3418 ));
3419 });
3420
3421 thread
3422 .update(cx, |thread, cx| {
3423 thread.handle_session_update(
3424 acp::SessionUpdate::ToolCallUpdate(acp::ToolCallUpdate::new(
3425 id,
3426 acp::ToolCallUpdateFields::new().status(acp::ToolCallStatus::Completed),
3427 )),
3428 cx,
3429 )
3430 })
3431 .unwrap();
3432
3433 request.await.unwrap();
3434
3435 thread.read_with(cx, |thread, _| {
3436 assert!(matches!(
3437 thread.entries[1],
3438 AgentThreadEntry::ToolCall(ToolCall {
3439 status: ToolCallStatus::Completed,
3440 ..
3441 })
3442 ));
3443 });
3444 }
3445
3446 #[gpui::test]
3447 async fn test_no_pending_edits_if_tool_calls_are_completed(cx: &mut TestAppContext) {
3448 init_test(cx);
3449 let fs = FakeFs::new(cx.background_executor.clone());
3450 fs.insert_tree(path!("/test"), json!({})).await;
3451 let project = Project::test(fs, [path!("/test").as_ref()], cx).await;
3452
3453 let connection = Rc::new(FakeAgentConnection::new().on_user_message({
3454 move |_, thread, mut cx| {
3455 async move {
3456 thread
3457 .update(&mut cx, |thread, cx| {
3458 thread.handle_session_update(
3459 acp::SessionUpdate::ToolCall(
3460 acp::ToolCall::new("test", "Label")
3461 .kind(acp::ToolKind::Edit)
3462 .status(acp::ToolCallStatus::Completed)
3463 .content(vec![acp::ToolCallContent::Diff(acp::Diff::new(
3464 "/test/test.txt",
3465 "foo",
3466 ))]),
3467 ),
3468 cx,
3469 )
3470 })
3471 .unwrap()
3472 .unwrap();
3473 Ok(acp::PromptResponse::new(acp::StopReason::EndTurn))
3474 }
3475 .boxed_local()
3476 }
3477 }));
3478
3479 let thread = cx
3480 .update(|cx| connection.new_session(project, Path::new(path!("/test")), cx))
3481 .await
3482 .unwrap();
3483
3484 cx.update(|cx| thread.update(cx, |thread, cx| thread.send(vec!["Hi".into()], cx)))
3485 .await
3486 .unwrap();
3487
3488 assert!(cx.read(|cx| !thread.read(cx).has_pending_edit_tool_calls()));
3489 }
3490
3491 #[gpui::test(iterations = 10)]
3492 async fn test_checkpoints(cx: &mut TestAppContext) {
3493 init_test(cx);
3494 let fs = FakeFs::new(cx.background_executor.clone());
3495 fs.insert_tree(
3496 path!("/test"),
3497 json!({
3498 ".git": {}
3499 }),
3500 )
3501 .await;
3502 let project = Project::test(fs.clone(), [path!("/test").as_ref()], cx).await;
3503
3504 let simulate_changes = Arc::new(AtomicBool::new(true));
3505 let next_filename = Arc::new(AtomicUsize::new(0));
3506 let connection = Rc::new(FakeAgentConnection::new().on_user_message({
3507 let simulate_changes = simulate_changes.clone();
3508 let next_filename = next_filename.clone();
3509 let fs = fs.clone();
3510 move |request, thread, mut cx| {
3511 let fs = fs.clone();
3512 let simulate_changes = simulate_changes.clone();
3513 let next_filename = next_filename.clone();
3514 async move {
3515 if simulate_changes.load(SeqCst) {
3516 let filename = format!("/test/file-{}", next_filename.fetch_add(1, SeqCst));
3517 fs.write(Path::new(&filename), b"").await?;
3518 }
3519
3520 let acp::ContentBlock::Text(content) = &request.prompt[0] else {
3521 panic!("expected text content block");
3522 };
3523 thread.update(&mut cx, |thread, cx| {
3524 thread
3525 .handle_session_update(
3526 acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new(
3527 content.text.to_uppercase().into(),
3528 )),
3529 cx,
3530 )
3531 .unwrap();
3532 })?;
3533 Ok(acp::PromptResponse::new(acp::StopReason::EndTurn))
3534 }
3535 .boxed_local()
3536 }
3537 }));
3538 let thread = cx
3539 .update(|cx| connection.new_session(project, Path::new(path!("/test")), cx))
3540 .await
3541 .unwrap();
3542
3543 cx.update(|cx| thread.update(cx, |thread, cx| thread.send(vec!["Lorem".into()], cx)))
3544 .await
3545 .unwrap();
3546 thread.read_with(cx, |thread, cx| {
3547 assert_eq!(
3548 thread.to_markdown(cx),
3549 indoc! {"
3550 ## User (checkpoint)
3551
3552 Lorem
3553
3554 ## Assistant
3555
3556 LOREM
3557
3558 "}
3559 );
3560 });
3561 assert_eq!(fs.files(), vec![Path::new(path!("/test/file-0"))]);
3562
3563 cx.update(|cx| thread.update(cx, |thread, cx| thread.send(vec!["ipsum".into()], cx)))
3564 .await
3565 .unwrap();
3566 thread.read_with(cx, |thread, cx| {
3567 assert_eq!(
3568 thread.to_markdown(cx),
3569 indoc! {"
3570 ## User (checkpoint)
3571
3572 Lorem
3573
3574 ## Assistant
3575
3576 LOREM
3577
3578 ## User (checkpoint)
3579
3580 ipsum
3581
3582 ## Assistant
3583
3584 IPSUM
3585
3586 "}
3587 );
3588 });
3589 assert_eq!(
3590 fs.files(),
3591 vec![
3592 Path::new(path!("/test/file-0")),
3593 Path::new(path!("/test/file-1"))
3594 ]
3595 );
3596
3597 // Checkpoint isn't stored when there are no changes.
3598 simulate_changes.store(false, SeqCst);
3599 cx.update(|cx| thread.update(cx, |thread, cx| thread.send(vec!["dolor".into()], cx)))
3600 .await
3601 .unwrap();
3602 thread.read_with(cx, |thread, cx| {
3603 assert_eq!(
3604 thread.to_markdown(cx),
3605 indoc! {"
3606 ## User (checkpoint)
3607
3608 Lorem
3609
3610 ## Assistant
3611
3612 LOREM
3613
3614 ## User (checkpoint)
3615
3616 ipsum
3617
3618 ## Assistant
3619
3620 IPSUM
3621
3622 ## User
3623
3624 dolor
3625
3626 ## Assistant
3627
3628 DOLOR
3629
3630 "}
3631 );
3632 });
3633 assert_eq!(
3634 fs.files(),
3635 vec![
3636 Path::new(path!("/test/file-0")),
3637 Path::new(path!("/test/file-1"))
3638 ]
3639 );
3640
3641 // Rewinding the conversation truncates the history and restores the checkpoint.
3642 thread
3643 .update(cx, |thread, cx| {
3644 let AgentThreadEntry::UserMessage(message) = &thread.entries[2] else {
3645 panic!("unexpected entries {:?}", thread.entries)
3646 };
3647 thread.restore_checkpoint(message.id.clone().unwrap(), cx)
3648 })
3649 .await
3650 .unwrap();
3651 thread.read_with(cx, |thread, cx| {
3652 assert_eq!(
3653 thread.to_markdown(cx),
3654 indoc! {"
3655 ## User (checkpoint)
3656
3657 Lorem
3658
3659 ## Assistant
3660
3661 LOREM
3662
3663 "}
3664 );
3665 });
3666 assert_eq!(fs.files(), vec![Path::new(path!("/test/file-0"))]);
3667 }
3668
3669 #[gpui::test]
3670 async fn test_tool_result_refusal(cx: &mut TestAppContext) {
3671 use std::sync::atomic::AtomicUsize;
3672 init_test(cx);
3673
3674 let fs = FakeFs::new(cx.executor());
3675 let project = Project::test(fs, None, cx).await;
3676
3677 // Create a connection that simulates refusal after tool result
3678 let prompt_count = Arc::new(AtomicUsize::new(0));
3679 let connection = Rc::new(FakeAgentConnection::new().on_user_message({
3680 let prompt_count = prompt_count.clone();
3681 move |_request, thread, mut cx| {
3682 let count = prompt_count.fetch_add(1, SeqCst);
3683 async move {
3684 if count == 0 {
3685 // First prompt: Generate a tool call with result
3686 thread.update(&mut cx, |thread, cx| {
3687 thread
3688 .handle_session_update(
3689 acp::SessionUpdate::ToolCall(
3690 acp::ToolCall::new("tool1", "Test Tool")
3691 .kind(acp::ToolKind::Fetch)
3692 .status(acp::ToolCallStatus::Completed)
3693 .raw_input(serde_json::json!({"query": "test"}))
3694 .raw_output(serde_json::json!({"result": "inappropriate content"})),
3695 ),
3696 cx,
3697 )
3698 .unwrap();
3699 })?;
3700
3701 // Now return refusal because of the tool result
3702 Ok(acp::PromptResponse::new(acp::StopReason::Refusal))
3703 } else {
3704 Ok(acp::PromptResponse::new(acp::StopReason::EndTurn))
3705 }
3706 }
3707 .boxed_local()
3708 }
3709 }));
3710
3711 let thread = cx
3712 .update(|cx| connection.new_session(project, Path::new(path!("/test")), cx))
3713 .await
3714 .unwrap();
3715
3716 // Track if we see a Refusal event
3717 let saw_refusal_event = Arc::new(std::sync::Mutex::new(false));
3718 let saw_refusal_event_captured = saw_refusal_event.clone();
3719 thread.update(cx, |_thread, cx| {
3720 cx.subscribe(
3721 &thread,
3722 move |_thread, _event_thread, event: &AcpThreadEvent, _cx| {
3723 if matches!(event, AcpThreadEvent::Refusal) {
3724 *saw_refusal_event_captured.lock().unwrap() = true;
3725 }
3726 },
3727 )
3728 .detach();
3729 });
3730
3731 // Send a user message - this will trigger tool call and then refusal
3732 let send_task = thread.update(cx, |thread, cx| thread.send(vec!["Hello".into()], cx));
3733 cx.background_executor.spawn(send_task).detach();
3734 cx.run_until_parked();
3735
3736 // Verify that:
3737 // 1. A Refusal event WAS emitted (because it's a tool result refusal, not user prompt)
3738 // 2. The user message was NOT truncated
3739 assert!(
3740 *saw_refusal_event.lock().unwrap(),
3741 "Refusal event should be emitted for tool result refusals"
3742 );
3743
3744 thread.read_with(cx, |thread, _| {
3745 let entries = thread.entries();
3746 assert!(entries.len() >= 2, "Should have user message and tool call");
3747
3748 // Verify user message is still there
3749 assert!(
3750 matches!(entries[0], AgentThreadEntry::UserMessage(_)),
3751 "User message should not be truncated"
3752 );
3753
3754 // Verify tool call is there with result
3755 if let AgentThreadEntry::ToolCall(tool_call) = &entries[1] {
3756 assert!(
3757 tool_call.raw_output.is_some(),
3758 "Tool call should have output"
3759 );
3760 } else {
3761 panic!("Expected tool call at index 1");
3762 }
3763 });
3764 }
3765
3766 #[gpui::test]
3767 async fn test_user_prompt_refusal_emits_event(cx: &mut TestAppContext) {
3768 init_test(cx);
3769
3770 let fs = FakeFs::new(cx.executor());
3771 let project = Project::test(fs, None, cx).await;
3772
3773 let refuse_next = Arc::new(AtomicBool::new(false));
3774 let connection = Rc::new(FakeAgentConnection::new().on_user_message({
3775 let refuse_next = refuse_next.clone();
3776 move |_request, _thread, _cx| {
3777 if refuse_next.load(SeqCst) {
3778 async move { Ok(acp::PromptResponse::new(acp::StopReason::Refusal)) }
3779 .boxed_local()
3780 } else {
3781 async move { Ok(acp::PromptResponse::new(acp::StopReason::EndTurn)) }
3782 .boxed_local()
3783 }
3784 }
3785 }));
3786
3787 let thread = cx
3788 .update(|cx| connection.new_session(project, Path::new(path!("/test")), cx))
3789 .await
3790 .unwrap();
3791
3792 // Track if we see a Refusal event
3793 let saw_refusal_event = Arc::new(std::sync::Mutex::new(false));
3794 let saw_refusal_event_captured = saw_refusal_event.clone();
3795 thread.update(cx, |_thread, cx| {
3796 cx.subscribe(
3797 &thread,
3798 move |_thread, _event_thread, event: &AcpThreadEvent, _cx| {
3799 if matches!(event, AcpThreadEvent::Refusal) {
3800 *saw_refusal_event_captured.lock().unwrap() = true;
3801 }
3802 },
3803 )
3804 .detach();
3805 });
3806
3807 // Send a message that will be refused
3808 refuse_next.store(true, SeqCst);
3809 cx.update(|cx| thread.update(cx, |thread, cx| thread.send(vec!["hello".into()], cx)))
3810 .await
3811 .unwrap();
3812
3813 // Verify that a Refusal event WAS emitted for user prompt refusal
3814 assert!(
3815 *saw_refusal_event.lock().unwrap(),
3816 "Refusal event should be emitted for user prompt refusals"
3817 );
3818
3819 // Verify the message was truncated (user prompt refusal)
3820 thread.read_with(cx, |thread, cx| {
3821 assert_eq!(thread.to_markdown(cx), "");
3822 });
3823 }
3824
3825 #[gpui::test]
3826 async fn test_refusal(cx: &mut TestAppContext) {
3827 init_test(cx);
3828 let fs = FakeFs::new(cx.background_executor.clone());
3829 fs.insert_tree(path!("/"), json!({})).await;
3830 let project = Project::test(fs.clone(), [path!("/").as_ref()], cx).await;
3831
3832 let refuse_next = Arc::new(AtomicBool::new(false));
3833 let connection = Rc::new(FakeAgentConnection::new().on_user_message({
3834 let refuse_next = refuse_next.clone();
3835 move |request, thread, mut cx| {
3836 let refuse_next = refuse_next.clone();
3837 async move {
3838 if refuse_next.load(SeqCst) {
3839 return Ok(acp::PromptResponse::new(acp::StopReason::Refusal));
3840 }
3841
3842 let acp::ContentBlock::Text(content) = &request.prompt[0] else {
3843 panic!("expected text content block");
3844 };
3845 thread.update(&mut cx, |thread, cx| {
3846 thread
3847 .handle_session_update(
3848 acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new(
3849 content.text.to_uppercase().into(),
3850 )),
3851 cx,
3852 )
3853 .unwrap();
3854 })?;
3855 Ok(acp::PromptResponse::new(acp::StopReason::EndTurn))
3856 }
3857 .boxed_local()
3858 }
3859 }));
3860 let thread = cx
3861 .update(|cx| connection.new_session(project, Path::new(path!("/test")), cx))
3862 .await
3863 .unwrap();
3864
3865 cx.update(|cx| thread.update(cx, |thread, cx| thread.send(vec!["hello".into()], cx)))
3866 .await
3867 .unwrap();
3868 thread.read_with(cx, |thread, cx| {
3869 assert_eq!(
3870 thread.to_markdown(cx),
3871 indoc! {"
3872 ## User
3873
3874 hello
3875
3876 ## Assistant
3877
3878 HELLO
3879
3880 "}
3881 );
3882 });
3883
3884 // Simulate refusing the second message. The message should be truncated
3885 // when a user prompt is refused.
3886 refuse_next.store(true, SeqCst);
3887 cx.update(|cx| thread.update(cx, |thread, cx| thread.send(vec!["world".into()], cx)))
3888 .await
3889 .unwrap();
3890 thread.read_with(cx, |thread, cx| {
3891 assert_eq!(
3892 thread.to_markdown(cx),
3893 indoc! {"
3894 ## User
3895
3896 hello
3897
3898 ## Assistant
3899
3900 HELLO
3901
3902 "}
3903 );
3904 });
3905 }
3906
3907 async fn run_until_first_tool_call(
3908 thread: &Entity<AcpThread>,
3909 cx: &mut TestAppContext,
3910 ) -> usize {
3911 let (mut tx, mut rx) = mpsc::channel::<usize>(1);
3912
3913 let subscription = cx.update(|cx| {
3914 cx.subscribe(thread, move |thread, _, cx| {
3915 for (ix, entry) in thread.read(cx).entries.iter().enumerate() {
3916 if matches!(entry, AgentThreadEntry::ToolCall(_)) {
3917 return tx.try_send(ix).unwrap();
3918 }
3919 }
3920 })
3921 });
3922
3923 select! {
3924 _ = futures::FutureExt::fuse(cx.background_executor.timer(Duration::from_secs(10))) => {
3925 panic!("Timeout waiting for tool call")
3926 }
3927 ix = rx.next().fuse() => {
3928 drop(subscription);
3929 ix.unwrap()
3930 }
3931 }
3932 }
3933
3934 #[derive(Clone, Default)]
3935 struct FakeAgentConnection {
3936 auth_methods: Vec<acp::AuthMethod>,
3937 sessions: Arc<parking_lot::Mutex<HashMap<acp::SessionId, WeakEntity<AcpThread>>>>,
3938 set_title_calls: Rc<RefCell<Vec<SharedString>>>,
3939 on_user_message: Option<
3940 Rc<
3941 dyn Fn(
3942 acp::PromptRequest,
3943 WeakEntity<AcpThread>,
3944 AsyncApp,
3945 ) -> LocalBoxFuture<'static, Result<acp::PromptResponse>>
3946 + 'static,
3947 >,
3948 >,
3949 }
3950
3951 impl FakeAgentConnection {
3952 fn new() -> Self {
3953 Self {
3954 auth_methods: Vec::new(),
3955 on_user_message: None,
3956 sessions: Arc::default(),
3957 set_title_calls: Default::default(),
3958 }
3959 }
3960
3961 #[expect(unused)]
3962 fn with_auth_methods(mut self, auth_methods: Vec<acp::AuthMethod>) -> Self {
3963 self.auth_methods = auth_methods;
3964 self
3965 }
3966
3967 fn on_user_message(
3968 mut self,
3969 handler: impl Fn(
3970 acp::PromptRequest,
3971 WeakEntity<AcpThread>,
3972 AsyncApp,
3973 ) -> LocalBoxFuture<'static, Result<acp::PromptResponse>>
3974 + 'static,
3975 ) -> Self {
3976 self.on_user_message.replace(Rc::new(handler));
3977 self
3978 }
3979 }
3980
3981 impl AgentConnection for FakeAgentConnection {
3982 fn telemetry_id(&self) -> SharedString {
3983 "fake".into()
3984 }
3985
3986 fn auth_methods(&self) -> &[acp::AuthMethod] {
3987 &self.auth_methods
3988 }
3989
3990 fn new_session(
3991 self: Rc<Self>,
3992 project: Entity<Project>,
3993 cwd: &Path,
3994 cx: &mut App,
3995 ) -> Task<gpui::Result<Entity<AcpThread>>> {
3996 let session_id = acp::SessionId::new(
3997 rand::rng()
3998 .sample_iter(&distr::Alphanumeric)
3999 .take(7)
4000 .map(char::from)
4001 .collect::<String>(),
4002 );
4003 let action_log = cx.new(|_| ActionLog::new(project.clone()));
4004 let thread = cx.new(|cx| {
4005 AcpThread::new(
4006 None,
4007 "Test",
4008 Some(cwd.to_path_buf()),
4009 self.clone(),
4010 project,
4011 action_log,
4012 session_id.clone(),
4013 watch::Receiver::constant(
4014 acp::PromptCapabilities::new()
4015 .image(true)
4016 .audio(true)
4017 .embedded_context(true),
4018 ),
4019 cx,
4020 )
4021 });
4022 self.sessions.lock().insert(session_id, thread.downgrade());
4023 Task::ready(Ok(thread))
4024 }
4025
4026 fn authenticate(&self, method: acp::AuthMethodId, _cx: &mut App) -> Task<gpui::Result<()>> {
4027 if self.auth_methods().iter().any(|m| m.id() == &method) {
4028 Task::ready(Ok(()))
4029 } else {
4030 Task::ready(Err(anyhow!("Invalid Auth Method")))
4031 }
4032 }
4033
4034 fn prompt(
4035 &self,
4036 _id: Option<UserMessageId>,
4037 params: acp::PromptRequest,
4038 cx: &mut App,
4039 ) -> Task<gpui::Result<acp::PromptResponse>> {
4040 let sessions = self.sessions.lock();
4041 let thread = sessions.get(¶ms.session_id).unwrap();
4042 if let Some(handler) = &self.on_user_message {
4043 let handler = handler.clone();
4044 let thread = thread.clone();
4045 cx.spawn(async move |cx| handler(params, thread, cx.clone()).await)
4046 } else {
4047 Task::ready(Ok(acp::PromptResponse::new(acp::StopReason::EndTurn)))
4048 }
4049 }
4050
4051 fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {}
4052
4053 fn truncate(
4054 &self,
4055 session_id: &acp::SessionId,
4056 _cx: &App,
4057 ) -> Option<Rc<dyn AgentSessionTruncate>> {
4058 Some(Rc::new(FakeAgentSessionEditor {
4059 _session_id: session_id.clone(),
4060 }))
4061 }
4062
4063 fn set_title(
4064 &self,
4065 _session_id: &acp::SessionId,
4066 _cx: &App,
4067 ) -> Option<Rc<dyn AgentSessionSetTitle>> {
4068 Some(Rc::new(FakeAgentSessionSetTitle {
4069 calls: self.set_title_calls.clone(),
4070 }))
4071 }
4072
4073 fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
4074 self
4075 }
4076 }
4077
4078 struct FakeAgentSessionSetTitle {
4079 calls: Rc<RefCell<Vec<SharedString>>>,
4080 }
4081
4082 impl AgentSessionSetTitle for FakeAgentSessionSetTitle {
4083 fn run(&self, title: SharedString, _cx: &mut App) -> Task<Result<()>> {
4084 self.calls.borrow_mut().push(title);
4085 Task::ready(Ok(()))
4086 }
4087 }
4088
4089 struct FakeAgentSessionEditor {
4090 _session_id: acp::SessionId,
4091 }
4092
4093 impl AgentSessionTruncate for FakeAgentSessionEditor {
4094 fn run(&self, _message_id: UserMessageId, _cx: &mut App) -> Task<Result<()>> {
4095 Task::ready(Ok(()))
4096 }
4097 }
4098
4099 #[gpui::test]
4100 async fn test_tool_call_not_found_creates_failed_entry(cx: &mut TestAppContext) {
4101 init_test(cx);
4102
4103 let fs = FakeFs::new(cx.executor());
4104 let project = Project::test(fs, [], cx).await;
4105 let connection = Rc::new(FakeAgentConnection::new());
4106 let thread = cx
4107 .update(|cx| connection.new_session(project, Path::new(path!("/test")), cx))
4108 .await
4109 .unwrap();
4110
4111 // Try to update a tool call that doesn't exist
4112 let nonexistent_id = acp::ToolCallId::new("nonexistent-tool-call");
4113 thread.update(cx, |thread, cx| {
4114 let result = thread.handle_session_update(
4115 acp::SessionUpdate::ToolCallUpdate(acp::ToolCallUpdate::new(
4116 nonexistent_id.clone(),
4117 acp::ToolCallUpdateFields::new().status(acp::ToolCallStatus::Completed),
4118 )),
4119 cx,
4120 );
4121
4122 // The update should succeed (not return an error)
4123 assert!(result.is_ok());
4124
4125 // There should now be exactly one entry in the thread
4126 assert_eq!(thread.entries.len(), 1);
4127
4128 // The entry should be a failed tool call
4129 if let AgentThreadEntry::ToolCall(tool_call) = &thread.entries[0] {
4130 assert_eq!(tool_call.id, nonexistent_id);
4131 assert!(matches!(tool_call.status, ToolCallStatus::Failed));
4132 assert_eq!(tool_call.kind, acp::ToolKind::Fetch);
4133
4134 // Check that the content contains the error message
4135 assert_eq!(tool_call.content.len(), 1);
4136 if let ToolCallContent::ContentBlock(content_block) = &tool_call.content[0] {
4137 match content_block {
4138 ContentBlock::Markdown { markdown } => {
4139 let markdown_text = markdown.read(cx).source();
4140 assert!(markdown_text.contains("Tool call not found"));
4141 }
4142 ContentBlock::Empty => panic!("Expected markdown content, got empty"),
4143 ContentBlock::ResourceLink { .. } => {
4144 panic!("Expected markdown content, got resource link")
4145 }
4146 ContentBlock::Image { .. } => {
4147 panic!("Expected markdown content, got image")
4148 }
4149 }
4150 } else {
4151 panic!("Expected ContentBlock, got: {:?}", tool_call.content[0]);
4152 }
4153 } else {
4154 panic!("Expected ToolCall entry, got: {:?}", thread.entries[0]);
4155 }
4156 });
4157 }
4158
4159 /// Tests that restoring a checkpoint properly cleans up terminals that were
4160 /// created after that checkpoint, and cancels any in-progress generation.
4161 ///
4162 /// Reproduces issue #35142: When a checkpoint is restored, any terminal processes
4163 /// that were started after that checkpoint should be terminated, and any in-progress
4164 /// AI generation should be canceled.
4165 #[gpui::test]
4166 async fn test_restore_checkpoint_kills_terminal(cx: &mut TestAppContext) {
4167 init_test(cx);
4168
4169 let fs = FakeFs::new(cx.executor());
4170 let project = Project::test(fs, [], cx).await;
4171 let connection = Rc::new(FakeAgentConnection::new());
4172 let thread = cx
4173 .update(|cx| connection.new_session(project, Path::new(path!("/test")), cx))
4174 .await
4175 .unwrap();
4176
4177 // Send first user message to create a checkpoint
4178 cx.update(|cx| {
4179 thread.update(cx, |thread, cx| {
4180 thread.send(vec!["first message".into()], cx)
4181 })
4182 })
4183 .await
4184 .unwrap();
4185
4186 // Send second message (creates another checkpoint) - we'll restore to this one
4187 cx.update(|cx| {
4188 thread.update(cx, |thread, cx| {
4189 thread.send(vec!["second message".into()], cx)
4190 })
4191 })
4192 .await
4193 .unwrap();
4194
4195 // Create 2 terminals BEFORE the checkpoint that have completed running
4196 let terminal_id_1 = acp::TerminalId::new(uuid::Uuid::new_v4().to_string());
4197 let mock_terminal_1 = cx.new(|cx| {
4198 let builder = ::terminal::TerminalBuilder::new_display_only(
4199 ::terminal::terminal_settings::CursorShape::default(),
4200 ::terminal::terminal_settings::AlternateScroll::On,
4201 None,
4202 0,
4203 cx.background_executor(),
4204 PathStyle::local(),
4205 )
4206 .unwrap();
4207 builder.subscribe(cx)
4208 });
4209
4210 thread.update(cx, |thread, cx| {
4211 thread.on_terminal_provider_event(
4212 TerminalProviderEvent::Created {
4213 terminal_id: terminal_id_1.clone(),
4214 label: "echo 'first'".to_string(),
4215 cwd: Some(PathBuf::from("/test")),
4216 output_byte_limit: None,
4217 terminal: mock_terminal_1.clone(),
4218 },
4219 cx,
4220 );
4221 });
4222
4223 thread.update(cx, |thread, cx| {
4224 thread.on_terminal_provider_event(
4225 TerminalProviderEvent::Output {
4226 terminal_id: terminal_id_1.clone(),
4227 data: b"first\n".to_vec(),
4228 },
4229 cx,
4230 );
4231 });
4232
4233 thread.update(cx, |thread, cx| {
4234 thread.on_terminal_provider_event(
4235 TerminalProviderEvent::Exit {
4236 terminal_id: terminal_id_1.clone(),
4237 status: acp::TerminalExitStatus::new().exit_code(0),
4238 },
4239 cx,
4240 );
4241 });
4242
4243 let terminal_id_2 = acp::TerminalId::new(uuid::Uuid::new_v4().to_string());
4244 let mock_terminal_2 = cx.new(|cx| {
4245 let builder = ::terminal::TerminalBuilder::new_display_only(
4246 ::terminal::terminal_settings::CursorShape::default(),
4247 ::terminal::terminal_settings::AlternateScroll::On,
4248 None,
4249 0,
4250 cx.background_executor(),
4251 PathStyle::local(),
4252 )
4253 .unwrap();
4254 builder.subscribe(cx)
4255 });
4256
4257 thread.update(cx, |thread, cx| {
4258 thread.on_terminal_provider_event(
4259 TerminalProviderEvent::Created {
4260 terminal_id: terminal_id_2.clone(),
4261 label: "echo 'second'".to_string(),
4262 cwd: Some(PathBuf::from("/test")),
4263 output_byte_limit: None,
4264 terminal: mock_terminal_2.clone(),
4265 },
4266 cx,
4267 );
4268 });
4269
4270 thread.update(cx, |thread, cx| {
4271 thread.on_terminal_provider_event(
4272 TerminalProviderEvent::Output {
4273 terminal_id: terminal_id_2.clone(),
4274 data: b"second\n".to_vec(),
4275 },
4276 cx,
4277 );
4278 });
4279
4280 thread.update(cx, |thread, cx| {
4281 thread.on_terminal_provider_event(
4282 TerminalProviderEvent::Exit {
4283 terminal_id: terminal_id_2.clone(),
4284 status: acp::TerminalExitStatus::new().exit_code(0),
4285 },
4286 cx,
4287 );
4288 });
4289
4290 // Get the second message ID to restore to
4291 let second_message_id = thread.read_with(cx, |thread, _| {
4292 // At this point we have:
4293 // - Index 0: First user message (with checkpoint)
4294 // - Index 1: Second user message (with checkpoint)
4295 // No assistant responses because FakeAgentConnection just returns EndTurn
4296 let AgentThreadEntry::UserMessage(message) = &thread.entries[1] else {
4297 panic!("expected user message at index 1");
4298 };
4299 message.id.clone().unwrap()
4300 });
4301
4302 // Create a terminal AFTER the checkpoint we'll restore to.
4303 // This simulates the AI agent starting a long-running terminal command.
4304 let terminal_id = acp::TerminalId::new(uuid::Uuid::new_v4().to_string());
4305 let mock_terminal = cx.new(|cx| {
4306 let builder = ::terminal::TerminalBuilder::new_display_only(
4307 ::terminal::terminal_settings::CursorShape::default(),
4308 ::terminal::terminal_settings::AlternateScroll::On,
4309 None,
4310 0,
4311 cx.background_executor(),
4312 PathStyle::local(),
4313 )
4314 .unwrap();
4315 builder.subscribe(cx)
4316 });
4317
4318 // Register the terminal as created
4319 thread.update(cx, |thread, cx| {
4320 thread.on_terminal_provider_event(
4321 TerminalProviderEvent::Created {
4322 terminal_id: terminal_id.clone(),
4323 label: "sleep 1000".to_string(),
4324 cwd: Some(PathBuf::from("/test")),
4325 output_byte_limit: None,
4326 terminal: mock_terminal.clone(),
4327 },
4328 cx,
4329 );
4330 });
4331
4332 // Simulate the terminal producing output (still running)
4333 thread.update(cx, |thread, cx| {
4334 thread.on_terminal_provider_event(
4335 TerminalProviderEvent::Output {
4336 terminal_id: terminal_id.clone(),
4337 data: b"terminal is running...\n".to_vec(),
4338 },
4339 cx,
4340 );
4341 });
4342
4343 // Create a tool call entry that references this terminal
4344 // This represents the agent requesting a terminal command
4345 thread.update(cx, |thread, cx| {
4346 thread
4347 .handle_session_update(
4348 acp::SessionUpdate::ToolCall(
4349 acp::ToolCall::new("terminal-tool-1", "Running command")
4350 .kind(acp::ToolKind::Execute)
4351 .status(acp::ToolCallStatus::InProgress)
4352 .content(vec![acp::ToolCallContent::Terminal(acp::Terminal::new(
4353 terminal_id.clone(),
4354 ))])
4355 .raw_input(serde_json::json!({"command": "sleep 1000", "cd": "/test"})),
4356 ),
4357 cx,
4358 )
4359 .unwrap();
4360 });
4361
4362 // Verify terminal exists and is in the thread
4363 let terminal_exists_before =
4364 thread.read_with(cx, |thread, _| thread.terminals.contains_key(&terminal_id));
4365 assert!(
4366 terminal_exists_before,
4367 "Terminal should exist before checkpoint restore"
4368 );
4369
4370 // Verify the terminal's underlying task is still running (not completed)
4371 let terminal_running_before = thread.read_with(cx, |thread, _cx| {
4372 let terminal_entity = thread.terminals.get(&terminal_id).unwrap();
4373 terminal_entity.read_with(cx, |term, _cx| {
4374 term.output().is_none() // output is None means it's still running
4375 })
4376 });
4377 assert!(
4378 terminal_running_before,
4379 "Terminal should be running before checkpoint restore"
4380 );
4381
4382 // Verify we have the expected entries before restore
4383 let entry_count_before = thread.read_with(cx, |thread, _| thread.entries.len());
4384 assert!(
4385 entry_count_before > 1,
4386 "Should have multiple entries before restore"
4387 );
4388
4389 // Restore the checkpoint to the second message.
4390 // This should:
4391 // 1. Cancel any in-progress generation (via the cancel() call)
4392 // 2. Remove the terminal that was created after that point
4393 thread
4394 .update(cx, |thread, cx| {
4395 thread.restore_checkpoint(second_message_id, cx)
4396 })
4397 .await
4398 .unwrap();
4399
4400 // Verify that no send_task is in progress after restore
4401 // (cancel() clears the send_task)
4402 let has_send_task_after = thread.read_with(cx, |thread, _| thread.running_turn.is_some());
4403 assert!(
4404 !has_send_task_after,
4405 "Should not have a send_task after restore (cancel should have cleared it)"
4406 );
4407
4408 // Verify the entries were truncated (restoring to index 1 truncates at 1, keeping only index 0)
4409 let entry_count = thread.read_with(cx, |thread, _| thread.entries.len());
4410 assert_eq!(
4411 entry_count, 1,
4412 "Should have 1 entry after restore (only the first user message)"
4413 );
4414
4415 // Verify the 2 completed terminals from before the checkpoint still exist
4416 let terminal_1_exists = thread.read_with(cx, |thread, _| {
4417 thread.terminals.contains_key(&terminal_id_1)
4418 });
4419 assert!(
4420 terminal_1_exists,
4421 "Terminal 1 (from before checkpoint) should still exist"
4422 );
4423
4424 let terminal_2_exists = thread.read_with(cx, |thread, _| {
4425 thread.terminals.contains_key(&terminal_id_2)
4426 });
4427 assert!(
4428 terminal_2_exists,
4429 "Terminal 2 (from before checkpoint) should still exist"
4430 );
4431
4432 // Verify they're still in completed state
4433 let terminal_1_completed = thread.read_with(cx, |thread, _cx| {
4434 let terminal_entity = thread.terminals.get(&terminal_id_1).unwrap();
4435 terminal_entity.read_with(cx, |term, _cx| term.output().is_some())
4436 });
4437 assert!(terminal_1_completed, "Terminal 1 should still be completed");
4438
4439 let terminal_2_completed = thread.read_with(cx, |thread, _cx| {
4440 let terminal_entity = thread.terminals.get(&terminal_id_2).unwrap();
4441 terminal_entity.read_with(cx, |term, _cx| term.output().is_some())
4442 });
4443 assert!(terminal_2_completed, "Terminal 2 should still be completed");
4444
4445 // Verify the running terminal (created after checkpoint) was removed
4446 let terminal_3_exists =
4447 thread.read_with(cx, |thread, _| thread.terminals.contains_key(&terminal_id));
4448 assert!(
4449 !terminal_3_exists,
4450 "Terminal 3 (created after checkpoint) should have been removed"
4451 );
4452
4453 // Verify total count is 2 (the two from before the checkpoint)
4454 let terminal_count = thread.read_with(cx, |thread, _| thread.terminals.len());
4455 assert_eq!(
4456 terminal_count, 2,
4457 "Should have exactly 2 terminals (the completed ones from before checkpoint)"
4458 );
4459 }
4460
4461 /// Tests that update_last_checkpoint correctly updates the original message's checkpoint
4462 /// even when a new user message is added while the async checkpoint comparison is in progress.
4463 ///
4464 /// This is a regression test for a bug where update_last_checkpoint would fail with
4465 /// "no checkpoint" if a new user message (without a checkpoint) was added between when
4466 /// update_last_checkpoint started and when its async closure ran.
4467 #[gpui::test]
4468 async fn test_update_last_checkpoint_with_new_message_added(cx: &mut TestAppContext) {
4469 init_test(cx);
4470
4471 let fs = FakeFs::new(cx.executor());
4472 fs.insert_tree(path!("/test"), json!({".git": {}, "file.txt": "content"}))
4473 .await;
4474 let project = Project::test(fs.clone(), [Path::new(path!("/test"))], cx).await;
4475
4476 let handler_done = Arc::new(AtomicBool::new(false));
4477 let handler_done_clone = handler_done.clone();
4478 let connection = Rc::new(FakeAgentConnection::new().on_user_message(
4479 move |_, _thread, _cx| {
4480 handler_done_clone.store(true, SeqCst);
4481 async move { Ok(acp::PromptResponse::new(acp::StopReason::EndTurn)) }.boxed_local()
4482 },
4483 ));
4484
4485 let thread = cx
4486 .update(|cx| connection.new_session(project, Path::new(path!("/test")), cx))
4487 .await
4488 .unwrap();
4489
4490 let send_future = thread.update(cx, |thread, cx| thread.send_raw("First message", cx));
4491 let send_task = cx.background_executor.spawn(send_future);
4492
4493 // Tick until handler completes, then a few more to let update_last_checkpoint start
4494 while !handler_done.load(SeqCst) {
4495 cx.executor().tick();
4496 }
4497 for _ in 0..5 {
4498 cx.executor().tick();
4499 }
4500
4501 thread.update(cx, |thread, cx| {
4502 thread.push_entry(
4503 AgentThreadEntry::UserMessage(UserMessage {
4504 id: Some(UserMessageId::new()),
4505 content: ContentBlock::Empty,
4506 chunks: vec!["Injected message (no checkpoint)".into()],
4507 checkpoint: None,
4508 indented: false,
4509 }),
4510 cx,
4511 );
4512 });
4513
4514 cx.run_until_parked();
4515 let result = send_task.await;
4516
4517 assert!(
4518 result.is_ok(),
4519 "send should succeed even when new message added during update_last_checkpoint: {:?}",
4520 result.err()
4521 );
4522 }
4523
4524 /// Tests that when a follow-up message is sent during generation,
4525 /// the first turn completing does NOT clear `running_turn` because
4526 /// it now belongs to the second turn.
4527 #[gpui::test]
4528 async fn test_follow_up_message_during_generation_does_not_clear_turn(cx: &mut TestAppContext) {
4529 init_test(cx);
4530
4531 let fs = FakeFs::new(cx.executor());
4532 let project = Project::test(fs, [], cx).await;
4533
4534 // First handler waits for this signal before completing
4535 let (first_complete_tx, first_complete_rx) = futures::channel::oneshot::channel::<()>();
4536 let first_complete_rx = RefCell::new(Some(first_complete_rx));
4537
4538 let connection = Rc::new(FakeAgentConnection::new().on_user_message({
4539 move |params, _thread, _cx| {
4540 let first_complete_rx = first_complete_rx.borrow_mut().take();
4541 let is_first = params
4542 .prompt
4543 .iter()
4544 .any(|c| matches!(c, acp::ContentBlock::Text(t) if t.text.contains("first")));
4545
4546 async move {
4547 if is_first {
4548 // First handler waits until signaled
4549 if let Some(rx) = first_complete_rx {
4550 rx.await.ok();
4551 }
4552 }
4553 Ok(acp::PromptResponse::new(acp::StopReason::EndTurn))
4554 }
4555 .boxed_local()
4556 }
4557 }));
4558
4559 let thread = cx
4560 .update(|cx| connection.new_session(project, Path::new(path!("/test")), cx))
4561 .await
4562 .unwrap();
4563
4564 // Send first message (turn_id=1) - handler will block
4565 let first_request = thread.update(cx, |thread, cx| thread.send_raw("first", cx));
4566 assert_eq!(thread.read_with(cx, |t, _| t.turn_id), 1);
4567
4568 // Send second message (turn_id=2) while first is still blocked
4569 // This calls cancel() which takes turn 1's running_turn and sets turn 2's
4570 let second_request = thread.update(cx, |thread, cx| thread.send_raw("second", cx));
4571 assert_eq!(thread.read_with(cx, |t, _| t.turn_id), 2);
4572
4573 let running_turn_after_second_send =
4574 thread.read_with(cx, |thread, _| thread.running_turn.as_ref().map(|t| t.id));
4575 assert_eq!(
4576 running_turn_after_second_send,
4577 Some(2),
4578 "running_turn should be set to turn 2 after sending second message"
4579 );
4580
4581 // Now signal first handler to complete
4582 first_complete_tx.send(()).ok();
4583
4584 // First request completes - should NOT clear running_turn
4585 // because running_turn now belongs to turn 2
4586 first_request.await.unwrap();
4587
4588 let running_turn_after_first =
4589 thread.read_with(cx, |thread, _| thread.running_turn.as_ref().map(|t| t.id));
4590 assert_eq!(
4591 running_turn_after_first,
4592 Some(2),
4593 "first turn completing should not clear running_turn (belongs to turn 2)"
4594 );
4595
4596 // Second request completes - SHOULD clear running_turn
4597 second_request.await.unwrap();
4598
4599 let running_turn_after_second =
4600 thread.read_with(cx, |thread, _| thread.running_turn.is_some());
4601 assert!(
4602 !running_turn_after_second,
4603 "second turn completing should clear running_turn"
4604 );
4605 }
4606
4607 #[gpui::test]
4608 async fn test_send_returns_cancelled_response_and_marks_tools_as_cancelled(
4609 cx: &mut TestAppContext,
4610 ) {
4611 init_test(cx);
4612
4613 let fs = FakeFs::new(cx.executor());
4614 let project = Project::test(fs, [], cx).await;
4615
4616 let connection = Rc::new(FakeAgentConnection::new().on_user_message(
4617 move |_params, thread, mut cx| {
4618 async move {
4619 thread
4620 .update(&mut cx, |thread, cx| {
4621 thread.handle_session_update(
4622 acp::SessionUpdate::ToolCall(
4623 acp::ToolCall::new(
4624 acp::ToolCallId::new("test-tool"),
4625 "Test Tool",
4626 )
4627 .kind(acp::ToolKind::Fetch)
4628 .status(acp::ToolCallStatus::InProgress),
4629 ),
4630 cx,
4631 )
4632 })
4633 .unwrap()
4634 .unwrap();
4635
4636 Ok(acp::PromptResponse::new(acp::StopReason::Cancelled))
4637 }
4638 .boxed_local()
4639 },
4640 ));
4641
4642 let thread = cx
4643 .update(|cx| connection.new_session(project, Path::new(path!("/test")), cx))
4644 .await
4645 .unwrap();
4646
4647 let response = thread
4648 .update(cx, |thread, cx| thread.send_raw("test message", cx))
4649 .await;
4650
4651 let response = response
4652 .expect("send should succeed")
4653 .expect("should have response");
4654 assert_eq!(
4655 response.stop_reason,
4656 acp::StopReason::Cancelled,
4657 "response should have Cancelled stop_reason"
4658 );
4659
4660 thread.read_with(cx, |thread, _| {
4661 let tool_entry = thread
4662 .entries
4663 .iter()
4664 .find_map(|e| {
4665 if let AgentThreadEntry::ToolCall(call) = e {
4666 Some(call)
4667 } else {
4668 None
4669 }
4670 })
4671 .expect("should have tool call entry");
4672
4673 assert!(
4674 matches!(tool_entry.status, ToolCallStatus::Canceled),
4675 "tool should be marked as Canceled when response is Cancelled, got {:?}",
4676 tool_entry.status
4677 );
4678 });
4679 }
4680
4681 #[gpui::test]
4682 async fn test_provisional_title_replaced_by_real_title(cx: &mut TestAppContext) {
4683 init_test(cx);
4684
4685 let fs = FakeFs::new(cx.executor());
4686 let project = Project::test(fs, [], cx).await;
4687 let connection = Rc::new(FakeAgentConnection::new());
4688 let set_title_calls = connection.set_title_calls.clone();
4689
4690 let thread = cx
4691 .update(|cx| connection.new_session(project, Path::new(path!("/test")), cx))
4692 .await
4693 .unwrap();
4694
4695 // Initial title is the default.
4696 thread.read_with(cx, |thread, _| {
4697 assert_eq!(thread.title().as_ref(), "Test");
4698 });
4699
4700 // Setting a provisional title updates the display title.
4701 thread.update(cx, |thread, cx| {
4702 thread.set_provisional_title("Hello, can you help…".into(), cx);
4703 });
4704 thread.read_with(cx, |thread, _| {
4705 assert_eq!(thread.title().as_ref(), "Hello, can you help…");
4706 });
4707
4708 // The provisional title should NOT have propagated to the connection.
4709 assert_eq!(
4710 set_title_calls.borrow().len(),
4711 0,
4712 "provisional title should not propagate to the connection"
4713 );
4714
4715 // When the real title arrives via set_title, it replaces the
4716 // provisional title and propagates to the connection.
4717 let task = thread.update(cx, |thread, cx| {
4718 thread.set_title("Helping with Rust question".into(), cx)
4719 });
4720 task.await.expect("set_title should succeed");
4721 thread.read_with(cx, |thread, _| {
4722 assert_eq!(thread.title().as_ref(), "Helping with Rust question");
4723 });
4724 assert_eq!(
4725 set_title_calls.borrow().as_slice(),
4726 &[SharedString::from("Helping with Rust question")],
4727 "real title should propagate to the connection"
4728 );
4729 }
4730}