1use acp_thread::{AgentConnection, Plan};
2use agent_servers::AgentServer;
3use agent_settings::{AgentSettings, NotifyWhenAgentWaiting};
4use audio::{Audio, Sound};
5use std::cell::RefCell;
6use std::collections::BTreeMap;
7use std::path::Path;
8use std::process::ExitStatus;
9use std::rc::Rc;
10use std::sync::Arc;
11use std::time::Duration;
12
13use agent_client_protocol as acp;
14use assistant_tool::ActionLog;
15use buffer_diff::BufferDiff;
16use collections::{HashMap, HashSet};
17use editor::{
18 AnchorRangeExt, ContextMenuOptions, ContextMenuPlacement, Editor, EditorElement, EditorMode,
19 EditorStyle, MinimapVisibility, MultiBuffer, PathKey,
20};
21use file_icons::FileIcons;
22use gpui::{
23 Action, Animation, AnimationExt, App, BorderStyle, EdgesRefinement, Empty, Entity, EntityId,
24 FocusHandle, Focusable, Hsla, Length, ListOffset, ListState, PlatformDisplay, SharedString,
25 StyleRefinement, Subscription, Task, TextStyle, TextStyleRefinement, Transformation,
26 UnderlineStyle, WeakEntity, Window, WindowHandle, div, linear_color_stop, linear_gradient,
27 list, percentage, point, prelude::*, pulsating_between,
28};
29use language::language_settings::SoftWrap;
30use language::{Buffer, Language};
31use markdown::{HeadingLevelStyles, Markdown, MarkdownElement, MarkdownStyle};
32use parking_lot::Mutex;
33use project::Project;
34use settings::Settings as _;
35use text::{Anchor, BufferSnapshot};
36use theme::ThemeSettings;
37use ui::{Disclosure, Divider, DividerColor, KeyBinding, Tooltip, prelude::*};
38use util::ResultExt;
39use workspace::{CollaboratorId, Workspace};
40use zed_actions::agent::{Chat, NextHistoryMessage, PreviousHistoryMessage};
41
42use ::acp_thread::{
43 AcpThread, AcpThreadEvent, AgentThreadEntry, AssistantMessage, AssistantMessageChunk, Diff,
44 LoadError, MentionPath, ThreadStatus, ToolCall, ToolCallContent, ToolCallStatus,
45};
46
47use crate::acp::completion_provider::{ContextPickerCompletionProvider, MentionSet};
48use crate::acp::message_history::MessageHistory;
49use crate::agent_diff::AgentDiff;
50use crate::message_editor::{MAX_EDITOR_LINES, MIN_EDITOR_LINES};
51use crate::ui::{AgentNotification, AgentNotificationEvent};
52use crate::{
53 AgentDiffPane, AgentPanel, ExpandMessageEditor, Follow, KeepAll, OpenAgentDiff, RejectAll,
54};
55
56const RESPONSE_PADDING_X: Pixels = px(19.);
57
58pub struct AcpThreadView {
59 agent: Rc<dyn AgentServer>,
60 workspace: WeakEntity<Workspace>,
61 project: Entity<Project>,
62 thread_state: ThreadState,
63 diff_editors: HashMap<EntityId, Entity<Editor>>,
64 message_editor: Entity<Editor>,
65 message_set_from_history: Option<BufferSnapshot>,
66 _message_editor_subscription: Subscription,
67 mention_set: Arc<Mutex<MentionSet>>,
68 notifications: Vec<WindowHandle<AgentNotification>>,
69 notification_subscriptions: HashMap<WindowHandle<AgentNotification>, Vec<Subscription>>,
70 last_error: Option<Entity<Markdown>>,
71 list_state: ListState,
72 auth_task: Option<Task<()>>,
73 expanded_tool_calls: HashSet<acp::ToolCallId>,
74 expanded_thinking_blocks: HashSet<(usize, usize)>,
75 edits_expanded: bool,
76 plan_expanded: bool,
77 editor_expanded: bool,
78 message_history: Rc<RefCell<MessageHistory<Vec<acp::ContentBlock>>>>,
79 _cancel_task: Option<Task<()>>,
80}
81
82enum ThreadState {
83 Loading {
84 _task: Task<()>,
85 },
86 Ready {
87 thread: Entity<AcpThread>,
88 _subscription: [Subscription; 2],
89 },
90 LoadError(LoadError),
91 Unauthenticated {
92 connection: Rc<dyn AgentConnection>,
93 },
94 ServerExited {
95 status: ExitStatus,
96 },
97}
98
99impl AcpThreadView {
100 pub fn new(
101 agent: Rc<dyn AgentServer>,
102 workspace: WeakEntity<Workspace>,
103 project: Entity<Project>,
104 message_history: Rc<RefCell<MessageHistory<Vec<acp::ContentBlock>>>>,
105 min_lines: usize,
106 max_lines: Option<usize>,
107 window: &mut Window,
108 cx: &mut Context<Self>,
109 ) -> Self {
110 let language = Language::new(
111 language::LanguageConfig {
112 completion_query_characters: HashSet::from_iter(['.', '-', '_', '@']),
113 ..Default::default()
114 },
115 None,
116 );
117
118 let mention_set = Arc::new(Mutex::new(MentionSet::default()));
119
120 let message_editor = cx.new(|cx| {
121 let buffer = cx.new(|cx| Buffer::local("", cx).with_language(Arc::new(language), cx));
122 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
123
124 let mut editor = Editor::new(
125 editor::EditorMode::AutoHeight {
126 min_lines,
127 max_lines: max_lines,
128 },
129 buffer,
130 None,
131 window,
132 cx,
133 );
134 editor.set_placeholder_text("Message the agent - @ to include files", cx);
135 editor.set_show_indent_guides(false, cx);
136 editor.set_soft_wrap();
137 editor.set_use_modal_editing(true);
138 editor.set_completion_provider(Some(Rc::new(ContextPickerCompletionProvider::new(
139 mention_set.clone(),
140 workspace.clone(),
141 cx.weak_entity(),
142 ))));
143 editor.set_context_menu_options(ContextMenuOptions {
144 min_entries_visible: 12,
145 max_entries_visible: 12,
146 placement: Some(ContextMenuPlacement::Above),
147 });
148 editor
149 });
150
151 let message_editor_subscription =
152 cx.subscribe(&message_editor, |this, editor, event, cx| {
153 if let editor::EditorEvent::BufferEdited = &event {
154 let buffer = editor
155 .read(cx)
156 .buffer()
157 .read(cx)
158 .as_singleton()
159 .unwrap()
160 .read(cx)
161 .snapshot();
162 if let Some(message) = this.message_set_from_history.clone()
163 && message.version() != buffer.version()
164 {
165 this.message_set_from_history = None;
166 }
167
168 if this.message_set_from_history.is_none() {
169 this.message_history.borrow_mut().reset_position();
170 }
171 }
172 });
173
174 let mention_set = mention_set.clone();
175
176 let list_state = ListState::new(0, gpui::ListAlignment::Bottom, px(2048.0));
177
178 Self {
179 agent: agent.clone(),
180 workspace: workspace.clone(),
181 project: project.clone(),
182 thread_state: Self::initial_state(agent, workspace, project, window, cx),
183 message_editor,
184 message_set_from_history: None,
185 _message_editor_subscription: message_editor_subscription,
186 mention_set,
187 notifications: Vec::new(),
188 notification_subscriptions: HashMap::default(),
189 diff_editors: Default::default(),
190 list_state: list_state,
191 last_error: None,
192 auth_task: None,
193 expanded_tool_calls: HashSet::default(),
194 expanded_thinking_blocks: HashSet::default(),
195 edits_expanded: false,
196 plan_expanded: false,
197 editor_expanded: false,
198 message_history,
199 _cancel_task: None,
200 }
201 }
202
203 fn initial_state(
204 agent: Rc<dyn AgentServer>,
205 workspace: WeakEntity<Workspace>,
206 project: Entity<Project>,
207 window: &mut Window,
208 cx: &mut Context<Self>,
209 ) -> ThreadState {
210 let root_dir = project
211 .read(cx)
212 .visible_worktrees(cx)
213 .next()
214 .map(|worktree| worktree.read(cx).abs_path())
215 .unwrap_or_else(|| paths::home_dir().as_path().into());
216
217 let connect_task = agent.connect(&root_dir, &project, cx);
218 let load_task = cx.spawn_in(window, async move |this, cx| {
219 let connection = match connect_task.await {
220 Ok(connection) => connection,
221 Err(err) => {
222 this.update(cx, |this, cx| {
223 this.handle_load_error(err, cx);
224 cx.notify();
225 })
226 .log_err();
227 return;
228 }
229 };
230
231 // this.update_in(cx, |_this, _window, cx| {
232 // let status = connection.exit_status(cx);
233 // cx.spawn(async move |this, cx| {
234 // let status = status.await.ok();
235 // this.update(cx, |this, cx| {
236 // this.thread_state = ThreadState::ServerExited { status };
237 // cx.notify();
238 // })
239 // .ok();
240 // })
241 // .detach();
242 // })
243 // .ok();
244
245 let result = match connection
246 .clone()
247 .new_thread(project.clone(), &root_dir, cx)
248 .await
249 {
250 Err(e) => {
251 let mut cx = cx.clone();
252 if e.is::<acp_thread::AuthRequired>() {
253 this.update(&mut cx, |this, cx| {
254 this.thread_state = ThreadState::Unauthenticated { connection };
255 cx.notify();
256 })
257 .ok();
258 return;
259 } else {
260 Err(e)
261 }
262 }
263 Ok(session_id) => Ok(session_id),
264 };
265
266 this.update_in(cx, |this, window, cx| {
267 match result {
268 Ok(thread) => {
269 let thread_subscription =
270 cx.subscribe_in(&thread, window, Self::handle_thread_event);
271
272 let action_log = thread.read(cx).action_log().clone();
273 let action_log_subscription =
274 cx.observe(&action_log, |_, _, cx| cx.notify());
275
276 this.list_state
277 .splice(0..0, thread.read(cx).entries().len());
278
279 AgentDiff::set_active_thread(&workspace, thread.clone(), window, cx);
280
281 this.thread_state = ThreadState::Ready {
282 thread,
283 _subscription: [thread_subscription, action_log_subscription],
284 };
285
286 cx.notify();
287 }
288 Err(err) => {
289 this.handle_load_error(err, cx);
290 }
291 };
292 })
293 .log_err();
294 });
295
296 ThreadState::Loading { _task: load_task }
297 }
298
299 fn handle_load_error(&mut self, err: anyhow::Error, cx: &mut Context<Self>) {
300 if let Some(load_err) = err.downcast_ref::<LoadError>() {
301 self.thread_state = ThreadState::LoadError(load_err.clone());
302 } else {
303 self.thread_state = ThreadState::LoadError(LoadError::Other(err.to_string().into()))
304 }
305 cx.notify();
306 }
307
308 pub fn thread(&self) -> Option<&Entity<AcpThread>> {
309 match &self.thread_state {
310 ThreadState::Ready { thread, .. } => Some(thread),
311 ThreadState::Unauthenticated { .. }
312 | ThreadState::Loading { .. }
313 | ThreadState::LoadError(..)
314 | ThreadState::ServerExited { .. } => None,
315 }
316 }
317
318 pub fn title(&self, cx: &App) -> SharedString {
319 match &self.thread_state {
320 ThreadState::Ready { thread, .. } => thread.read(cx).title(),
321 ThreadState::Loading { .. } => "Loading…".into(),
322 ThreadState::LoadError(_) => "Failed to load".into(),
323 ThreadState::Unauthenticated { .. } => "Not authenticated".into(),
324 ThreadState::ServerExited { .. } => "Server exited unexpectedly".into(),
325 }
326 }
327
328 pub fn cancel(&mut self, cx: &mut Context<Self>) {
329 self.last_error.take();
330
331 if let Some(thread) = self.thread() {
332 self._cancel_task = Some(thread.update(cx, |thread, cx| thread.cancel(cx)));
333 }
334 }
335
336 pub fn expand_message_editor(
337 &mut self,
338 _: &ExpandMessageEditor,
339 _window: &mut Window,
340 cx: &mut Context<Self>,
341 ) {
342 self.set_editor_is_expanded(!self.editor_expanded, cx);
343 cx.notify();
344 }
345
346 fn set_editor_is_expanded(&mut self, is_expanded: bool, cx: &mut Context<Self>) {
347 self.editor_expanded = is_expanded;
348 self.message_editor.update(cx, |editor, _| {
349 if self.editor_expanded {
350 editor.set_mode(EditorMode::Full {
351 scale_ui_elements_with_buffer_font_size: false,
352 show_active_line_background: false,
353 sized_by_content: false,
354 })
355 } else {
356 editor.set_mode(EditorMode::AutoHeight {
357 min_lines: MIN_EDITOR_LINES,
358 max_lines: Some(MAX_EDITOR_LINES),
359 })
360 }
361 });
362 cx.notify();
363 }
364
365 fn chat(&mut self, _: &Chat, window: &mut Window, cx: &mut Context<Self>) {
366 self.last_error.take();
367
368 let mut ix = 0;
369 let mut chunks: Vec<acp::ContentBlock> = Vec::new();
370 let project = self.project.clone();
371 self.message_editor.update(cx, |editor, cx| {
372 let text = editor.text(cx);
373 editor.display_map.update(cx, |map, cx| {
374 let snapshot = map.snapshot(cx);
375 for (crease_id, crease) in snapshot.crease_snapshot.creases() {
376 if let Some(project_path) =
377 self.mention_set.lock().path_for_crease_id(crease_id)
378 {
379 let crease_range = crease.range().to_offset(&snapshot.buffer_snapshot);
380 if crease_range.start > ix {
381 chunks.push(text[ix..crease_range.start].into());
382 }
383 if let Some(abs_path) = project.read(cx).absolute_path(&project_path, cx) {
384 let path_str = abs_path.display().to_string();
385 chunks.push(acp::ContentBlock::ResourceLink(acp::ResourceLink {
386 uri: path_str.clone(),
387 name: path_str,
388 annotations: None,
389 description: None,
390 mime_type: None,
391 size: None,
392 title: None,
393 }));
394 }
395 ix = crease_range.end;
396 }
397 }
398
399 if ix < text.len() {
400 let last_chunk = text[ix..].trim();
401 if !last_chunk.is_empty() {
402 chunks.push(last_chunk.into());
403 }
404 }
405 })
406 });
407
408 if chunks.is_empty() {
409 return;
410 }
411
412 let Some(thread) = self.thread() else {
413 return;
414 };
415 let task = thread.update(cx, |thread, cx| thread.send(chunks.clone(), cx));
416
417 cx.spawn(async move |this, cx| {
418 let result = task.await;
419
420 this.update(cx, |this, cx| {
421 if let Err(err) = result {
422 this.last_error =
423 Some(cx.new(|cx| Markdown::new(err.to_string().into(), None, None, cx)))
424 }
425 })
426 })
427 .detach();
428
429 let mention_set = self.mention_set.clone();
430
431 self.set_editor_is_expanded(false, cx);
432
433 self.message_editor.update(cx, |editor, cx| {
434 editor.clear(window, cx);
435 editor.remove_creases(mention_set.lock().drain(), cx)
436 });
437
438 self.scroll_to_bottom(cx);
439
440 self.message_history.borrow_mut().push(chunks);
441 }
442
443 fn previous_history_message(
444 &mut self,
445 _: &PreviousHistoryMessage,
446 window: &mut Window,
447 cx: &mut Context<Self>,
448 ) {
449 if self.message_set_from_history.is_none() && !self.message_editor.read(cx).is_empty(cx) {
450 self.message_editor.update(cx, |editor, cx| {
451 editor.move_up(&Default::default(), window, cx);
452 });
453 return;
454 }
455
456 self.message_set_from_history = Self::set_draft_message(
457 self.message_editor.clone(),
458 self.mention_set.clone(),
459 self.project.clone(),
460 self.message_history
461 .borrow_mut()
462 .prev()
463 .map(|blocks| blocks.as_slice()),
464 window,
465 cx,
466 );
467 }
468
469 fn next_history_message(
470 &mut self,
471 _: &NextHistoryMessage,
472 window: &mut Window,
473 cx: &mut Context<Self>,
474 ) {
475 if self.message_set_from_history.is_none() {
476 self.message_editor.update(cx, |editor, cx| {
477 editor.move_down(&Default::default(), window, cx);
478 });
479 return;
480 }
481
482 let mut message_history = self.message_history.borrow_mut();
483 let next_history = message_history.next();
484
485 let set_draft_message = Self::set_draft_message(
486 self.message_editor.clone(),
487 self.mention_set.clone(),
488 self.project.clone(),
489 Some(
490 next_history
491 .map(|blocks| blocks.as_slice())
492 .unwrap_or_else(|| &[]),
493 ),
494 window,
495 cx,
496 );
497 // If we reset the text to an empty string because we ran out of history,
498 // we don't want to mark it as coming from the history
499 self.message_set_from_history = if next_history.is_some() {
500 set_draft_message
501 } else {
502 None
503 };
504 }
505
506 fn open_agent_diff(&mut self, _: &OpenAgentDiff, window: &mut Window, cx: &mut Context<Self>) {
507 if let Some(thread) = self.thread() {
508 AgentDiffPane::deploy(thread.clone(), self.workspace.clone(), window, cx).log_err();
509 }
510 }
511
512 fn open_edited_buffer(
513 &mut self,
514 buffer: &Entity<Buffer>,
515 window: &mut Window,
516 cx: &mut Context<Self>,
517 ) {
518 let Some(thread) = self.thread() else {
519 return;
520 };
521
522 let Some(diff) =
523 AgentDiffPane::deploy(thread.clone(), self.workspace.clone(), window, cx).log_err()
524 else {
525 return;
526 };
527
528 diff.update(cx, |diff, cx| {
529 diff.move_to_path(PathKey::for_buffer(&buffer, cx), window, cx)
530 })
531 }
532
533 fn set_draft_message(
534 message_editor: Entity<Editor>,
535 mention_set: Arc<Mutex<MentionSet>>,
536 project: Entity<Project>,
537 message: Option<&[acp::ContentBlock]>,
538 window: &mut Window,
539 cx: &mut Context<Self>,
540 ) -> Option<BufferSnapshot> {
541 cx.notify();
542
543 let message = message?;
544
545 let mut text = String::new();
546 let mut mentions = Vec::new();
547
548 for chunk in message {
549 match chunk {
550 acp::ContentBlock::Text(text_content) => {
551 text.push_str(&text_content.text);
552 }
553 acp::ContentBlock::ResourceLink(resource_link) => {
554 let path = Path::new(&resource_link.uri);
555 let start = text.len();
556 let content = MentionPath::new(&path).to_string();
557 text.push_str(&content);
558 let end = text.len();
559 if let Some(project_path) =
560 project.read(cx).project_path_for_absolute_path(&path, cx)
561 {
562 let filename: SharedString = path
563 .file_name()
564 .unwrap_or_default()
565 .to_string_lossy()
566 .to_string()
567 .into();
568 mentions.push((start..end, project_path, filename));
569 }
570 }
571 acp::ContentBlock::Image(_)
572 | acp::ContentBlock::Audio(_)
573 | acp::ContentBlock::Resource(_) => {}
574 }
575 }
576
577 let snapshot = message_editor.update(cx, |editor, cx| {
578 editor.set_text(text, window, cx);
579 editor.buffer().read(cx).snapshot(cx)
580 });
581
582 for (range, project_path, filename) in mentions {
583 let crease_icon_path = if project_path.path.is_dir() {
584 FileIcons::get_folder_icon(false, cx)
585 .unwrap_or_else(|| IconName::Folder.path().into())
586 } else {
587 FileIcons::get_icon(Path::new(project_path.path.as_ref()), cx)
588 .unwrap_or_else(|| IconName::File.path().into())
589 };
590
591 let anchor = snapshot.anchor_before(range.start);
592 let crease_id = crate::context_picker::insert_crease_for_mention(
593 anchor.excerpt_id,
594 anchor.text_anchor,
595 range.end - range.start,
596 filename,
597 crease_icon_path,
598 message_editor.clone(),
599 window,
600 cx,
601 );
602 if let Some(crease_id) = crease_id {
603 mention_set.lock().insert(crease_id, project_path);
604 }
605 }
606
607 let snapshot = snapshot.as_singleton().unwrap().2.clone();
608 Some(snapshot.text)
609 }
610
611 fn handle_thread_event(
612 &mut self,
613 thread: &Entity<AcpThread>,
614 event: &AcpThreadEvent,
615 window: &mut Window,
616 cx: &mut Context<Self>,
617 ) {
618 let count = self.list_state.item_count();
619 match event {
620 AcpThreadEvent::NewEntry => {
621 let index = thread.read(cx).entries().len() - 1;
622 self.sync_thread_entry_view(index, window, cx);
623 self.list_state.splice(count..count, 1);
624 }
625 AcpThreadEvent::EntryUpdated(index) => {
626 let index = *index;
627 self.sync_thread_entry_view(index, window, cx);
628 self.list_state.splice(index..index + 1, 1);
629 }
630 AcpThreadEvent::ToolAuthorizationRequired => {
631 self.notify_with_sound("Waiting for tool confirmation", IconName::Info, window, cx);
632 }
633 AcpThreadEvent::Stopped => {
634 let used_tools = thread.read(cx).used_tools_since_last_user_message();
635 self.notify_with_sound(
636 if used_tools {
637 "Finished running tools"
638 } else {
639 "New message"
640 },
641 IconName::ZedAssistant,
642 window,
643 cx,
644 );
645 }
646 AcpThreadEvent::Error => {
647 self.notify_with_sound(
648 "Agent stopped due to an error",
649 IconName::Warning,
650 window,
651 cx,
652 );
653 }
654 AcpThreadEvent::ServerExited(status) => {
655 self.thread_state = ThreadState::ServerExited { status: *status };
656 }
657 }
658 cx.notify();
659 }
660
661 fn sync_thread_entry_view(
662 &mut self,
663 entry_ix: usize,
664 window: &mut Window,
665 cx: &mut Context<Self>,
666 ) {
667 let Some(multibuffers) = self.entry_diff_multibuffers(entry_ix, cx) else {
668 return;
669 };
670
671 let multibuffers = multibuffers.collect::<Vec<_>>();
672
673 for multibuffer in multibuffers {
674 if self.diff_editors.contains_key(&multibuffer.entity_id()) {
675 return;
676 }
677
678 let editor = cx.new(|cx| {
679 let mut editor = Editor::new(
680 EditorMode::Full {
681 scale_ui_elements_with_buffer_font_size: false,
682 show_active_line_background: false,
683 sized_by_content: true,
684 },
685 multibuffer.clone(),
686 None,
687 window,
688 cx,
689 );
690 editor.set_show_gutter(false, cx);
691 editor.disable_inline_diagnostics();
692 editor.disable_expand_excerpt_buttons(cx);
693 editor.set_show_vertical_scrollbar(false, cx);
694 editor.set_minimap_visibility(MinimapVisibility::Disabled, window, cx);
695 editor.set_soft_wrap_mode(SoftWrap::None, cx);
696 editor.scroll_manager.set_forbid_vertical_scroll(true);
697 editor.set_show_indent_guides(false, cx);
698 editor.set_read_only(true);
699 editor.set_show_breakpoints(false, cx);
700 editor.set_show_code_actions(false, cx);
701 editor.set_show_git_diff_gutter(false, cx);
702 editor.set_expand_all_diff_hunks(cx);
703 editor.set_text_style_refinement(TextStyleRefinement {
704 font_size: Some(
705 TextSize::Small
706 .rems(cx)
707 .to_pixels(ThemeSettings::get_global(cx).agent_font_size(cx))
708 .into(),
709 ),
710 ..Default::default()
711 });
712 editor
713 });
714 let entity_id = multibuffer.entity_id();
715 cx.observe_release(&multibuffer, move |this, _, _| {
716 this.diff_editors.remove(&entity_id);
717 })
718 .detach();
719
720 self.diff_editors.insert(entity_id, editor);
721 }
722 }
723
724 fn entry_diff_multibuffers(
725 &self,
726 entry_ix: usize,
727 cx: &App,
728 ) -> Option<impl Iterator<Item = Entity<MultiBuffer>>> {
729 let entry = self.thread()?.read(cx).entries().get(entry_ix)?;
730 Some(entry.diffs().map(|diff| diff.multibuffer.clone()))
731 }
732
733 fn authenticate(
734 &mut self,
735 method: acp::AuthMethodId,
736 window: &mut Window,
737 cx: &mut Context<Self>,
738 ) {
739 let ThreadState::Unauthenticated { ref connection } = self.thread_state else {
740 return;
741 };
742
743 self.last_error.take();
744 let authenticate = connection.authenticate(method, cx);
745 self.auth_task = Some(cx.spawn_in(window, {
746 let project = self.project.clone();
747 let agent = self.agent.clone();
748 async move |this, cx| {
749 let result = authenticate.await;
750
751 this.update_in(cx, |this, window, cx| {
752 if let Err(err) = result {
753 this.last_error = Some(cx.new(|cx| {
754 Markdown::new(format!("Error: {err}").into(), None, None, cx)
755 }))
756 } else {
757 this.thread_state = Self::initial_state(
758 agent,
759 this.workspace.clone(),
760 project.clone(),
761 window,
762 cx,
763 )
764 }
765 this.auth_task.take()
766 })
767 .ok();
768 }
769 }));
770 }
771
772 fn authorize_tool_call(
773 &mut self,
774 tool_call_id: acp::ToolCallId,
775 option_id: acp::PermissionOptionId,
776 option_kind: acp::PermissionOptionKind,
777 cx: &mut Context<Self>,
778 ) {
779 let Some(thread) = self.thread() else {
780 return;
781 };
782 thread.update(cx, |thread, cx| {
783 thread.authorize_tool_call(tool_call_id, option_id, option_kind, cx);
784 });
785 cx.notify();
786 }
787
788 fn render_entry(
789 &self,
790 index: usize,
791 total_entries: usize,
792 entry: &AgentThreadEntry,
793 window: &mut Window,
794 cx: &Context<Self>,
795 ) -> AnyElement {
796 let primary = match &entry {
797 AgentThreadEntry::UserMessage(message) => div()
798 .py_4()
799 .px_2()
800 .child(
801 v_flex()
802 .p_3()
803 .gap_1p5()
804 .rounded_lg()
805 .shadow_md()
806 .bg(cx.theme().colors().editor_background)
807 .border_1()
808 .border_color(cx.theme().colors().border)
809 .text_xs()
810 .children(message.content.markdown().map(|md| {
811 self.render_markdown(
812 md.clone(),
813 user_message_markdown_style(window, cx),
814 )
815 })),
816 )
817 .into_any(),
818 AgentThreadEntry::AssistantMessage(AssistantMessage { chunks }) => {
819 let style = default_markdown_style(false, window, cx);
820 let message_body = v_flex()
821 .w_full()
822 .gap_2p5()
823 .children(chunks.iter().enumerate().filter_map(
824 |(chunk_ix, chunk)| match chunk {
825 AssistantMessageChunk::Message { block } => {
826 block.markdown().map(|md| {
827 self.render_markdown(md.clone(), style.clone())
828 .into_any_element()
829 })
830 }
831 AssistantMessageChunk::Thought { block } => {
832 block.markdown().map(|md| {
833 self.render_thinking_block(
834 index,
835 chunk_ix,
836 md.clone(),
837 window,
838 cx,
839 )
840 .into_any_element()
841 })
842 }
843 },
844 ))
845 .into_any();
846
847 v_flex()
848 .px_5()
849 .py_1()
850 .when(index + 1 == total_entries, |this| this.pb_4())
851 .w_full()
852 .text_ui(cx)
853 .child(message_body)
854 .into_any()
855 }
856 AgentThreadEntry::ToolCall(tool_call) => div()
857 .py_1p5()
858 .px_5()
859 .child(self.render_tool_call(index, tool_call, window, cx))
860 .into_any(),
861 };
862
863 let Some(thread) = self.thread() else {
864 return primary;
865 };
866 let is_generating = matches!(thread.read(cx).status(), ThreadStatus::Generating);
867 if index == total_entries - 1 && !is_generating {
868 v_flex()
869 .w_full()
870 .child(primary)
871 .child(self.render_thread_controls(cx))
872 .into_any_element()
873 } else {
874 primary
875 }
876 }
877
878 fn tool_card_header_bg(&self, cx: &Context<Self>) -> Hsla {
879 cx.theme()
880 .colors()
881 .element_background
882 .blend(cx.theme().colors().editor_foreground.opacity(0.025))
883 }
884
885 fn tool_card_border_color(&self, cx: &Context<Self>) -> Hsla {
886 cx.theme().colors().border.opacity(0.6)
887 }
888
889 fn tool_name_font_size(&self) -> Rems {
890 rems_from_px(13.)
891 }
892
893 fn render_thinking_block(
894 &self,
895 entry_ix: usize,
896 chunk_ix: usize,
897 chunk: Entity<Markdown>,
898 window: &Window,
899 cx: &Context<Self>,
900 ) -> AnyElement {
901 let header_id = SharedString::from(format!("thinking-block-header-{}", entry_ix));
902 let key = (entry_ix, chunk_ix);
903 let is_open = self.expanded_thinking_blocks.contains(&key);
904
905 v_flex()
906 .child(
907 h_flex()
908 .id(header_id)
909 .group("disclosure-header")
910 .w_full()
911 .justify_between()
912 .opacity(0.8)
913 .hover(|style| style.opacity(1.))
914 .child(
915 h_flex()
916 .gap_1p5()
917 .child(
918 Icon::new(IconName::ToolBulb)
919 .size(IconSize::Small)
920 .color(Color::Muted),
921 )
922 .child(
923 div()
924 .text_size(self.tool_name_font_size())
925 .child("Thinking"),
926 ),
927 )
928 .child(
929 div().visible_on_hover("disclosure-header").child(
930 Disclosure::new("thinking-disclosure", is_open)
931 .opened_icon(IconName::ChevronUp)
932 .closed_icon(IconName::ChevronDown)
933 .on_click(cx.listener({
934 move |this, _event, _window, cx| {
935 if is_open {
936 this.expanded_thinking_blocks.remove(&key);
937 } else {
938 this.expanded_thinking_blocks.insert(key);
939 }
940 cx.notify();
941 }
942 })),
943 ),
944 )
945 .on_click(cx.listener({
946 move |this, _event, _window, cx| {
947 if is_open {
948 this.expanded_thinking_blocks.remove(&key);
949 } else {
950 this.expanded_thinking_blocks.insert(key);
951 }
952 cx.notify();
953 }
954 })),
955 )
956 .when(is_open, |this| {
957 this.child(
958 div()
959 .relative()
960 .mt_1p5()
961 .ml(px(7.))
962 .pl_4()
963 .border_l_1()
964 .border_color(self.tool_card_border_color(cx))
965 .text_ui_sm(cx)
966 .child(
967 self.render_markdown(chunk, default_markdown_style(false, window, cx)),
968 ),
969 )
970 })
971 .into_any_element()
972 }
973
974 fn render_tool_call(
975 &self,
976 entry_ix: usize,
977 tool_call: &ToolCall,
978 window: &Window,
979 cx: &Context<Self>,
980 ) -> Div {
981 let header_id = SharedString::from(format!("tool-call-header-{}", entry_ix));
982
983 let status_icon = match &tool_call.status {
984 ToolCallStatus::Allowed {
985 status: acp::ToolCallStatus::Pending,
986 }
987 | ToolCallStatus::WaitingForConfirmation { .. } => None,
988 ToolCallStatus::Allowed {
989 status: acp::ToolCallStatus::InProgress,
990 ..
991 } => Some(
992 Icon::new(IconName::ArrowCircle)
993 .color(Color::Accent)
994 .size(IconSize::Small)
995 .with_animation(
996 "running",
997 Animation::new(Duration::from_secs(2)).repeat(),
998 |icon, delta| icon.transform(Transformation::rotate(percentage(delta))),
999 )
1000 .into_any(),
1001 ),
1002 ToolCallStatus::Allowed {
1003 status: acp::ToolCallStatus::Completed,
1004 ..
1005 } => None,
1006 ToolCallStatus::Rejected
1007 | ToolCallStatus::Canceled
1008 | ToolCallStatus::Allowed {
1009 status: acp::ToolCallStatus::Failed,
1010 ..
1011 } => Some(
1012 Icon::new(IconName::X)
1013 .color(Color::Error)
1014 .size(IconSize::Small)
1015 .into_any_element(),
1016 ),
1017 };
1018
1019 let needs_confirmation = match &tool_call.status {
1020 ToolCallStatus::WaitingForConfirmation { .. } => true,
1021 _ => tool_call
1022 .content
1023 .iter()
1024 .any(|content| matches!(content, ToolCallContent::Diff { .. })),
1025 };
1026
1027 let is_collapsible = !tool_call.content.is_empty() && !needs_confirmation;
1028 let is_open = !is_collapsible || self.expanded_tool_calls.contains(&tool_call.id);
1029
1030 v_flex()
1031 .when(needs_confirmation, |this| {
1032 this.rounded_lg()
1033 .border_1()
1034 .border_color(self.tool_card_border_color(cx))
1035 .bg(cx.theme().colors().editor_background)
1036 .overflow_hidden()
1037 })
1038 .child(
1039 h_flex()
1040 .id(header_id)
1041 .w_full()
1042 .gap_1()
1043 .justify_between()
1044 .map(|this| {
1045 if needs_confirmation {
1046 this.px_2()
1047 .py_1()
1048 .rounded_t_md()
1049 .bg(self.tool_card_header_bg(cx))
1050 .border_b_1()
1051 .border_color(self.tool_card_border_color(cx))
1052 } else {
1053 this.opacity(0.8).hover(|style| style.opacity(1.))
1054 }
1055 })
1056 .child(
1057 h_flex()
1058 .id("tool-call-header")
1059 .overflow_x_scroll()
1060 .map(|this| {
1061 if needs_confirmation {
1062 this.text_xs()
1063 } else {
1064 this.text_size(self.tool_name_font_size())
1065 }
1066 })
1067 .gap_1p5()
1068 .child(
1069 Icon::new(match tool_call.kind {
1070 acp::ToolKind::Read => IconName::ToolRead,
1071 acp::ToolKind::Edit => IconName::ToolPencil,
1072 acp::ToolKind::Delete => IconName::ToolDeleteFile,
1073 acp::ToolKind::Move => IconName::ArrowRightLeft,
1074 acp::ToolKind::Search => IconName::ToolSearch,
1075 acp::ToolKind::Execute => IconName::ToolTerminal,
1076 acp::ToolKind::Think => IconName::ToolBulb,
1077 acp::ToolKind::Fetch => IconName::ToolWeb,
1078 acp::ToolKind::Other => IconName::ToolHammer,
1079 })
1080 .size(IconSize::Small)
1081 .color(Color::Muted),
1082 )
1083 .child(if tool_call.locations.len() == 1 {
1084 let name = tool_call.locations[0]
1085 .path
1086 .file_name()
1087 .unwrap_or_default()
1088 .display()
1089 .to_string();
1090
1091 h_flex()
1092 .id(("open-tool-call-location", entry_ix))
1093 .child(name)
1094 .w_full()
1095 .max_w_full()
1096 .pr_1()
1097 .gap_0p5()
1098 .cursor_pointer()
1099 .rounded_sm()
1100 .opacity(0.8)
1101 .hover(|label| {
1102 label.opacity(1.).bg(cx
1103 .theme()
1104 .colors()
1105 .element_hover
1106 .opacity(0.5))
1107 })
1108 .tooltip(Tooltip::text("Jump to File"))
1109 .on_click(cx.listener(move |this, _, window, cx| {
1110 this.open_tool_call_location(entry_ix, 0, window, cx);
1111 }))
1112 .into_any_element()
1113 } else {
1114 self.render_markdown(
1115 tool_call.label.clone(),
1116 default_markdown_style(needs_confirmation, window, cx),
1117 )
1118 .into_any()
1119 }),
1120 )
1121 .child(
1122 h_flex()
1123 .gap_0p5()
1124 .when(is_collapsible, |this| {
1125 this.child(
1126 Disclosure::new(("expand", entry_ix), is_open)
1127 .opened_icon(IconName::ChevronUp)
1128 .closed_icon(IconName::ChevronDown)
1129 .on_click(cx.listener({
1130 let id = tool_call.id.clone();
1131 move |this: &mut Self, _, _, cx: &mut Context<Self>| {
1132 if is_open {
1133 this.expanded_tool_calls.remove(&id);
1134 } else {
1135 this.expanded_tool_calls.insert(id.clone());
1136 }
1137 cx.notify();
1138 }
1139 })),
1140 )
1141 })
1142 .children(status_icon),
1143 )
1144 .on_click(cx.listener({
1145 let id = tool_call.id.clone();
1146 move |this: &mut Self, _, _, cx: &mut Context<Self>| {
1147 if is_open {
1148 this.expanded_tool_calls.remove(&id);
1149 } else {
1150 this.expanded_tool_calls.insert(id.clone());
1151 }
1152 cx.notify();
1153 }
1154 })),
1155 )
1156 .when(is_open, |this| {
1157 this.child(
1158 v_flex()
1159 .text_xs()
1160 .when(is_collapsible, |this| {
1161 this.mt_1()
1162 .border_1()
1163 .border_color(self.tool_card_border_color(cx))
1164 .bg(cx.theme().colors().editor_background)
1165 .rounded_lg()
1166 })
1167 .map(|this| {
1168 if is_open {
1169 match &tool_call.status {
1170 ToolCallStatus::WaitingForConfirmation { options, .. } => this
1171 .children(tool_call.content.iter().map(|content| {
1172 div()
1173 .py_1p5()
1174 .child(
1175 self.render_tool_call_content(
1176 content, window, cx,
1177 ),
1178 )
1179 .into_any_element()
1180 }))
1181 .child(self.render_permission_buttons(
1182 options,
1183 entry_ix,
1184 tool_call.id.clone(),
1185 tool_call.content.is_empty(),
1186 cx,
1187 )),
1188 ToolCallStatus::Allowed { .. } | ToolCallStatus::Canceled => {
1189 this.children(tool_call.content.iter().map(|content| {
1190 div()
1191 .py_1p5()
1192 .child(
1193 self.render_tool_call_content(
1194 content, window, cx,
1195 ),
1196 )
1197 .into_any_element()
1198 }))
1199 }
1200 ToolCallStatus::Rejected => this,
1201 }
1202 } else {
1203 this
1204 }
1205 }),
1206 )
1207 })
1208 }
1209
1210 fn render_tool_call_content(
1211 &self,
1212 content: &ToolCallContent,
1213 window: &Window,
1214 cx: &Context<Self>,
1215 ) -> AnyElement {
1216 match content {
1217 ToolCallContent::ContentBlock { content } => {
1218 if let Some(md) = content.markdown() {
1219 div()
1220 .p_2()
1221 .child(
1222 self.render_markdown(
1223 md.clone(),
1224 default_markdown_style(false, window, cx),
1225 ),
1226 )
1227 .into_any_element()
1228 } else {
1229 Empty.into_any_element()
1230 }
1231 }
1232 ToolCallContent::Diff {
1233 diff: Diff { multibuffer, .. },
1234 ..
1235 } => self.render_diff_editor(multibuffer),
1236 }
1237 }
1238
1239 fn render_permission_buttons(
1240 &self,
1241 options: &[acp::PermissionOption],
1242 entry_ix: usize,
1243 tool_call_id: acp::ToolCallId,
1244 empty_content: bool,
1245 cx: &Context<Self>,
1246 ) -> Div {
1247 h_flex()
1248 .py_1p5()
1249 .px_1p5()
1250 .gap_1()
1251 .justify_end()
1252 .when(!empty_content, |this| {
1253 this.border_t_1()
1254 .border_color(self.tool_card_border_color(cx))
1255 })
1256 .children(options.iter().map(|option| {
1257 let option_id = SharedString::from(option.id.0.clone());
1258 Button::new((option_id, entry_ix), option.name.clone())
1259 .map(|this| match option.kind {
1260 acp::PermissionOptionKind::AllowOnce => {
1261 this.icon(IconName::Check).icon_color(Color::Success)
1262 }
1263 acp::PermissionOptionKind::AllowAlways => {
1264 this.icon(IconName::CheckDouble).icon_color(Color::Success)
1265 }
1266 acp::PermissionOptionKind::RejectOnce => {
1267 this.icon(IconName::X).icon_color(Color::Error)
1268 }
1269 acp::PermissionOptionKind::RejectAlways => {
1270 this.icon(IconName::X).icon_color(Color::Error)
1271 }
1272 })
1273 .icon_position(IconPosition::Start)
1274 .icon_size(IconSize::XSmall)
1275 .on_click(cx.listener({
1276 let tool_call_id = tool_call_id.clone();
1277 let option_id = option.id.clone();
1278 let option_kind = option.kind;
1279 move |this, _, _, cx| {
1280 this.authorize_tool_call(
1281 tool_call_id.clone(),
1282 option_id.clone(),
1283 option_kind,
1284 cx,
1285 );
1286 }
1287 }))
1288 }))
1289 }
1290
1291 fn render_diff_editor(&self, multibuffer: &Entity<MultiBuffer>) -> AnyElement {
1292 v_flex()
1293 .h_full()
1294 .child(
1295 if let Some(editor) = self.diff_editors.get(&multibuffer.entity_id()) {
1296 editor.clone().into_any_element()
1297 } else {
1298 Empty.into_any()
1299 },
1300 )
1301 .into_any()
1302 }
1303
1304 fn render_agent_logo(&self) -> AnyElement {
1305 Icon::new(self.agent.logo())
1306 .color(Color::Muted)
1307 .size(IconSize::XLarge)
1308 .into_any_element()
1309 }
1310
1311 fn render_error_agent_logo(&self) -> AnyElement {
1312 let logo = Icon::new(self.agent.logo())
1313 .color(Color::Muted)
1314 .size(IconSize::XLarge)
1315 .into_any_element();
1316
1317 h_flex()
1318 .relative()
1319 .justify_center()
1320 .child(div().opacity(0.3).child(logo))
1321 .child(
1322 h_flex().absolute().right_1().bottom_0().child(
1323 Icon::new(IconName::XCircle)
1324 .color(Color::Error)
1325 .size(IconSize::Small),
1326 ),
1327 )
1328 .into_any_element()
1329 }
1330
1331 fn render_empty_state(&self, cx: &App) -> AnyElement {
1332 let loading = matches!(&self.thread_state, ThreadState::Loading { .. });
1333
1334 v_flex()
1335 .size_full()
1336 .items_center()
1337 .justify_center()
1338 .child(if loading {
1339 h_flex()
1340 .justify_center()
1341 .child(self.render_agent_logo())
1342 .with_animation(
1343 "pulsating_icon",
1344 Animation::new(Duration::from_secs(2))
1345 .repeat()
1346 .with_easing(pulsating_between(0.4, 1.0)),
1347 |icon, delta| icon.opacity(delta),
1348 )
1349 .into_any()
1350 } else {
1351 self.render_agent_logo().into_any_element()
1352 })
1353 .child(h_flex().mt_4().mb_1().justify_center().child(if loading {
1354 div()
1355 .child(LoadingLabel::new("").size(LabelSize::Large))
1356 .into_any_element()
1357 } else {
1358 Headline::new(self.agent.empty_state_headline())
1359 .size(HeadlineSize::Medium)
1360 .into_any_element()
1361 }))
1362 .child(
1363 div()
1364 .max_w_1_2()
1365 .text_sm()
1366 .text_center()
1367 .map(|this| {
1368 if loading {
1369 this.invisible()
1370 } else {
1371 this.text_color(cx.theme().colors().text_muted)
1372 }
1373 })
1374 .child(self.agent.empty_state_message()),
1375 )
1376 .into_any()
1377 }
1378
1379 fn render_pending_auth_state(&self) -> AnyElement {
1380 v_flex()
1381 .items_center()
1382 .justify_center()
1383 .child(self.render_error_agent_logo())
1384 .child(
1385 h_flex()
1386 .mt_4()
1387 .mb_1()
1388 .justify_center()
1389 .child(Headline::new("Not Authenticated").size(HeadlineSize::Medium)),
1390 )
1391 .into_any()
1392 }
1393
1394 fn render_server_exited(&self, status: ExitStatus, _cx: &Context<Self>) -> AnyElement {
1395 v_flex()
1396 .items_center()
1397 .justify_center()
1398 .child(self.render_error_agent_logo())
1399 .child(
1400 v_flex()
1401 .mt_4()
1402 .mb_2()
1403 .gap_0p5()
1404 .text_center()
1405 .items_center()
1406 .child(Headline::new("Server exited unexpectedly").size(HeadlineSize::Medium))
1407 .child(
1408 Label::new(format!("Exit status: {}", status.code().unwrap_or(-127)))
1409 .size(LabelSize::Small)
1410 .color(Color::Muted),
1411 ),
1412 )
1413 .into_any_element()
1414 }
1415
1416 fn render_load_error(&self, e: &LoadError, cx: &Context<Self>) -> AnyElement {
1417 let mut container = v_flex()
1418 .items_center()
1419 .justify_center()
1420 .child(self.render_error_agent_logo())
1421 .child(
1422 v_flex()
1423 .mt_4()
1424 .mb_2()
1425 .gap_0p5()
1426 .text_center()
1427 .items_center()
1428 .child(Headline::new("Failed to launch").size(HeadlineSize::Medium))
1429 .child(
1430 Label::new(e.to_string())
1431 .size(LabelSize::Small)
1432 .color(Color::Muted),
1433 ),
1434 );
1435
1436 if let LoadError::Unsupported {
1437 upgrade_message,
1438 upgrade_command,
1439 ..
1440 } = &e
1441 {
1442 let upgrade_message = upgrade_message.clone();
1443 let upgrade_command = upgrade_command.clone();
1444 container = container.child(Button::new("upgrade", upgrade_message).on_click(
1445 cx.listener(move |this, _, window, cx| {
1446 this.workspace
1447 .update(cx, |workspace, cx| {
1448 let project = workspace.project().read(cx);
1449 let cwd = project.first_project_directory(cx);
1450 let shell = project.terminal_settings(&cwd, cx).shell.clone();
1451 let spawn_in_terminal = task::SpawnInTerminal {
1452 id: task::TaskId("install".to_string()),
1453 full_label: upgrade_command.clone(),
1454 label: upgrade_command.clone(),
1455 command: Some(upgrade_command.clone()),
1456 args: Vec::new(),
1457 command_label: upgrade_command.clone(),
1458 cwd,
1459 env: Default::default(),
1460 use_new_terminal: true,
1461 allow_concurrent_runs: true,
1462 reveal: Default::default(),
1463 reveal_target: Default::default(),
1464 hide: Default::default(),
1465 shell,
1466 show_summary: true,
1467 show_command: true,
1468 show_rerun: false,
1469 };
1470 workspace
1471 .spawn_in_terminal(spawn_in_terminal, window, cx)
1472 .detach();
1473 })
1474 .ok();
1475 }),
1476 ));
1477 }
1478
1479 container.into_any()
1480 }
1481
1482 fn render_activity_bar(
1483 &self,
1484 thread_entity: &Entity<AcpThread>,
1485 window: &mut Window,
1486 cx: &Context<Self>,
1487 ) -> Option<AnyElement> {
1488 let thread = thread_entity.read(cx);
1489 let action_log = thread.action_log();
1490 let changed_buffers = action_log.read(cx).changed_buffers(cx);
1491 let plan = thread.plan();
1492
1493 if changed_buffers.is_empty() && plan.is_empty() {
1494 return None;
1495 }
1496
1497 let editor_bg_color = cx.theme().colors().editor_background;
1498 let active_color = cx.theme().colors().element_selected;
1499 let bg_edit_files_disclosure = editor_bg_color.blend(active_color.opacity(0.3));
1500
1501 let pending_edits = thread.has_pending_edit_tool_calls();
1502
1503 v_flex()
1504 .mt_1()
1505 .mx_2()
1506 .bg(bg_edit_files_disclosure)
1507 .border_1()
1508 .border_b_0()
1509 .border_color(cx.theme().colors().border)
1510 .rounded_t_md()
1511 .shadow(vec![gpui::BoxShadow {
1512 color: gpui::black().opacity(0.15),
1513 offset: point(px(1.), px(-1.)),
1514 blur_radius: px(3.),
1515 spread_radius: px(0.),
1516 }])
1517 .when(!plan.is_empty(), |this| {
1518 this.child(self.render_plan_summary(plan, window, cx))
1519 .when(self.plan_expanded, |parent| {
1520 parent.child(self.render_plan_entries(plan, window, cx))
1521 })
1522 })
1523 .when(!changed_buffers.is_empty(), |this| {
1524 this.child(Divider::horizontal())
1525 .child(self.render_edits_summary(
1526 action_log,
1527 &changed_buffers,
1528 self.edits_expanded,
1529 pending_edits,
1530 window,
1531 cx,
1532 ))
1533 .when(self.edits_expanded, |parent| {
1534 parent.child(self.render_edited_files(
1535 action_log,
1536 &changed_buffers,
1537 pending_edits,
1538 cx,
1539 ))
1540 })
1541 })
1542 .into_any()
1543 .into()
1544 }
1545
1546 fn render_plan_summary(&self, plan: &Plan, window: &mut Window, cx: &Context<Self>) -> Div {
1547 let stats = plan.stats();
1548
1549 let title = if let Some(entry) = stats.in_progress_entry
1550 && !self.plan_expanded
1551 {
1552 h_flex()
1553 .w_full()
1554 .gap_1()
1555 .text_xs()
1556 .text_color(cx.theme().colors().text_muted)
1557 .justify_between()
1558 .child(
1559 h_flex()
1560 .gap_1()
1561 .child(
1562 Label::new("Current:")
1563 .size(LabelSize::Small)
1564 .color(Color::Muted),
1565 )
1566 .child(MarkdownElement::new(
1567 entry.content.clone(),
1568 plan_label_markdown_style(&entry.status, window, cx),
1569 )),
1570 )
1571 .when(stats.pending > 0, |this| {
1572 this.child(
1573 Label::new(format!("{} left", stats.pending))
1574 .size(LabelSize::Small)
1575 .color(Color::Muted)
1576 .mr_1(),
1577 )
1578 })
1579 } else {
1580 let status_label = if stats.pending == 0 {
1581 "All Done".to_string()
1582 } else if stats.completed == 0 {
1583 format!("{}", plan.entries.len())
1584 } else {
1585 format!("{}/{}", stats.completed, plan.entries.len())
1586 };
1587
1588 h_flex()
1589 .w_full()
1590 .gap_1()
1591 .justify_between()
1592 .child(
1593 Label::new("Plan")
1594 .size(LabelSize::Small)
1595 .color(Color::Muted),
1596 )
1597 .child(
1598 Label::new(status_label)
1599 .size(LabelSize::Small)
1600 .color(Color::Muted)
1601 .mr_1(),
1602 )
1603 };
1604
1605 h_flex()
1606 .p_1()
1607 .justify_between()
1608 .when(self.plan_expanded, |this| {
1609 this.border_b_1().border_color(cx.theme().colors().border)
1610 })
1611 .child(
1612 h_flex()
1613 .id("plan_summary")
1614 .w_full()
1615 .gap_1()
1616 .child(Disclosure::new("plan_disclosure", self.plan_expanded))
1617 .child(title)
1618 .on_click(cx.listener(|this, _, _, cx| {
1619 this.plan_expanded = !this.plan_expanded;
1620 cx.notify();
1621 })),
1622 )
1623 }
1624
1625 fn render_plan_entries(&self, plan: &Plan, window: &mut Window, cx: &Context<Self>) -> Div {
1626 v_flex().children(plan.entries.iter().enumerate().flat_map(|(index, entry)| {
1627 let element = h_flex()
1628 .py_1()
1629 .px_2()
1630 .gap_2()
1631 .justify_between()
1632 .bg(cx.theme().colors().editor_background)
1633 .when(index < plan.entries.len() - 1, |parent| {
1634 parent.border_color(cx.theme().colors().border).border_b_1()
1635 })
1636 .child(
1637 h_flex()
1638 .id(("plan_entry", index))
1639 .gap_1p5()
1640 .max_w_full()
1641 .overflow_x_scroll()
1642 .text_xs()
1643 .text_color(cx.theme().colors().text_muted)
1644 .child(match entry.status {
1645 acp::PlanEntryStatus::Pending => Icon::new(IconName::TodoPending)
1646 .size(IconSize::Small)
1647 .color(Color::Muted)
1648 .into_any_element(),
1649 acp::PlanEntryStatus::InProgress => Icon::new(IconName::TodoProgress)
1650 .size(IconSize::Small)
1651 .color(Color::Accent)
1652 .with_animation(
1653 "running",
1654 Animation::new(Duration::from_secs(2)).repeat(),
1655 |icon, delta| {
1656 icon.transform(Transformation::rotate(percentage(delta)))
1657 },
1658 )
1659 .into_any_element(),
1660 acp::PlanEntryStatus::Completed => Icon::new(IconName::TodoComplete)
1661 .size(IconSize::Small)
1662 .color(Color::Success)
1663 .into_any_element(),
1664 })
1665 .child(MarkdownElement::new(
1666 entry.content.clone(),
1667 plan_label_markdown_style(&entry.status, window, cx),
1668 )),
1669 );
1670
1671 Some(element)
1672 }))
1673 }
1674
1675 fn render_edits_summary(
1676 &self,
1677 action_log: &Entity<ActionLog>,
1678 changed_buffers: &BTreeMap<Entity<Buffer>, Entity<BufferDiff>>,
1679 expanded: bool,
1680 pending_edits: bool,
1681 window: &mut Window,
1682 cx: &Context<Self>,
1683 ) -> Div {
1684 const EDIT_NOT_READY_TOOLTIP_LABEL: &str = "Wait until file edits are complete.";
1685
1686 let focus_handle = self.focus_handle(cx);
1687
1688 h_flex()
1689 .p_1()
1690 .justify_between()
1691 .when(expanded, |this| {
1692 this.border_b_1().border_color(cx.theme().colors().border)
1693 })
1694 .child(
1695 h_flex()
1696 .id("edits-container")
1697 .cursor_pointer()
1698 .w_full()
1699 .gap_1()
1700 .child(Disclosure::new("edits-disclosure", expanded))
1701 .map(|this| {
1702 if pending_edits {
1703 this.child(
1704 Label::new(format!(
1705 "Editing {} {}…",
1706 changed_buffers.len(),
1707 if changed_buffers.len() == 1 {
1708 "file"
1709 } else {
1710 "files"
1711 }
1712 ))
1713 .color(Color::Muted)
1714 .size(LabelSize::Small)
1715 .with_animation(
1716 "edit-label",
1717 Animation::new(Duration::from_secs(2))
1718 .repeat()
1719 .with_easing(pulsating_between(0.3, 0.7)),
1720 |label, delta| label.alpha(delta),
1721 ),
1722 )
1723 } else {
1724 this.child(
1725 Label::new("Edits")
1726 .size(LabelSize::Small)
1727 .color(Color::Muted),
1728 )
1729 .child(Label::new("•").size(LabelSize::XSmall).color(Color::Muted))
1730 .child(
1731 Label::new(format!(
1732 "{} {}",
1733 changed_buffers.len(),
1734 if changed_buffers.len() == 1 {
1735 "file"
1736 } else {
1737 "files"
1738 }
1739 ))
1740 .size(LabelSize::Small)
1741 .color(Color::Muted),
1742 )
1743 }
1744 })
1745 .on_click(cx.listener(|this, _, _, cx| {
1746 this.edits_expanded = !this.edits_expanded;
1747 cx.notify();
1748 })),
1749 )
1750 .child(
1751 h_flex()
1752 .gap_1()
1753 .child(
1754 IconButton::new("review-changes", IconName::ListTodo)
1755 .icon_size(IconSize::Small)
1756 .tooltip({
1757 let focus_handle = focus_handle.clone();
1758 move |window, cx| {
1759 Tooltip::for_action_in(
1760 "Review Changes",
1761 &OpenAgentDiff,
1762 &focus_handle,
1763 window,
1764 cx,
1765 )
1766 }
1767 })
1768 .on_click(cx.listener(|_, _, window, cx| {
1769 window.dispatch_action(OpenAgentDiff.boxed_clone(), cx);
1770 })),
1771 )
1772 .child(Divider::vertical().color(DividerColor::Border))
1773 .child(
1774 Button::new("reject-all-changes", "Reject All")
1775 .label_size(LabelSize::Small)
1776 .disabled(pending_edits)
1777 .when(pending_edits, |this| {
1778 this.tooltip(Tooltip::text(EDIT_NOT_READY_TOOLTIP_LABEL))
1779 })
1780 .key_binding(
1781 KeyBinding::for_action_in(
1782 &RejectAll,
1783 &focus_handle.clone(),
1784 window,
1785 cx,
1786 )
1787 .map(|kb| kb.size(rems_from_px(10.))),
1788 )
1789 .on_click({
1790 let action_log = action_log.clone();
1791 cx.listener(move |_, _, _, cx| {
1792 action_log.update(cx, |action_log, cx| {
1793 action_log.reject_all_edits(cx).detach();
1794 })
1795 })
1796 }),
1797 )
1798 .child(
1799 Button::new("keep-all-changes", "Keep All")
1800 .label_size(LabelSize::Small)
1801 .disabled(pending_edits)
1802 .when(pending_edits, |this| {
1803 this.tooltip(Tooltip::text(EDIT_NOT_READY_TOOLTIP_LABEL))
1804 })
1805 .key_binding(
1806 KeyBinding::for_action_in(&KeepAll, &focus_handle, window, cx)
1807 .map(|kb| kb.size(rems_from_px(10.))),
1808 )
1809 .on_click({
1810 let action_log = action_log.clone();
1811 cx.listener(move |_, _, _, cx| {
1812 action_log.update(cx, |action_log, cx| {
1813 action_log.keep_all_edits(cx);
1814 })
1815 })
1816 }),
1817 ),
1818 )
1819 }
1820
1821 fn render_edited_files(
1822 &self,
1823 action_log: &Entity<ActionLog>,
1824 changed_buffers: &BTreeMap<Entity<Buffer>, Entity<BufferDiff>>,
1825 pending_edits: bool,
1826 cx: &Context<Self>,
1827 ) -> Div {
1828 let editor_bg_color = cx.theme().colors().editor_background;
1829
1830 v_flex().children(changed_buffers.into_iter().enumerate().flat_map(
1831 |(index, (buffer, _diff))| {
1832 let file = buffer.read(cx).file()?;
1833 let path = file.path();
1834
1835 let file_path = path.parent().and_then(|parent| {
1836 let parent_str = parent.to_string_lossy();
1837
1838 if parent_str.is_empty() {
1839 None
1840 } else {
1841 Some(
1842 Label::new(format!("/{}{}", parent_str, std::path::MAIN_SEPARATOR_STR))
1843 .color(Color::Muted)
1844 .size(LabelSize::XSmall)
1845 .buffer_font(cx),
1846 )
1847 }
1848 });
1849
1850 let file_name = path.file_name().map(|name| {
1851 Label::new(name.to_string_lossy().to_string())
1852 .size(LabelSize::XSmall)
1853 .buffer_font(cx)
1854 });
1855
1856 let file_icon = FileIcons::get_icon(&path, cx)
1857 .map(Icon::from_path)
1858 .map(|icon| icon.color(Color::Muted).size(IconSize::Small))
1859 .unwrap_or_else(|| {
1860 Icon::new(IconName::File)
1861 .color(Color::Muted)
1862 .size(IconSize::Small)
1863 });
1864
1865 let overlay_gradient = linear_gradient(
1866 90.,
1867 linear_color_stop(editor_bg_color, 1.),
1868 linear_color_stop(editor_bg_color.opacity(0.2), 0.),
1869 );
1870
1871 let element = h_flex()
1872 .group("edited-code")
1873 .id(("file-container", index))
1874 .relative()
1875 .py_1()
1876 .pl_2()
1877 .pr_1()
1878 .gap_2()
1879 .justify_between()
1880 .bg(editor_bg_color)
1881 .when(index < changed_buffers.len() - 1, |parent| {
1882 parent.border_color(cx.theme().colors().border).border_b_1()
1883 })
1884 .child(
1885 h_flex()
1886 .id(("file-name", index))
1887 .pr_8()
1888 .gap_1p5()
1889 .max_w_full()
1890 .overflow_x_scroll()
1891 .child(file_icon)
1892 .child(h_flex().gap_0p5().children(file_name).children(file_path))
1893 .on_click({
1894 let buffer = buffer.clone();
1895 cx.listener(move |this, _, window, cx| {
1896 this.open_edited_buffer(&buffer, window, cx);
1897 })
1898 }),
1899 )
1900 .child(
1901 h_flex()
1902 .gap_1()
1903 .visible_on_hover("edited-code")
1904 .child(
1905 Button::new("review", "Review")
1906 .label_size(LabelSize::Small)
1907 .on_click({
1908 let buffer = buffer.clone();
1909 cx.listener(move |this, _, window, cx| {
1910 this.open_edited_buffer(&buffer, window, cx);
1911 })
1912 }),
1913 )
1914 .child(Divider::vertical().color(DividerColor::BorderVariant))
1915 .child(
1916 Button::new("reject-file", "Reject")
1917 .label_size(LabelSize::Small)
1918 .disabled(pending_edits)
1919 .on_click({
1920 let buffer = buffer.clone();
1921 let action_log = action_log.clone();
1922 move |_, _, cx| {
1923 action_log.update(cx, |action_log, cx| {
1924 action_log
1925 .reject_edits_in_ranges(
1926 buffer.clone(),
1927 vec![Anchor::MIN..Anchor::MAX],
1928 cx,
1929 )
1930 .detach_and_log_err(cx);
1931 })
1932 }
1933 }),
1934 )
1935 .child(
1936 Button::new("keep-file", "Keep")
1937 .label_size(LabelSize::Small)
1938 .disabled(pending_edits)
1939 .on_click({
1940 let buffer = buffer.clone();
1941 let action_log = action_log.clone();
1942 move |_, _, cx| {
1943 action_log.update(cx, |action_log, cx| {
1944 action_log.keep_edits_in_range(
1945 buffer.clone(),
1946 Anchor::MIN..Anchor::MAX,
1947 cx,
1948 );
1949 })
1950 }
1951 }),
1952 ),
1953 )
1954 .child(
1955 div()
1956 .id("gradient-overlay")
1957 .absolute()
1958 .h_full()
1959 .w_12()
1960 .top_0()
1961 .bottom_0()
1962 .right(px(152.))
1963 .bg(overlay_gradient),
1964 );
1965
1966 Some(element)
1967 },
1968 ))
1969 }
1970
1971 fn render_message_editor(&mut self, window: &mut Window, cx: &mut Context<Self>) -> AnyElement {
1972 let focus_handle = self.message_editor.focus_handle(cx);
1973 let editor_bg_color = cx.theme().colors().editor_background;
1974 let (expand_icon, expand_tooltip) = if self.editor_expanded {
1975 (IconName::Minimize, "Minimize Message Editor")
1976 } else {
1977 (IconName::Maximize, "Expand Message Editor")
1978 };
1979
1980 v_flex()
1981 .on_action(cx.listener(Self::expand_message_editor))
1982 .p_2()
1983 .gap_2()
1984 .border_t_1()
1985 .border_color(cx.theme().colors().border)
1986 .bg(editor_bg_color)
1987 .when(self.editor_expanded, |this| {
1988 this.h(vh(0.8, window)).size_full().justify_between()
1989 })
1990 .child(
1991 v_flex()
1992 .relative()
1993 .size_full()
1994 .pt_1()
1995 .pr_2p5()
1996 .child(div().flex_1().child({
1997 let settings = ThemeSettings::get_global(cx);
1998 let font_size = TextSize::Small
1999 .rems(cx)
2000 .to_pixels(settings.agent_font_size(cx));
2001 let line_height = settings.buffer_line_height.value() * font_size;
2002
2003 let text_style = TextStyle {
2004 color: cx.theme().colors().text,
2005 font_family: settings.buffer_font.family.clone(),
2006 font_fallbacks: settings.buffer_font.fallbacks.clone(),
2007 font_features: settings.buffer_font.features.clone(),
2008 font_size: font_size.into(),
2009 line_height: line_height.into(),
2010 ..Default::default()
2011 };
2012
2013 EditorElement::new(
2014 &self.message_editor,
2015 EditorStyle {
2016 background: editor_bg_color,
2017 local_player: cx.theme().players().local(),
2018 text: text_style,
2019 syntax: cx.theme().syntax().clone(),
2020 ..Default::default()
2021 },
2022 )
2023 }))
2024 .child(
2025 h_flex()
2026 .absolute()
2027 .top_0()
2028 .right_0()
2029 .opacity(0.5)
2030 .hover(|this| this.opacity(1.0))
2031 .child(
2032 IconButton::new("toggle-height", expand_icon)
2033 .icon_size(IconSize::XSmall)
2034 .icon_color(Color::Muted)
2035 .tooltip({
2036 let focus_handle = focus_handle.clone();
2037 move |window, cx| {
2038 Tooltip::for_action_in(
2039 expand_tooltip,
2040 &ExpandMessageEditor,
2041 &focus_handle,
2042 window,
2043 cx,
2044 )
2045 }
2046 })
2047 .on_click(cx.listener(|_, _, window, cx| {
2048 window.dispatch_action(Box::new(ExpandMessageEditor), cx);
2049 })),
2050 ),
2051 ),
2052 )
2053 .child(
2054 h_flex()
2055 .flex_none()
2056 .justify_between()
2057 .child(self.render_follow_toggle(cx))
2058 .child(self.render_send_button(cx)),
2059 )
2060 .into_any()
2061 }
2062
2063 fn render_send_button(&self, cx: &mut Context<Self>) -> AnyElement {
2064 if self.thread().map_or(true, |thread| {
2065 thread.read(cx).status() == ThreadStatus::Idle
2066 }) {
2067 let is_editor_empty = self.message_editor.read(cx).is_empty(cx);
2068 IconButton::new("send-message", IconName::Send)
2069 .icon_color(Color::Accent)
2070 .style(ButtonStyle::Filled)
2071 .disabled(self.thread().is_none() || is_editor_empty)
2072 .when(!is_editor_empty, |button| {
2073 button.tooltip(move |window, cx| Tooltip::for_action("Send", &Chat, window, cx))
2074 })
2075 .when(is_editor_empty, |button| {
2076 button.tooltip(Tooltip::text("Type a message to submit"))
2077 })
2078 .on_click(cx.listener(|this, _, window, cx| {
2079 this.chat(&Chat, window, cx);
2080 }))
2081 .into_any_element()
2082 } else {
2083 IconButton::new("stop-generation", IconName::StopFilled)
2084 .icon_color(Color::Error)
2085 .style(ButtonStyle::Tinted(ui::TintColor::Error))
2086 .tooltip(move |window, cx| {
2087 Tooltip::for_action("Stop Generation", &editor::actions::Cancel, window, cx)
2088 })
2089 .on_click(cx.listener(|this, _event, _, cx| this.cancel(cx)))
2090 .into_any_element()
2091 }
2092 }
2093
2094 fn render_follow_toggle(&self, cx: &mut Context<Self>) -> impl IntoElement {
2095 let following = self
2096 .workspace
2097 .read_with(cx, |workspace, _| {
2098 workspace.is_being_followed(CollaboratorId::Agent)
2099 })
2100 .unwrap_or(false);
2101
2102 IconButton::new("follow-agent", IconName::Crosshair)
2103 .icon_size(IconSize::Small)
2104 .icon_color(Color::Muted)
2105 .toggle_state(following)
2106 .selected_icon_color(Some(Color::Custom(cx.theme().players().agent().cursor)))
2107 .tooltip(move |window, cx| {
2108 if following {
2109 Tooltip::for_action("Stop Following Agent", &Follow, window, cx)
2110 } else {
2111 Tooltip::with_meta(
2112 "Follow Agent",
2113 Some(&Follow),
2114 "Track the agent's location as it reads and edits files.",
2115 window,
2116 cx,
2117 )
2118 }
2119 })
2120 .on_click(cx.listener(move |this, _, window, cx| {
2121 this.workspace
2122 .update(cx, |workspace, cx| {
2123 if following {
2124 workspace.unfollow(CollaboratorId::Agent, window, cx);
2125 } else {
2126 workspace.follow(CollaboratorId::Agent, window, cx);
2127 }
2128 })
2129 .ok();
2130 }))
2131 }
2132
2133 fn render_markdown(&self, markdown: Entity<Markdown>, style: MarkdownStyle) -> MarkdownElement {
2134 let workspace = self.workspace.clone();
2135 MarkdownElement::new(markdown, style).on_url_click(move |text, window, cx| {
2136 Self::open_link(text, &workspace, window, cx);
2137 })
2138 }
2139
2140 fn open_link(
2141 url: SharedString,
2142 workspace: &WeakEntity<Workspace>,
2143 window: &mut Window,
2144 cx: &mut App,
2145 ) {
2146 let Some(workspace) = workspace.upgrade() else {
2147 cx.open_url(&url);
2148 return;
2149 };
2150
2151 if let Some(mention_path) = MentionPath::try_parse(&url) {
2152 workspace.update(cx, |workspace, cx| {
2153 let project = workspace.project();
2154 let Some((path, entry)) = project.update(cx, |project, cx| {
2155 let path = project.find_project_path(mention_path.path(), cx)?;
2156 let entry = project.entry_for_path(&path, cx)?;
2157 Some((path, entry))
2158 }) else {
2159 return;
2160 };
2161
2162 if entry.is_dir() {
2163 project.update(cx, |_, cx| {
2164 cx.emit(project::Event::RevealInProjectPanel(entry.id));
2165 });
2166 } else {
2167 workspace
2168 .open_path(path, None, true, window, cx)
2169 .detach_and_log_err(cx);
2170 }
2171 })
2172 } else {
2173 cx.open_url(&url);
2174 }
2175 }
2176
2177 fn open_tool_call_location(
2178 &self,
2179 entry_ix: usize,
2180 location_ix: usize,
2181 window: &mut Window,
2182 cx: &mut Context<Self>,
2183 ) -> Option<()> {
2184 let location = self
2185 .thread()?
2186 .read(cx)
2187 .entries()
2188 .get(entry_ix)?
2189 .locations()?
2190 .get(location_ix)?;
2191
2192 let project_path = self
2193 .project
2194 .read(cx)
2195 .find_project_path(&location.path, cx)?;
2196
2197 let open_task = self
2198 .workspace
2199 .update(cx, |worskpace, cx| {
2200 worskpace.open_path(project_path, None, true, window, cx)
2201 })
2202 .log_err()?;
2203
2204 window
2205 .spawn(cx, async move |cx| {
2206 let item = open_task.await?;
2207
2208 let Some(active_editor) = item.downcast::<Editor>() else {
2209 return anyhow::Ok(());
2210 };
2211
2212 active_editor.update_in(cx, |editor, window, cx| {
2213 let snapshot = editor.buffer().read(cx).snapshot(cx);
2214 let first_hunk = editor
2215 .diff_hunks_in_ranges(
2216 &[editor::Anchor::min()..editor::Anchor::max()],
2217 &snapshot,
2218 )
2219 .next();
2220 if let Some(first_hunk) = first_hunk {
2221 let first_hunk_start = first_hunk.multi_buffer_range().start;
2222 editor.change_selections(Default::default(), window, cx, |selections| {
2223 selections.select_anchor_ranges([first_hunk_start..first_hunk_start]);
2224 })
2225 }
2226 })?;
2227
2228 anyhow::Ok(())
2229 })
2230 .detach_and_log_err(cx);
2231
2232 None
2233 }
2234
2235 pub fn open_thread_as_markdown(
2236 &self,
2237 workspace: Entity<Workspace>,
2238 window: &mut Window,
2239 cx: &mut App,
2240 ) -> Task<anyhow::Result<()>> {
2241 let markdown_language_task = workspace
2242 .read(cx)
2243 .app_state()
2244 .languages
2245 .language_for_name("Markdown");
2246
2247 let (thread_summary, markdown) = if let Some(thread) = self.thread() {
2248 let thread = thread.read(cx);
2249 (thread.title().to_string(), thread.to_markdown(cx))
2250 } else {
2251 return Task::ready(Ok(()));
2252 };
2253
2254 window.spawn(cx, async move |cx| {
2255 let markdown_language = markdown_language_task.await?;
2256
2257 workspace.update_in(cx, |workspace, window, cx| {
2258 let project = workspace.project().clone();
2259
2260 if !project.read(cx).is_local() {
2261 anyhow::bail!("failed to open active thread as markdown in remote project");
2262 }
2263
2264 let buffer = project.update(cx, |project, cx| {
2265 project.create_local_buffer(&markdown, Some(markdown_language), cx)
2266 });
2267 let buffer = cx.new(|cx| {
2268 MultiBuffer::singleton(buffer, cx).with_title(thread_summary.clone())
2269 });
2270
2271 workspace.add_item_to_active_pane(
2272 Box::new(cx.new(|cx| {
2273 let mut editor =
2274 Editor::for_multibuffer(buffer, Some(project.clone()), window, cx);
2275 editor.set_breadcrumb_header(thread_summary);
2276 editor
2277 })),
2278 None,
2279 true,
2280 window,
2281 cx,
2282 );
2283
2284 anyhow::Ok(())
2285 })??;
2286 anyhow::Ok(())
2287 })
2288 }
2289
2290 fn scroll_to_top(&mut self, cx: &mut Context<Self>) {
2291 self.list_state.scroll_to(ListOffset::default());
2292 cx.notify();
2293 }
2294
2295 pub fn scroll_to_bottom(&mut self, cx: &mut Context<Self>) {
2296 if let Some(thread) = self.thread() {
2297 let entry_count = thread.read(cx).entries().len();
2298 self.list_state.reset(entry_count);
2299 cx.notify();
2300 }
2301 }
2302
2303 fn notify_with_sound(
2304 &mut self,
2305 caption: impl Into<SharedString>,
2306 icon: IconName,
2307 window: &mut Window,
2308 cx: &mut Context<Self>,
2309 ) {
2310 self.play_notification_sound(window, cx);
2311 self.show_notification(caption, icon, window, cx);
2312 }
2313
2314 fn play_notification_sound(&self, window: &Window, cx: &mut App) {
2315 let settings = AgentSettings::get_global(cx);
2316 if settings.play_sound_when_agent_done && !window.is_window_active() {
2317 Audio::play_sound(Sound::AgentDone, cx);
2318 }
2319 }
2320
2321 fn show_notification(
2322 &mut self,
2323 caption: impl Into<SharedString>,
2324 icon: IconName,
2325 window: &mut Window,
2326 cx: &mut Context<Self>,
2327 ) {
2328 if window.is_window_active() || !self.notifications.is_empty() {
2329 return;
2330 }
2331
2332 let title = self.title(cx);
2333
2334 match AgentSettings::get_global(cx).notify_when_agent_waiting {
2335 NotifyWhenAgentWaiting::PrimaryScreen => {
2336 if let Some(primary) = cx.primary_display() {
2337 self.pop_up(icon, caption.into(), title, window, primary, cx);
2338 }
2339 }
2340 NotifyWhenAgentWaiting::AllScreens => {
2341 let caption = caption.into();
2342 for screen in cx.displays() {
2343 self.pop_up(icon, caption.clone(), title.clone(), window, screen, cx);
2344 }
2345 }
2346 NotifyWhenAgentWaiting::Never => {
2347 // Don't show anything
2348 }
2349 }
2350 }
2351
2352 fn pop_up(
2353 &mut self,
2354 icon: IconName,
2355 caption: SharedString,
2356 title: SharedString,
2357 window: &mut Window,
2358 screen: Rc<dyn PlatformDisplay>,
2359 cx: &mut Context<Self>,
2360 ) {
2361 let options = AgentNotification::window_options(screen, cx);
2362
2363 let project_name = self.workspace.upgrade().and_then(|workspace| {
2364 workspace
2365 .read(cx)
2366 .project()
2367 .read(cx)
2368 .visible_worktrees(cx)
2369 .next()
2370 .map(|worktree| worktree.read(cx).root_name().to_string())
2371 });
2372
2373 if let Some(screen_window) = cx
2374 .open_window(options, |_, cx| {
2375 cx.new(|_| {
2376 AgentNotification::new(title.clone(), caption.clone(), icon, project_name)
2377 })
2378 })
2379 .log_err()
2380 {
2381 if let Some(pop_up) = screen_window.entity(cx).log_err() {
2382 self.notification_subscriptions
2383 .entry(screen_window)
2384 .or_insert_with(Vec::new)
2385 .push(cx.subscribe_in(&pop_up, window, {
2386 |this, _, event, window, cx| match event {
2387 AgentNotificationEvent::Accepted => {
2388 let handle = window.window_handle();
2389 cx.activate(true);
2390
2391 let workspace_handle = this.workspace.clone();
2392
2393 // If there are multiple Zed windows, activate the correct one.
2394 cx.defer(move |cx| {
2395 handle
2396 .update(cx, |_view, window, _cx| {
2397 window.activate_window();
2398
2399 if let Some(workspace) = workspace_handle.upgrade() {
2400 workspace.update(_cx, |workspace, cx| {
2401 workspace.focus_panel::<AgentPanel>(window, cx);
2402 });
2403 }
2404 })
2405 .log_err();
2406 });
2407
2408 this.dismiss_notifications(cx);
2409 }
2410 AgentNotificationEvent::Dismissed => {
2411 this.dismiss_notifications(cx);
2412 }
2413 }
2414 }));
2415
2416 self.notifications.push(screen_window);
2417
2418 // If the user manually refocuses the original window, dismiss the popup.
2419 self.notification_subscriptions
2420 .entry(screen_window)
2421 .or_insert_with(Vec::new)
2422 .push({
2423 let pop_up_weak = pop_up.downgrade();
2424
2425 cx.observe_window_activation(window, move |_, window, cx| {
2426 if window.is_window_active() {
2427 if let Some(pop_up) = pop_up_weak.upgrade() {
2428 pop_up.update(cx, |_, cx| {
2429 cx.emit(AgentNotificationEvent::Dismissed);
2430 });
2431 }
2432 }
2433 })
2434 });
2435 }
2436 }
2437 }
2438
2439 fn dismiss_notifications(&mut self, cx: &mut Context<Self>) {
2440 for window in self.notifications.drain(..) {
2441 window
2442 .update(cx, |_, window, _| {
2443 window.remove_window();
2444 })
2445 .ok();
2446
2447 self.notification_subscriptions.remove(&window);
2448 }
2449 }
2450
2451 fn render_thread_controls(&self, cx: &Context<Self>) -> impl IntoElement {
2452 let open_as_markdown = IconButton::new("open-as-markdown", IconName::FileText)
2453 .icon_size(IconSize::XSmall)
2454 .icon_color(Color::Ignored)
2455 .tooltip(Tooltip::text("Open Thread as Markdown"))
2456 .on_click(cx.listener(move |this, _, window, cx| {
2457 if let Some(workspace) = this.workspace.upgrade() {
2458 this.open_thread_as_markdown(workspace, window, cx)
2459 .detach_and_log_err(cx);
2460 }
2461 }));
2462
2463 let scroll_to_top = IconButton::new("scroll_to_top", IconName::ArrowUpAlt)
2464 .icon_size(IconSize::XSmall)
2465 .icon_color(Color::Ignored)
2466 .tooltip(Tooltip::text("Scroll To Top"))
2467 .on_click(cx.listener(move |this, _, _, cx| {
2468 this.scroll_to_top(cx);
2469 }));
2470
2471 h_flex()
2472 .mr_1()
2473 .pb_2()
2474 .px(RESPONSE_PADDING_X)
2475 .opacity(0.4)
2476 .hover(|style| style.opacity(1.))
2477 .flex_wrap()
2478 .justify_end()
2479 .child(open_as_markdown)
2480 .child(scroll_to_top)
2481 }
2482}
2483
2484impl Focusable for AcpThreadView {
2485 fn focus_handle(&self, cx: &App) -> FocusHandle {
2486 self.message_editor.focus_handle(cx)
2487 }
2488}
2489
2490impl Render for AcpThreadView {
2491 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
2492 v_flex()
2493 .size_full()
2494 .key_context("AcpThread")
2495 .on_action(cx.listener(Self::chat))
2496 .on_action(cx.listener(Self::previous_history_message))
2497 .on_action(cx.listener(Self::next_history_message))
2498 .on_action(cx.listener(Self::open_agent_diff))
2499 .bg(cx.theme().colors().panel_background)
2500 .child(match &self.thread_state {
2501 ThreadState::Unauthenticated { connection } => v_flex()
2502 .p_2()
2503 .flex_1()
2504 .items_center()
2505 .justify_center()
2506 .child(self.render_pending_auth_state())
2507 .child(h_flex().mt_1p5().justify_center().children(
2508 connection.auth_methods().into_iter().map(|method| {
2509 Button::new(
2510 SharedString::from(method.id.0.clone()),
2511 method.name.clone(),
2512 )
2513 .on_click({
2514 let method_id = method.id.clone();
2515 cx.listener(move |this, _, window, cx| {
2516 this.authenticate(method_id.clone(), window, cx)
2517 })
2518 })
2519 }),
2520 )),
2521 ThreadState::Loading { .. } => v_flex().flex_1().child(self.render_empty_state(cx)),
2522 ThreadState::LoadError(e) => v_flex()
2523 .p_2()
2524 .flex_1()
2525 .items_center()
2526 .justify_center()
2527 .child(self.render_load_error(e, cx)),
2528 ThreadState::ServerExited { status } => v_flex()
2529 .p_2()
2530 .flex_1()
2531 .items_center()
2532 .justify_center()
2533 .child(self.render_server_exited(*status, cx)),
2534 ThreadState::Ready { thread, .. } => {
2535 let thread_clone = thread.clone();
2536
2537 v_flex().flex_1().map(|this| {
2538 if self.list_state.item_count() > 0 {
2539 this.child(
2540 list(
2541 self.list_state.clone(),
2542 cx.processor(|this, index: usize, window, cx| {
2543 let Some((entry, len)) = this.thread().and_then(|thread| {
2544 let entries = &thread.read(cx).entries();
2545 Some((entries.get(index)?, entries.len()))
2546 }) else {
2547 return Empty.into_any();
2548 };
2549 this.render_entry(index, len, entry, window, cx)
2550 }),
2551 )
2552 .with_sizing_behavior(gpui::ListSizingBehavior::Auto)
2553 .flex_grow()
2554 .into_any(),
2555 )
2556 .children(match thread_clone.read(cx).status() {
2557 ThreadStatus::Idle | ThreadStatus::WaitingForToolConfirmation => {
2558 None
2559 }
2560 ThreadStatus::Generating => div()
2561 .px_5()
2562 .py_2()
2563 .child(LoadingLabel::new("").size(LabelSize::Small))
2564 .into(),
2565 })
2566 .children(self.render_activity_bar(&thread_clone, window, cx))
2567 } else {
2568 this.child(self.render_empty_state(cx))
2569 }
2570 })
2571 }
2572 })
2573 .when_some(self.last_error.clone(), |el, error| {
2574 el.child(
2575 div()
2576 .p_2()
2577 .text_xs()
2578 .border_t_1()
2579 .border_color(cx.theme().colors().border)
2580 .bg(cx.theme().status().error_background)
2581 .child(
2582 self.render_markdown(error, default_markdown_style(false, window, cx)),
2583 ),
2584 )
2585 })
2586 .child(self.render_message_editor(window, cx))
2587 }
2588}
2589
2590fn user_message_markdown_style(window: &Window, cx: &App) -> MarkdownStyle {
2591 let mut style = default_markdown_style(false, window, cx);
2592 let mut text_style = window.text_style();
2593 let theme_settings = ThemeSettings::get_global(cx);
2594
2595 let buffer_font = theme_settings.buffer_font.family.clone();
2596 let buffer_font_size = TextSize::Small.rems(cx);
2597
2598 text_style.refine(&TextStyleRefinement {
2599 font_family: Some(buffer_font),
2600 font_size: Some(buffer_font_size.into()),
2601 ..Default::default()
2602 });
2603
2604 style.base_text_style = text_style;
2605 style.link_callback = Some(Rc::new(move |url, cx| {
2606 if MentionPath::try_parse(url).is_some() {
2607 let colors = cx.theme().colors();
2608 Some(TextStyleRefinement {
2609 background_color: Some(colors.element_background),
2610 ..Default::default()
2611 })
2612 } else {
2613 None
2614 }
2615 }));
2616 style
2617}
2618
2619fn default_markdown_style(buffer_font: bool, window: &Window, cx: &App) -> MarkdownStyle {
2620 let theme_settings = ThemeSettings::get_global(cx);
2621 let colors = cx.theme().colors();
2622
2623 let buffer_font_size = TextSize::Small.rems(cx);
2624
2625 let mut text_style = window.text_style();
2626 let line_height = buffer_font_size * 1.75;
2627
2628 let font_family = if buffer_font {
2629 theme_settings.buffer_font.family.clone()
2630 } else {
2631 theme_settings.ui_font.family.clone()
2632 };
2633
2634 let font_size = if buffer_font {
2635 TextSize::Small.rems(cx)
2636 } else {
2637 TextSize::Default.rems(cx)
2638 };
2639
2640 text_style.refine(&TextStyleRefinement {
2641 font_family: Some(font_family),
2642 font_fallbacks: theme_settings.ui_font.fallbacks.clone(),
2643 font_features: Some(theme_settings.ui_font.features.clone()),
2644 font_size: Some(font_size.into()),
2645 line_height: Some(line_height.into()),
2646 color: Some(cx.theme().colors().text),
2647 ..Default::default()
2648 });
2649
2650 MarkdownStyle {
2651 base_text_style: text_style.clone(),
2652 syntax: cx.theme().syntax().clone(),
2653 selection_background_color: cx.theme().colors().element_selection_background,
2654 code_block_overflow_x_scroll: true,
2655 table_overflow_x_scroll: true,
2656 heading_level_styles: Some(HeadingLevelStyles {
2657 h1: Some(TextStyleRefinement {
2658 font_size: Some(rems(1.15).into()),
2659 ..Default::default()
2660 }),
2661 h2: Some(TextStyleRefinement {
2662 font_size: Some(rems(1.1).into()),
2663 ..Default::default()
2664 }),
2665 h3: Some(TextStyleRefinement {
2666 font_size: Some(rems(1.05).into()),
2667 ..Default::default()
2668 }),
2669 h4: Some(TextStyleRefinement {
2670 font_size: Some(rems(1.).into()),
2671 ..Default::default()
2672 }),
2673 h5: Some(TextStyleRefinement {
2674 font_size: Some(rems(0.95).into()),
2675 ..Default::default()
2676 }),
2677 h6: Some(TextStyleRefinement {
2678 font_size: Some(rems(0.875).into()),
2679 ..Default::default()
2680 }),
2681 }),
2682 code_block: StyleRefinement {
2683 padding: EdgesRefinement {
2684 top: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
2685 left: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
2686 right: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
2687 bottom: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
2688 },
2689 margin: EdgesRefinement {
2690 top: Some(Length::Definite(Pixels(8.).into())),
2691 left: Some(Length::Definite(Pixels(0.).into())),
2692 right: Some(Length::Definite(Pixels(0.).into())),
2693 bottom: Some(Length::Definite(Pixels(12.).into())),
2694 },
2695 border_style: Some(BorderStyle::Solid),
2696 border_widths: EdgesRefinement {
2697 top: Some(AbsoluteLength::Pixels(Pixels(1.))),
2698 left: Some(AbsoluteLength::Pixels(Pixels(1.))),
2699 right: Some(AbsoluteLength::Pixels(Pixels(1.))),
2700 bottom: Some(AbsoluteLength::Pixels(Pixels(1.))),
2701 },
2702 border_color: Some(colors.border_variant),
2703 background: Some(colors.editor_background.into()),
2704 text: Some(TextStyleRefinement {
2705 font_family: Some(theme_settings.buffer_font.family.clone()),
2706 font_fallbacks: theme_settings.buffer_font.fallbacks.clone(),
2707 font_features: Some(theme_settings.buffer_font.features.clone()),
2708 font_size: Some(buffer_font_size.into()),
2709 ..Default::default()
2710 }),
2711 ..Default::default()
2712 },
2713 inline_code: TextStyleRefinement {
2714 font_family: Some(theme_settings.buffer_font.family.clone()),
2715 font_fallbacks: theme_settings.buffer_font.fallbacks.clone(),
2716 font_features: Some(theme_settings.buffer_font.features.clone()),
2717 font_size: Some(buffer_font_size.into()),
2718 background_color: Some(colors.editor_foreground.opacity(0.08)),
2719 ..Default::default()
2720 },
2721 link: TextStyleRefinement {
2722 background_color: Some(colors.editor_foreground.opacity(0.025)),
2723 underline: Some(UnderlineStyle {
2724 color: Some(colors.text_accent.opacity(0.5)),
2725 thickness: px(1.),
2726 ..Default::default()
2727 }),
2728 ..Default::default()
2729 },
2730 ..Default::default()
2731 }
2732}
2733
2734fn plan_label_markdown_style(
2735 status: &acp::PlanEntryStatus,
2736 window: &Window,
2737 cx: &App,
2738) -> MarkdownStyle {
2739 let default_md_style = default_markdown_style(false, window, cx);
2740
2741 MarkdownStyle {
2742 base_text_style: TextStyle {
2743 color: cx.theme().colors().text_muted,
2744 strikethrough: if matches!(status, acp::PlanEntryStatus::Completed) {
2745 Some(gpui::StrikethroughStyle {
2746 thickness: px(1.),
2747 color: Some(cx.theme().colors().text_muted.opacity(0.8)),
2748 })
2749 } else {
2750 None
2751 },
2752 ..default_md_style.base_text_style
2753 },
2754 ..default_md_style
2755 }
2756}
2757
2758#[cfg(test)]
2759mod tests {
2760 use agent_client_protocol::SessionId;
2761 use editor::EditorSettings;
2762 use fs::FakeFs;
2763 use futures::future::try_join_all;
2764 use gpui::{SemanticVersion, TestAppContext, VisualTestContext};
2765 use rand::Rng;
2766 use settings::SettingsStore;
2767
2768 use super::*;
2769
2770 #[gpui::test]
2771 async fn test_drop(cx: &mut TestAppContext) {
2772 init_test(cx);
2773
2774 let (thread_view, _cx) = setup_thread_view(StubAgentServer::default(), cx).await;
2775 let weak_view = thread_view.downgrade();
2776 drop(thread_view);
2777 assert!(!weak_view.is_upgradable());
2778 }
2779
2780 #[gpui::test]
2781 async fn test_notification_for_stop_event(cx: &mut TestAppContext) {
2782 init_test(cx);
2783
2784 let (thread_view, cx) = setup_thread_view(StubAgentServer::default(), cx).await;
2785
2786 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
2787 message_editor.update_in(cx, |editor, window, cx| {
2788 editor.set_text("Hello", window, cx);
2789 });
2790
2791 cx.deactivate_window();
2792
2793 thread_view.update_in(cx, |thread_view, window, cx| {
2794 thread_view.chat(&Chat, window, cx);
2795 });
2796
2797 cx.run_until_parked();
2798
2799 assert!(
2800 cx.windows()
2801 .iter()
2802 .any(|window| window.downcast::<AgentNotification>().is_some())
2803 );
2804 }
2805
2806 #[gpui::test]
2807 async fn test_notification_for_error(cx: &mut TestAppContext) {
2808 init_test(cx);
2809
2810 let (thread_view, cx) =
2811 setup_thread_view(StubAgentServer::new(SaboteurAgentConnection), cx).await;
2812
2813 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
2814 message_editor.update_in(cx, |editor, window, cx| {
2815 editor.set_text("Hello", window, cx);
2816 });
2817
2818 cx.deactivate_window();
2819
2820 thread_view.update_in(cx, |thread_view, window, cx| {
2821 thread_view.chat(&Chat, window, cx);
2822 });
2823
2824 cx.run_until_parked();
2825
2826 assert!(
2827 cx.windows()
2828 .iter()
2829 .any(|window| window.downcast::<AgentNotification>().is_some())
2830 );
2831 }
2832
2833 #[gpui::test]
2834 async fn test_notification_for_tool_authorization(cx: &mut TestAppContext) {
2835 init_test(cx);
2836
2837 let tool_call_id = acp::ToolCallId("1".into());
2838 let tool_call = acp::ToolCall {
2839 id: tool_call_id.clone(),
2840 title: "Label".into(),
2841 kind: acp::ToolKind::Edit,
2842 status: acp::ToolCallStatus::Pending,
2843 content: vec!["hi".into()],
2844 locations: vec![],
2845 raw_input: None,
2846 };
2847 let connection = StubAgentConnection::new(vec![acp::SessionUpdate::ToolCall(tool_call)])
2848 .with_permission_requests(HashMap::from_iter([(
2849 tool_call_id,
2850 vec![acp::PermissionOption {
2851 id: acp::PermissionOptionId("1".into()),
2852 name: "Allow".into(),
2853 kind: acp::PermissionOptionKind::AllowOnce,
2854 }],
2855 )]));
2856 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
2857
2858 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
2859 message_editor.update_in(cx, |editor, window, cx| {
2860 editor.set_text("Hello", window, cx);
2861 });
2862
2863 cx.deactivate_window();
2864
2865 thread_view.update_in(cx, |thread_view, window, cx| {
2866 thread_view.chat(&Chat, window, cx);
2867 });
2868
2869 cx.run_until_parked();
2870
2871 assert!(
2872 cx.windows()
2873 .iter()
2874 .any(|window| window.downcast::<AgentNotification>().is_some())
2875 );
2876 }
2877
2878 async fn setup_thread_view(
2879 agent: impl AgentServer + 'static,
2880 cx: &mut TestAppContext,
2881 ) -> (Entity<AcpThreadView>, &mut VisualTestContext) {
2882 let fs = FakeFs::new(cx.executor());
2883 let project = Project::test(fs, [], cx).await;
2884 let (workspace, cx) =
2885 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
2886
2887 let thread_view = cx.update(|window, cx| {
2888 cx.new(|cx| {
2889 AcpThreadView::new(
2890 Rc::new(agent),
2891 workspace.downgrade(),
2892 project,
2893 Rc::new(RefCell::new(MessageHistory::default())),
2894 1,
2895 None,
2896 window,
2897 cx,
2898 )
2899 })
2900 });
2901 cx.run_until_parked();
2902 (thread_view, cx)
2903 }
2904
2905 struct StubAgentServer<C> {
2906 connection: C,
2907 }
2908
2909 impl<C> StubAgentServer<C> {
2910 fn new(connection: C) -> Self {
2911 Self { connection }
2912 }
2913 }
2914
2915 impl StubAgentServer<StubAgentConnection> {
2916 fn default() -> Self {
2917 Self::new(StubAgentConnection::default())
2918 }
2919 }
2920
2921 impl<C> AgentServer for StubAgentServer<C>
2922 where
2923 C: 'static + AgentConnection + Send + Clone,
2924 {
2925 fn logo(&self) -> ui::IconName {
2926 unimplemented!()
2927 }
2928
2929 fn name(&self) -> &'static str {
2930 unimplemented!()
2931 }
2932
2933 fn empty_state_headline(&self) -> &'static str {
2934 unimplemented!()
2935 }
2936
2937 fn empty_state_message(&self) -> &'static str {
2938 unimplemented!()
2939 }
2940
2941 fn connect(
2942 &self,
2943 _root_dir: &Path,
2944 _project: &Entity<Project>,
2945 _cx: &mut App,
2946 ) -> Task<gpui::Result<Rc<dyn AgentConnection>>> {
2947 Task::ready(Ok(Rc::new(self.connection.clone())))
2948 }
2949 }
2950
2951 #[derive(Clone, Default)]
2952 struct StubAgentConnection {
2953 sessions: Arc<Mutex<HashMap<acp::SessionId, WeakEntity<AcpThread>>>>,
2954 permission_requests: HashMap<acp::ToolCallId, Vec<acp::PermissionOption>>,
2955 updates: Vec<acp::SessionUpdate>,
2956 }
2957
2958 impl StubAgentConnection {
2959 fn new(updates: Vec<acp::SessionUpdate>) -> Self {
2960 Self {
2961 updates,
2962 permission_requests: HashMap::default(),
2963 sessions: Arc::default(),
2964 }
2965 }
2966
2967 fn with_permission_requests(
2968 mut self,
2969 permission_requests: HashMap<acp::ToolCallId, Vec<acp::PermissionOption>>,
2970 ) -> Self {
2971 self.permission_requests = permission_requests;
2972 self
2973 }
2974 }
2975
2976 impl AgentConnection for StubAgentConnection {
2977 fn auth_methods(&self) -> &[acp::AuthMethod] {
2978 &[]
2979 }
2980
2981 fn new_thread(
2982 self: Rc<Self>,
2983 project: Entity<Project>,
2984 _cwd: &Path,
2985 cx: &mut gpui::AsyncApp,
2986 ) -> Task<gpui::Result<Entity<AcpThread>>> {
2987 let session_id = SessionId(
2988 rand::thread_rng()
2989 .sample_iter(&rand::distributions::Alphanumeric)
2990 .take(7)
2991 .map(char::from)
2992 .collect::<String>()
2993 .into(),
2994 );
2995 let thread = cx
2996 .new(|cx| AcpThread::new("Test", self.clone(), project, session_id.clone(), cx))
2997 .unwrap();
2998 self.sessions.lock().insert(session_id, thread.downgrade());
2999 Task::ready(Ok(thread))
3000 }
3001
3002 fn authenticate(
3003 &self,
3004 _method_id: acp::AuthMethodId,
3005 _cx: &mut App,
3006 ) -> Task<gpui::Result<()>> {
3007 unimplemented!()
3008 }
3009
3010 fn prompt(
3011 &self,
3012 params: acp::PromptRequest,
3013 cx: &mut App,
3014 ) -> Task<gpui::Result<acp::PromptResponse>> {
3015 let sessions = self.sessions.lock();
3016 let thread = sessions.get(¶ms.session_id).unwrap();
3017 let mut tasks = vec![];
3018 for update in &self.updates {
3019 let thread = thread.clone();
3020 let update = update.clone();
3021 let permission_request = if let acp::SessionUpdate::ToolCall(tool_call) = &update
3022 && let Some(options) = self.permission_requests.get(&tool_call.id)
3023 {
3024 Some((tool_call.clone(), options.clone()))
3025 } else {
3026 None
3027 };
3028 let task = cx.spawn(async move |cx| {
3029 if let Some((tool_call, options)) = permission_request {
3030 let permission = thread.update(cx, |thread, cx| {
3031 thread.request_tool_call_permission(
3032 tool_call.clone(),
3033 options.clone(),
3034 cx,
3035 )
3036 })?;
3037 permission.await?;
3038 }
3039 thread.update(cx, |thread, cx| {
3040 thread.handle_session_update(update.clone(), cx).unwrap();
3041 })?;
3042 anyhow::Ok(())
3043 });
3044 tasks.push(task);
3045 }
3046 cx.spawn(async move |_| {
3047 try_join_all(tasks).await?;
3048 Ok(acp::PromptResponse {
3049 stop_reason: acp::StopReason::EndTurn,
3050 })
3051 })
3052 }
3053
3054 fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {
3055 unimplemented!()
3056 }
3057 }
3058
3059 #[derive(Clone)]
3060 struct SaboteurAgentConnection;
3061
3062 impl AgentConnection for SaboteurAgentConnection {
3063 fn new_thread(
3064 self: Rc<Self>,
3065 project: Entity<Project>,
3066 _cwd: &Path,
3067 cx: &mut gpui::AsyncApp,
3068 ) -> Task<gpui::Result<Entity<AcpThread>>> {
3069 Task::ready(Ok(cx
3070 .new(|cx| {
3071 AcpThread::new(
3072 "SaboteurAgentConnection",
3073 self,
3074 project,
3075 SessionId("test".into()),
3076 cx,
3077 )
3078 })
3079 .unwrap()))
3080 }
3081
3082 fn auth_methods(&self) -> &[acp::AuthMethod] {
3083 &[]
3084 }
3085
3086 fn authenticate(
3087 &self,
3088 _method_id: acp::AuthMethodId,
3089 _cx: &mut App,
3090 ) -> Task<gpui::Result<()>> {
3091 unimplemented!()
3092 }
3093
3094 fn prompt(
3095 &self,
3096 _params: acp::PromptRequest,
3097 _cx: &mut App,
3098 ) -> Task<gpui::Result<acp::PromptResponse>> {
3099 Task::ready(Err(anyhow::anyhow!("Error prompting")))
3100 }
3101
3102 fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {
3103 unimplemented!()
3104 }
3105 }
3106
3107 fn init_test(cx: &mut TestAppContext) {
3108 cx.update(|cx| {
3109 let settings_store = SettingsStore::test(cx);
3110 cx.set_global(settings_store);
3111 language::init(cx);
3112 Project::init_settings(cx);
3113 AgentSettings::register(cx);
3114 workspace::init_settings(cx);
3115 ThemeSettings::register(cx);
3116 release_channel::init(SemanticVersion::default(), cx);
3117 EditorSettings::register(cx);
3118 });
3119 }
3120}