1use acp_thread::{
2 AcpThread, AcpThreadEvent, AgentThreadEntry, AssistantMessage, AssistantMessageChunk,
3 AuthRequired, LoadError, MentionUri, RetryStatus, ThreadStatus, ToolCall, ToolCallContent,
4 ToolCallStatus, UserMessageId,
5};
6use acp_thread::{AgentConnection, Plan};
7use action_log::ActionLog;
8use agent::{DbThreadMetadata, HistoryEntry, HistoryEntryId, HistoryStore, NativeAgentServer};
9use agent_client_protocol::{self as acp, PromptCapabilities};
10use agent_servers::{AgentServer, AgentServerDelegate};
11use agent_settings::{AgentProfileId, AgentSettings, CompletionMode};
12use anyhow::{Result, anyhow, bail};
13use arrayvec::ArrayVec;
14use audio::{Audio, Sound};
15use buffer_diff::BufferDiff;
16use client::zed_urls;
17use cloud_llm_client::PlanV1;
18use collections::{HashMap, HashSet};
19use editor::scroll::Autoscroll;
20use editor::{Editor, EditorEvent, EditorMode, MultiBuffer, PathKey, SelectionEffects};
21use file_icons::FileIcons;
22use fs::Fs;
23use futures::FutureExt as _;
24use gpui::{
25 Action, Animation, AnimationExt, AnyView, App, BorderStyle, ClickEvent, ClipboardItem,
26 CursorStyle, EdgesRefinement, ElementId, Empty, Entity, FocusHandle, Focusable, Hsla, Length,
27 ListOffset, ListState, PlatformDisplay, SharedString, StyleRefinement, Subscription, Task,
28 TextStyle, TextStyleRefinement, UnderlineStyle, WeakEntity, Window, WindowHandle, div,
29 ease_in_out, linear_color_stop, linear_gradient, list, point, pulsating_between,
30};
31use language::Buffer;
32
33use language_model::LanguageModelRegistry;
34use markdown::{HeadingLevelStyles, Markdown, MarkdownElement, MarkdownStyle};
35use project::{Project, ProjectEntryId};
36use prompt_store::{PromptId, PromptStore};
37use rope::Point;
38use settings::{NotifyWhenAgentWaiting, Settings as _, SettingsStore};
39use std::cell::RefCell;
40use std::path::Path;
41use std::sync::Arc;
42use std::time::Instant;
43use std::{collections::BTreeMap, rc::Rc, time::Duration};
44use terminal_view::terminal_panel::TerminalPanel;
45use text::Anchor;
46use theme::{AgentFontSize, ThemeSettings};
47use ui::{
48 Callout, CommonAnimationExt, Disclosure, Divider, DividerColor, ElevationIndex, KeyBinding,
49 PopoverMenuHandle, SpinnerLabel, TintColor, Tooltip, WithScrollbar, prelude::*,
50};
51use util::{ResultExt, size::format_file_size, time::duration_alt_display};
52use workspace::{CollaboratorId, Workspace};
53use zed_actions::agent::{Chat, ToggleModelSelector};
54use zed_actions::assistant::OpenRulesLibrary;
55
56use super::entry_view_state::EntryViewState;
57use crate::acp::AcpModelSelectorPopover;
58use crate::acp::ModeSelector;
59use crate::acp::entry_view_state::{EntryViewEvent, ViewEvent};
60use crate::acp::message_editor::{MessageEditor, MessageEditorEvent};
61use crate::agent_diff::AgentDiff;
62use crate::profile_selector::{ProfileProvider, ProfileSelector};
63
64use crate::ui::{
65 AgentNotification, AgentNotificationEvent, BurnModeTooltip, UnavailableEditingTooltip,
66 UsageCallout,
67};
68use crate::{
69 AgentDiffPane, AgentPanel, AllowAlways, AllowOnce, ContinueThread, ContinueWithBurnMode,
70 CycleModeSelector, ExpandMessageEditor, Follow, KeepAll, OpenAgentDiff, OpenHistory, RejectAll,
71 RejectOnce, ToggleBurnMode, ToggleProfileSelector,
72};
73
74#[derive(Copy, Clone, Debug, PartialEq, Eq)]
75enum ThreadFeedback {
76 Positive,
77 Negative,
78}
79
80#[derive(Debug)]
81enum ThreadError {
82 PaymentRequired,
83 ModelRequestLimitReached(cloud_llm_client::Plan),
84 ToolUseLimitReached,
85 Refusal,
86 AuthenticationRequired(SharedString),
87 Other(SharedString),
88}
89
90impl ThreadError {
91 fn from_err(error: anyhow::Error, agent: &Rc<dyn AgentServer>) -> Self {
92 if error.is::<language_model::PaymentRequiredError>() {
93 Self::PaymentRequired
94 } else if error.is::<language_model::ToolUseLimitReachedError>() {
95 Self::ToolUseLimitReached
96 } else if let Some(error) =
97 error.downcast_ref::<language_model::ModelRequestLimitReachedError>()
98 {
99 Self::ModelRequestLimitReached(error.plan)
100 } else if let Some(acp_error) = error.downcast_ref::<acp::Error>()
101 && acp_error.code == acp::ErrorCode::AUTH_REQUIRED.code
102 {
103 Self::AuthenticationRequired(acp_error.message.clone().into())
104 } else {
105 let string = error.to_string();
106 // TODO: we should have Gemini return better errors here.
107 if agent.clone().downcast::<agent_servers::Gemini>().is_some()
108 && string.contains("Could not load the default credentials")
109 || string.contains("API key not valid")
110 || string.contains("Request had invalid authentication credentials")
111 {
112 Self::AuthenticationRequired(string.into())
113 } else {
114 Self::Other(error.to_string().into())
115 }
116 }
117 }
118}
119
120impl ProfileProvider for Entity<agent::Thread> {
121 fn profile_id(&self, cx: &App) -> AgentProfileId {
122 self.read(cx).profile().clone()
123 }
124
125 fn set_profile(&self, profile_id: AgentProfileId, cx: &mut App) {
126 self.update(cx, |thread, _cx| {
127 thread.set_profile(profile_id);
128 });
129 }
130
131 fn profiles_supported(&self, cx: &App) -> bool {
132 self.read(cx)
133 .model()
134 .is_some_and(|model| model.supports_tools())
135 }
136}
137
138#[derive(Default)]
139struct ThreadFeedbackState {
140 feedback: Option<ThreadFeedback>,
141 comments_editor: Option<Entity<Editor>>,
142}
143
144impl ThreadFeedbackState {
145 pub fn submit(
146 &mut self,
147 thread: Entity<AcpThread>,
148 feedback: ThreadFeedback,
149 window: &mut Window,
150 cx: &mut App,
151 ) {
152 let Some(telemetry) = thread.read(cx).connection().telemetry() else {
153 return;
154 };
155
156 if self.feedback == Some(feedback) {
157 return;
158 }
159
160 self.feedback = Some(feedback);
161 match feedback {
162 ThreadFeedback::Positive => {
163 self.comments_editor = None;
164 }
165 ThreadFeedback::Negative => {
166 self.comments_editor = Some(Self::build_feedback_comments_editor(window, cx));
167 }
168 }
169 let session_id = thread.read(cx).session_id().clone();
170 let agent_name = telemetry.agent_name();
171 let task = telemetry.thread_data(&session_id, cx);
172 let rating = match feedback {
173 ThreadFeedback::Positive => "positive",
174 ThreadFeedback::Negative => "negative",
175 };
176 cx.background_spawn(async move {
177 let thread = task.await?;
178 telemetry::event!(
179 "Agent Thread Rated",
180 session_id = session_id,
181 rating = rating,
182 agent = agent_name,
183 thread = thread
184 );
185 anyhow::Ok(())
186 })
187 .detach_and_log_err(cx);
188 }
189
190 pub fn submit_comments(&mut self, thread: Entity<AcpThread>, cx: &mut App) {
191 let Some(telemetry) = thread.read(cx).connection().telemetry() else {
192 return;
193 };
194
195 let Some(comments) = self
196 .comments_editor
197 .as_ref()
198 .map(|editor| editor.read(cx).text(cx))
199 .filter(|text| !text.trim().is_empty())
200 else {
201 return;
202 };
203
204 self.comments_editor.take();
205
206 let session_id = thread.read(cx).session_id().clone();
207 let agent_name = telemetry.agent_name();
208 let task = telemetry.thread_data(&session_id, cx);
209 cx.background_spawn(async move {
210 let thread = task.await?;
211 telemetry::event!(
212 "Agent Thread Feedback Comments",
213 session_id = session_id,
214 comments = comments,
215 agent = agent_name,
216 thread = thread
217 );
218 anyhow::Ok(())
219 })
220 .detach_and_log_err(cx);
221 }
222
223 pub fn clear(&mut self) {
224 *self = Self::default()
225 }
226
227 pub fn dismiss_comments(&mut self) {
228 self.comments_editor.take();
229 }
230
231 fn build_feedback_comments_editor(window: &mut Window, cx: &mut App) -> Entity<Editor> {
232 let buffer = cx.new(|cx| {
233 let empty_string = String::new();
234 MultiBuffer::singleton(cx.new(|cx| Buffer::local(empty_string, cx)), cx)
235 });
236
237 let editor = cx.new(|cx| {
238 let mut editor = Editor::new(
239 editor::EditorMode::AutoHeight {
240 min_lines: 1,
241 max_lines: Some(4),
242 },
243 buffer,
244 None,
245 window,
246 cx,
247 );
248 editor.set_placeholder_text(
249 "What went wrong? Share your feedback so we can improve.",
250 window,
251 cx,
252 );
253 editor
254 });
255
256 editor.read(cx).focus_handle(cx).focus(window);
257 editor
258 }
259}
260
261pub struct AcpThreadView {
262 agent: Rc<dyn AgentServer>,
263 acp_agent: Option<Rc<dyn agent_servers::AcpAgentServer>>,
264 workspace: WeakEntity<Workspace>,
265 project: Entity<Project>,
266 thread_state: ThreadState,
267 auth_commands: HashMap<String, task::SpawnInTerminal>,
268 history_store: Entity<HistoryStore>,
269 hovered_recent_history_item: Option<usize>,
270 entry_view_state: Entity<EntryViewState>,
271 message_editor: Entity<MessageEditor>,
272 focus_handle: FocusHandle,
273 model_selector: Option<Entity<AcpModelSelectorPopover>>,
274 profile_selector: Option<Entity<ProfileSelector>>,
275 notifications: Vec<WindowHandle<AgentNotification>>,
276 notification_subscriptions: HashMap<WindowHandle<AgentNotification>, Vec<Subscription>>,
277 thread_retry_status: Option<RetryStatus>,
278 thread_error: Option<ThreadError>,
279 thread_feedback: ThreadFeedbackState,
280 list_state: ListState,
281 auth_task: Option<Task<()>>,
282 expanded_tool_calls: HashSet<acp::ToolCallId>,
283 expanded_thinking_blocks: HashSet<(usize, usize)>,
284 edits_expanded: bool,
285 plan_expanded: bool,
286 editor_expanded: bool,
287 should_be_following: bool,
288 editing_message: Option<usize>,
289 prompt_capabilities: Rc<RefCell<PromptCapabilities>>,
290 available_commands: Rc<RefCell<Vec<acp::AvailableCommand>>>,
291 is_loading_contents: bool,
292 new_server_version_available: Option<SharedString>,
293 resume_thread_metadata: Option<DbThreadMetadata>,
294 _cancel_task: Option<Task<()>>,
295 _subscriptions: [Subscription; 5],
296 #[cfg(target_os = "windows")]
297 show_codex_windows_warning: bool,
298}
299
300enum ThreadState {
301 Loading(Entity<LoadingView>),
302 Ready {
303 thread: Entity<AcpThread>,
304 title_editor: Option<Entity<Editor>>,
305 mode_selector: Option<Entity<ModeSelector>>,
306 _subscriptions: Vec<Subscription>,
307 },
308 LoadError(LoadError),
309 Unauthenticated {
310 connection: Rc<dyn AgentConnection>,
311 description: Option<Entity<Markdown>>,
312 configuration_view: Option<AnyView>,
313 pending_auth_method: Option<acp::AuthMethodId>,
314 _subscription: Option<Subscription>,
315 },
316}
317
318struct LoadingView {
319 title: SharedString,
320 _load_task: Task<()>,
321 _update_title_task: Task<anyhow::Result<()>>,
322}
323
324impl AcpThreadView {
325 pub fn new(
326 agent: Rc<dyn AgentServer>,
327 resume_thread: Option<DbThreadMetadata>,
328 summarize_thread: Option<DbThreadMetadata>,
329 workspace: WeakEntity<Workspace>,
330 project: Entity<Project>,
331 history_store: Entity<HistoryStore>,
332 prompt_store: Option<Entity<PromptStore>>,
333 window: &mut Window,
334 cx: &mut Context<Self>,
335 ) -> Self {
336 let prompt_capabilities = Rc::new(RefCell::new(acp::PromptCapabilities::default()));
337 let available_commands = Rc::new(RefCell::new(vec![]));
338
339 let placeholder = if agent.name() == "Zed Agent" {
340 format!("Message the {} — @ to include context", agent.name())
341 } else if agent.name() == "Claude Code"
342 || agent.name() == "Codex"
343 || !available_commands.borrow().is_empty()
344 {
345 format!(
346 "Message {} — @ to include context, / for commands",
347 agent.name()
348 )
349 } else {
350 format!("Message {} — @ to include context", agent.name())
351 };
352
353 let message_editor = cx.new(|cx| {
354 let mut editor = MessageEditor::new(
355 workspace.clone(),
356 project.clone(),
357 history_store.clone(),
358 prompt_store.clone(),
359 prompt_capabilities.clone(),
360 available_commands.clone(),
361 agent.name(),
362 &placeholder,
363 editor::EditorMode::AutoHeight {
364 min_lines: AgentSettings::get_global(cx).message_editor_min_lines,
365 max_lines: Some(AgentSettings::get_global(cx).set_message_editor_max_lines()),
366 },
367 window,
368 cx,
369 );
370 if let Some(entry) = summarize_thread {
371 editor.insert_thread_summary(entry, window, cx);
372 }
373 editor
374 });
375
376 let list_state = ListState::new(0, gpui::ListAlignment::Bottom, px(2048.0));
377
378 let entry_view_state = cx.new(|_| {
379 EntryViewState::new(
380 workspace.clone(),
381 project.clone(),
382 history_store.clone(),
383 prompt_store.clone(),
384 prompt_capabilities.clone(),
385 available_commands.clone(),
386 agent.name(),
387 )
388 });
389
390 let agent_server_store = project.read(cx).agent_server_store().clone();
391 let subscriptions = [
392 cx.observe_global_in::<SettingsStore>(window, Self::agent_ui_font_size_changed),
393 cx.observe_global_in::<AgentFontSize>(window, Self::agent_ui_font_size_changed),
394 cx.subscribe_in(&message_editor, window, Self::handle_message_editor_event),
395 cx.subscribe_in(&entry_view_state, window, Self::handle_entry_view_event),
396 cx.subscribe_in(
397 &agent_server_store,
398 window,
399 Self::handle_agent_servers_updated,
400 ),
401 ];
402
403 #[cfg(target_os = "windows")]
404 let show_codex_windows_warning = crate::ExternalAgent::parse_built_in(agent.as_ref())
405 == Some(crate::ExternalAgent::Codex);
406
407 // Try to downcast to AcpAgentServer for ACP-specific functionality
408 let acp_agent = agent
409 .clone()
410 .into_any()
411 .downcast::<agent_servers::Gemini>()
412 .map(|a| a as Rc<dyn agent_servers::AcpAgentServer>)
413 .or_else(|_| {
414 agent
415 .clone()
416 .into_any()
417 .downcast::<agent_servers::ClaudeCode>()
418 .map(|a| a as Rc<dyn agent_servers::AcpAgentServer>)
419 })
420 .or_else(|_| {
421 agent
422 .clone()
423 .into_any()
424 .downcast::<agent_servers::Codex>()
425 .map(|a| a as Rc<dyn agent_servers::AcpAgentServer>)
426 })
427 .or_else(|_| {
428 agent
429 .clone()
430 .into_any()
431 .downcast::<agent_servers::CustomAgentServer>()
432 .map(|a| a as Rc<dyn agent_servers::AcpAgentServer>)
433 })
434 .ok();
435
436 Self {
437 agent: agent.clone(),
438 acp_agent,
439 workspace: workspace.clone(),
440 project: project.clone(),
441 entry_view_state,
442 thread_state: Self::initial_state(
443 agent.clone(),
444 resume_thread.clone(),
445 workspace.clone(),
446 project.clone(),
447 window,
448 cx,
449 ),
450 auth_commands: HashMap::default(),
451 message_editor,
452 model_selector: None,
453 profile_selector: None,
454
455 notifications: Vec::new(),
456 notification_subscriptions: HashMap::default(),
457 list_state: list_state,
458 thread_retry_status: None,
459 thread_error: None,
460 thread_feedback: Default::default(),
461 auth_task: None,
462 expanded_tool_calls: HashSet::default(),
463 expanded_thinking_blocks: HashSet::default(),
464 editing_message: None,
465 edits_expanded: false,
466 plan_expanded: false,
467 prompt_capabilities,
468 available_commands,
469 editor_expanded: false,
470 should_be_following: false,
471 history_store,
472 hovered_recent_history_item: None,
473 is_loading_contents: false,
474 _subscriptions: subscriptions,
475 _cancel_task: None,
476 focus_handle: cx.focus_handle(),
477 new_server_version_available: None,
478 resume_thread_metadata: resume_thread,
479 #[cfg(target_os = "windows")]
480 show_codex_windows_warning,
481 }
482 }
483
484 fn reset(&mut self, window: &mut Window, cx: &mut Context<Self>) {
485 self.thread_state = Self::initial_state(
486 self.agent.clone(),
487 self.resume_thread_metadata.clone(),
488 self.workspace.clone(),
489 self.project.clone(),
490 window,
491 cx,
492 );
493 self.available_commands.replace(vec![]);
494 self.new_server_version_available.take();
495 cx.notify();
496 }
497
498 fn initial_state(
499 agent: Rc<dyn AgentServer>,
500 resume_thread: Option<DbThreadMetadata>,
501 workspace: WeakEntity<Workspace>,
502 project: Entity<Project>,
503 window: &mut Window,
504 cx: &mut Context<Self>,
505 ) -> ThreadState {
506 if project.read(cx).is_via_collab()
507 && agent.clone().downcast::<NativeAgentServer>().is_none()
508 {
509 return ThreadState::LoadError(LoadError::Other(
510 "External agents are not yet supported in shared projects.".into(),
511 ));
512 }
513 let mut worktrees = project.read(cx).visible_worktrees(cx).collect::<Vec<_>>();
514 // Pick the first non-single-file worktree for the root directory if there are any,
515 // and otherwise the parent of a single-file worktree, falling back to $HOME if there are no visible worktrees.
516 worktrees.sort_by(|l, r| {
517 l.read(cx)
518 .is_single_file()
519 .cmp(&r.read(cx).is_single_file())
520 });
521 let root_dir = worktrees
522 .into_iter()
523 .filter_map(|worktree| {
524 if worktree.read(cx).is_single_file() {
525 Some(worktree.read(cx).abs_path().parent()?.into())
526 } else {
527 Some(worktree.read(cx).abs_path())
528 }
529 })
530 .next();
531 let (status_tx, mut status_rx) = watch::channel("Loading…".into());
532 let (new_version_available_tx, mut new_version_available_rx) = watch::channel(None);
533 let delegate = AgentServerDelegate::new(
534 project.read(cx).agent_server_store().clone(),
535 project.clone(),
536 Some(status_tx),
537 Some(new_version_available_tx),
538 );
539
540 let connect_task = agent.connect(root_dir.as_deref(), delegate, cx);
541 let load_task = cx.spawn_in(window, async move |this, cx| {
542 let connection = match connect_task.await {
543 Ok((connection, auth_commands)) => {
544 this.update(cx, |this, _| this.auth_commands = auth_commands)
545 .ok();
546 connection
547 }
548 Err(err) => {
549 this.update_in(cx, |this, window, cx| {
550 if err.downcast_ref::<LoadError>().is_some() {
551 this.handle_load_error(err, window, cx);
552 } else {
553 this.handle_thread_error(err, cx);
554 }
555 cx.notify();
556 })
557 .log_err();
558 return;
559 }
560 };
561
562 let result = if let Some(native_agent) = connection
563 .clone()
564 .downcast::<agent::NativeAgentConnection>()
565 && let Some(resume) = resume_thread.clone()
566 {
567 cx.update(|_, cx| {
568 native_agent
569 .0
570 .update(cx, |agent, cx| agent.open_thread(resume.id, cx))
571 })
572 .log_err()
573 } else {
574 let root_dir = if let Some(acp_agent) = connection
575 .clone()
576 .downcast::<agent_servers::AcpConnection>()
577 {
578 acp_agent.root_dir().into()
579 } else {
580 root_dir.unwrap_or(paths::home_dir().as_path().into())
581 };
582 cx.update(|_, cx| {
583 connection
584 .clone()
585 .new_thread(project.clone(), &root_dir, cx)
586 })
587 .log_err()
588 };
589
590 let Some(result) = result else {
591 return;
592 };
593
594 let result = match result.await {
595 Err(e) => match e.downcast::<acp_thread::AuthRequired>() {
596 Ok(err) => {
597 cx.update(|window, cx| {
598 Self::handle_auth_required(this, err, agent, connection, window, cx)
599 })
600 .log_err();
601 return;
602 }
603 Err(err) => Err(err),
604 },
605 Ok(thread) => Ok(thread),
606 };
607
608 this.update_in(cx, |this, window, cx| {
609 match result {
610 Ok(thread) => {
611 let action_log = thread.read(cx).action_log().clone();
612
613 this.prompt_capabilities
614 .replace(thread.read(cx).prompt_capabilities());
615
616 let count = thread.read(cx).entries().len();
617 this.entry_view_state.update(cx, |view_state, cx| {
618 for ix in 0..count {
619 view_state.sync_entry(ix, &thread, window, cx);
620 }
621 this.list_state.splice_focusable(
622 0..0,
623 (0..count).map(|ix| view_state.entry(ix)?.focus_handle(cx)),
624 );
625 });
626
627 if let Some(resume) = resume_thread {
628 this.history_store.update(cx, |history, cx| {
629 history.push_recently_opened_entry(
630 HistoryEntryId::AcpThread(resume.id),
631 cx,
632 );
633 });
634 }
635
636 AgentDiff::set_active_thread(&workspace, thread.clone(), window, cx);
637
638 this.model_selector = thread
639 .read(cx)
640 .connection()
641 .model_selector(thread.read(cx).session_id())
642 .map(|selector| {
643 cx.new(|cx| {
644 AcpModelSelectorPopover::new(
645 selector,
646 PopoverMenuHandle::default(),
647 this.focus_handle(cx),
648 window,
649 cx,
650 )
651 })
652 });
653
654 let mode_selector = thread
655 .read(cx)
656 .connection()
657 .session_modes(thread.read(cx).session_id(), cx)
658 .map(|session_modes| {
659 let fs = this.project.read(cx).fs().clone();
660 let focus_handle = this.focus_handle(cx);
661 cx.new(|_cx| {
662 ModeSelector::new(
663 session_modes,
664 this.agent.clone(),
665 fs,
666 focus_handle,
667 )
668 })
669 });
670
671 let mut subscriptions = vec![
672 cx.subscribe_in(&thread, window, Self::handle_thread_event),
673 cx.observe(&action_log, |_, _, cx| cx.notify()),
674 ];
675
676 let title_editor =
677 if thread.update(cx, |thread, cx| thread.can_set_title(cx)) {
678 let editor = cx.new(|cx| {
679 let mut editor = Editor::single_line(window, cx);
680 editor.set_text(thread.read(cx).title(), window, cx);
681 editor
682 });
683 subscriptions.push(cx.subscribe_in(
684 &editor,
685 window,
686 Self::handle_title_editor_event,
687 ));
688 Some(editor)
689 } else {
690 None
691 };
692
693 this.thread_state = ThreadState::Ready {
694 thread,
695 title_editor,
696 mode_selector,
697 _subscriptions: subscriptions,
698 };
699 this.message_editor.focus_handle(cx).focus(window);
700
701 this.profile_selector = this.as_native_thread(cx).map(|thread| {
702 cx.new(|cx| {
703 ProfileSelector::new(
704 <dyn Fs>::global(cx),
705 Arc::new(thread.clone()),
706 this.focus_handle(cx),
707 cx,
708 )
709 })
710 });
711
712 cx.notify();
713 }
714 Err(err) => {
715 this.handle_load_error(err, window, cx);
716 }
717 };
718 })
719 .log_err();
720 });
721
722 cx.spawn(async move |this, cx| {
723 while let Ok(new_version) = new_version_available_rx.recv().await {
724 if let Some(new_version) = new_version {
725 this.update(cx, |this, cx| {
726 this.new_server_version_available = Some(new_version.into());
727 cx.notify();
728 })
729 .log_err();
730 }
731 }
732 })
733 .detach();
734
735 let loading_view = cx.new(|cx| {
736 let update_title_task = cx.spawn(async move |this, cx| {
737 loop {
738 let status = status_rx.recv().await?;
739 this.update(cx, |this: &mut LoadingView, cx| {
740 this.title = status;
741 cx.notify();
742 })?;
743 }
744 });
745
746 LoadingView {
747 title: "Loading…".into(),
748 _load_task: load_task,
749 _update_title_task: update_title_task,
750 }
751 });
752
753 ThreadState::Loading(loading_view)
754 }
755
756 fn handle_auth_required(
757 this: WeakEntity<Self>,
758 err: AuthRequired,
759 agent: Rc<dyn AgentServer>,
760 connection: Rc<dyn AgentConnection>,
761 window: &mut Window,
762 cx: &mut App,
763 ) {
764 let agent_name = agent.name();
765 let (configuration_view, subscription) = if let Some(provider_id) = err.provider_id {
766 let registry = LanguageModelRegistry::global(cx);
767
768 let sub = window.subscribe(®istry, cx, {
769 let provider_id = provider_id.clone();
770 let this = this.clone();
771 move |_, ev, window, cx| {
772 if let language_model::Event::ProviderStateChanged(updated_provider_id) = &ev
773 && &provider_id == updated_provider_id
774 && LanguageModelRegistry::global(cx)
775 .read(cx)
776 .provider(&provider_id)
777 .map_or(false, |provider| provider.is_authenticated(cx))
778 {
779 this.update(cx, |this, cx| {
780 this.reset(window, cx);
781 })
782 .ok();
783 }
784 }
785 });
786
787 let view = registry.read(cx).provider(&provider_id).map(|provider| {
788 provider.configuration_view(
789 language_model::ConfigurationViewTargetAgent::Other(agent_name.clone()),
790 window,
791 cx,
792 )
793 });
794
795 (view, Some(sub))
796 } else {
797 (None, None)
798 };
799
800 this.update(cx, |this, cx| {
801 this.thread_state = ThreadState::Unauthenticated {
802 pending_auth_method: None,
803 connection,
804 configuration_view,
805 description: err
806 .description
807 .clone()
808 .map(|desc| cx.new(|cx| Markdown::new(desc.into(), None, None, cx))),
809 _subscription: subscription,
810 };
811 if this.message_editor.focus_handle(cx).is_focused(window) {
812 this.focus_handle.focus(window)
813 }
814 cx.notify();
815 })
816 .ok();
817 }
818
819 fn handle_load_error(
820 &mut self,
821 err: anyhow::Error,
822 window: &mut Window,
823 cx: &mut Context<Self>,
824 ) {
825 if let Some(load_err) = err.downcast_ref::<LoadError>() {
826 self.thread_state = ThreadState::LoadError(load_err.clone());
827 } else {
828 self.thread_state = ThreadState::LoadError(LoadError::Other(err.to_string().into()))
829 }
830 if self.message_editor.focus_handle(cx).is_focused(window) {
831 self.focus_handle.focus(window)
832 }
833 cx.notify();
834 }
835
836 fn handle_agent_servers_updated(
837 &mut self,
838 _agent_server_store: &Entity<project::AgentServerStore>,
839 _event: &project::AgentServersUpdated,
840 window: &mut Window,
841 cx: &mut Context<Self>,
842 ) {
843 // If we're in a LoadError state OR have a thread_error set (which can happen
844 // when agent.connect() fails during loading), retry loading the thread.
845 // This handles the case where a thread is restored before authentication completes.
846 let should_retry =
847 matches!(&self.thread_state, ThreadState::LoadError(_)) || self.thread_error.is_some();
848
849 if should_retry {
850 self.thread_error = None;
851 self.reset(window, cx);
852 }
853 }
854
855 pub fn workspace(&self) -> &WeakEntity<Workspace> {
856 &self.workspace
857 }
858
859 pub fn thread(&self) -> Option<&Entity<AcpThread>> {
860 match &self.thread_state {
861 ThreadState::Ready { thread, .. } => Some(thread),
862 ThreadState::Unauthenticated { .. }
863 | ThreadState::Loading { .. }
864 | ThreadState::LoadError { .. } => None,
865 }
866 }
867
868 pub fn mode_selector(&self) -> Option<&Entity<ModeSelector>> {
869 match &self.thread_state {
870 ThreadState::Ready { mode_selector, .. } => mode_selector.as_ref(),
871 ThreadState::Unauthenticated { .. }
872 | ThreadState::Loading { .. }
873 | ThreadState::LoadError { .. } => None,
874 }
875 }
876
877 pub fn title(&self, cx: &App) -> SharedString {
878 match &self.thread_state {
879 ThreadState::Ready { .. } | ThreadState::Unauthenticated { .. } => "New Thread".into(),
880 ThreadState::Loading(loading_view) => loading_view.read(cx).title.clone(),
881 ThreadState::LoadError(error) => match error {
882 LoadError::Unsupported { .. } => format!("Upgrade {}", self.agent.name()).into(),
883 LoadError::FailedToInstall(_) => {
884 format!("Failed to Install {}", self.agent.name()).into()
885 }
886 LoadError::Exited { .. } => format!("{} Exited", self.agent.name()).into(),
887 LoadError::Other(_) => format!("Error Loading {}", self.agent.name()).into(),
888 },
889 }
890 }
891
892 pub fn title_editor(&self) -> Option<Entity<Editor>> {
893 if let ThreadState::Ready { title_editor, .. } = &self.thread_state {
894 title_editor.clone()
895 } else {
896 None
897 }
898 }
899
900 pub fn cancel_generation(&mut self, cx: &mut Context<Self>) {
901 self.thread_error.take();
902 self.thread_retry_status.take();
903
904 if let Some(thread) = self.thread() {
905 self._cancel_task = Some(thread.update(cx, |thread, cx| thread.cancel(cx)));
906 }
907 }
908
909 pub fn expand_message_editor(
910 &mut self,
911 _: &ExpandMessageEditor,
912 _window: &mut Window,
913 cx: &mut Context<Self>,
914 ) {
915 self.set_editor_is_expanded(!self.editor_expanded, cx);
916 cx.notify();
917 }
918
919 fn set_editor_is_expanded(&mut self, is_expanded: bool, cx: &mut Context<Self>) {
920 self.editor_expanded = is_expanded;
921 self.message_editor.update(cx, |editor, cx| {
922 if is_expanded {
923 editor.set_mode(
924 EditorMode::Full {
925 scale_ui_elements_with_buffer_font_size: false,
926 show_active_line_background: false,
927 sized_by_content: false,
928 },
929 cx,
930 )
931 } else {
932 let agent_settings = AgentSettings::get_global(cx);
933 editor.set_mode(
934 EditorMode::AutoHeight {
935 min_lines: agent_settings.message_editor_min_lines,
936 max_lines: Some(agent_settings.set_message_editor_max_lines()),
937 },
938 cx,
939 )
940 }
941 });
942 cx.notify();
943 }
944
945 pub fn handle_title_editor_event(
946 &mut self,
947 title_editor: &Entity<Editor>,
948 event: &EditorEvent,
949 window: &mut Window,
950 cx: &mut Context<Self>,
951 ) {
952 let Some(thread) = self.thread() else { return };
953
954 match event {
955 EditorEvent::BufferEdited => {
956 let new_title = title_editor.read(cx).text(cx);
957 thread.update(cx, |thread, cx| {
958 thread
959 .set_title(new_title.into(), cx)
960 .detach_and_log_err(cx);
961 })
962 }
963 EditorEvent::Blurred => {
964 if title_editor.read(cx).text(cx).is_empty() {
965 title_editor.update(cx, |editor, cx| {
966 editor.set_text("New Thread", window, cx);
967 });
968 }
969 }
970 _ => {}
971 }
972 }
973
974 pub fn handle_message_editor_event(
975 &mut self,
976 _: &Entity<MessageEditor>,
977 event: &MessageEditorEvent,
978 window: &mut Window,
979 cx: &mut Context<Self>,
980 ) {
981 match event {
982 MessageEditorEvent::Send => self.send(window, cx),
983 MessageEditorEvent::Cancel => self.cancel_generation(cx),
984 MessageEditorEvent::Focus => {
985 self.cancel_editing(&Default::default(), window, cx);
986 }
987 MessageEditorEvent::LostFocus => {}
988 }
989 }
990
991 pub fn handle_entry_view_event(
992 &mut self,
993 _: &Entity<EntryViewState>,
994 event: &EntryViewEvent,
995 window: &mut Window,
996 cx: &mut Context<Self>,
997 ) {
998 match &event.view_event {
999 ViewEvent::NewDiff(tool_call_id) => {
1000 if AgentSettings::get_global(cx).expand_edit_card {
1001 self.expanded_tool_calls.insert(tool_call_id.clone());
1002 }
1003 }
1004 ViewEvent::NewTerminal(tool_call_id) => {
1005 if AgentSettings::get_global(cx).expand_terminal_card {
1006 self.expanded_tool_calls.insert(tool_call_id.clone());
1007 }
1008 }
1009 ViewEvent::TerminalMovedToBackground(tool_call_id) => {
1010 self.expanded_tool_calls.remove(tool_call_id);
1011 }
1012 ViewEvent::MessageEditorEvent(_editor, MessageEditorEvent::Focus) => {
1013 if let Some(thread) = self.thread()
1014 && let Some(AgentThreadEntry::UserMessage(user_message)) =
1015 thread.read(cx).entries().get(event.entry_index)
1016 && user_message.id.is_some()
1017 {
1018 self.editing_message = Some(event.entry_index);
1019 cx.notify();
1020 }
1021 }
1022 ViewEvent::MessageEditorEvent(editor, MessageEditorEvent::LostFocus) => {
1023 if let Some(thread) = self.thread()
1024 && let Some(AgentThreadEntry::UserMessage(user_message)) =
1025 thread.read(cx).entries().get(event.entry_index)
1026 && user_message.id.is_some()
1027 {
1028 if editor.read(cx).text(cx).as_str() == user_message.content.to_markdown(cx) {
1029 self.editing_message = None;
1030 cx.notify();
1031 }
1032 }
1033 }
1034 ViewEvent::MessageEditorEvent(editor, MessageEditorEvent::Send) => {
1035 self.regenerate(event.entry_index, editor.clone(), window, cx);
1036 }
1037 ViewEvent::MessageEditorEvent(_editor, MessageEditorEvent::Cancel) => {
1038 self.cancel_editing(&Default::default(), window, cx);
1039 }
1040 }
1041 }
1042
1043 fn resume_chat(&mut self, cx: &mut Context<Self>) {
1044 self.thread_error.take();
1045 let Some(thread) = self.thread() else {
1046 return;
1047 };
1048 if !thread.read(cx).can_resume(cx) {
1049 return;
1050 }
1051
1052 let task = thread.update(cx, |thread, cx| thread.resume(cx));
1053 cx.spawn(async move |this, cx| {
1054 let result = task.await;
1055
1056 this.update(cx, |this, cx| {
1057 if let Err(err) = result {
1058 this.handle_thread_error(err, cx);
1059 }
1060 })
1061 })
1062 .detach();
1063 }
1064
1065 fn send(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1066 let Some(thread) = self.thread() else { return };
1067
1068 if self.is_loading_contents {
1069 return;
1070 }
1071
1072 self.history_store.update(cx, |history, cx| {
1073 history.push_recently_opened_entry(
1074 HistoryEntryId::AcpThread(thread.read(cx).session_id().clone()),
1075 cx,
1076 );
1077 });
1078
1079 if thread.read(cx).status() != ThreadStatus::Idle {
1080 self.stop_current_and_send_new_message(window, cx);
1081 return;
1082 }
1083
1084 let text = self.message_editor.read(cx).text(cx);
1085 let text = text.trim();
1086
1087 // Check if this is a login or logout command (only for ACP agents)
1088 let command_name = text.strip_prefix('/');
1089 let is_remote = self.project.read(cx).is_via_remote_server();
1090 let (login_commands, logout_commands) = if let Some(acp_agent) = &self.acp_agent {
1091 let login = if is_remote {
1092 acp_agent.remote_login_commands()
1093 } else {
1094 acp_agent.local_login_commands()
1095 };
1096 let logout = if is_remote {
1097 acp_agent.remote_logout_commands()
1098 } else {
1099 acp_agent.local_logout_commands()
1100 };
1101 (login, logout)
1102 } else {
1103 (vec![], vec![])
1104 };
1105 let is_login_command = if let Some(cmd) = command_name {
1106 login_commands.iter().any(|c| c == cmd)
1107 } else {
1108 false
1109 };
1110 let is_logout_command = if let Some(cmd) = command_name {
1111 logout_commands.iter().any(|c| c == cmd)
1112 } else {
1113 false
1114 };
1115
1116 if is_login_command || is_logout_command {
1117 let ThreadState::Ready { thread, .. } = &self.thread_state else {
1118 return;
1119 };
1120
1121 let connection = thread.read(cx).connection().clone();
1122 let can_login = !connection.auth_methods().is_empty() || !self.auth_commands.is_empty();
1123
1124 // Does the agent have a specific logout command? Prefer that in case they need to reset internal state.
1125 let logout_supported = is_logout_command
1126 && self
1127 .available_commands
1128 .borrow()
1129 .iter()
1130 .any(|command| command_name == Some(command.name.as_str()));
1131
1132 if can_login && !logout_supported {
1133 self.message_editor
1134 .update(cx, |editor, cx| editor.clear(window, cx));
1135
1136 let this = cx.weak_entity();
1137 let agent = self.agent.clone();
1138 window.defer(cx, |window, cx| {
1139 Self::handle_auth_required(
1140 this,
1141 AuthRequired {
1142 description: None,
1143 provider_id: None,
1144 },
1145 agent,
1146 connection,
1147 window,
1148 cx,
1149 );
1150 });
1151 cx.notify();
1152 return;
1153 }
1154 }
1155
1156 self.send_impl(self.message_editor.clone(), window, cx)
1157 }
1158
1159 fn stop_current_and_send_new_message(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1160 let Some(thread) = self.thread().cloned() else {
1161 return;
1162 };
1163
1164 let cancelled = thread.update(cx, |thread, cx| thread.cancel(cx));
1165
1166 cx.spawn_in(window, async move |this, cx| {
1167 cancelled.await;
1168
1169 this.update_in(cx, |this, window, cx| {
1170 this.send_impl(this.message_editor.clone(), window, cx);
1171 })
1172 .ok();
1173 })
1174 .detach();
1175 }
1176
1177 fn send_impl(
1178 &mut self,
1179 message_editor: Entity<MessageEditor>,
1180 window: &mut Window,
1181 cx: &mut Context<Self>,
1182 ) {
1183 let full_mention_content = self.as_native_thread(cx).is_some_and(|thread| {
1184 // Include full contents when using minimal profile
1185 let thread = thread.read(cx);
1186 AgentSettings::get_global(cx)
1187 .profiles
1188 .get(thread.profile())
1189 .is_some_and(|profile| profile.tools.is_empty())
1190 });
1191
1192 let contents = message_editor.update(cx, |message_editor, cx| {
1193 message_editor.contents(full_mention_content, cx)
1194 });
1195
1196 let agent_telemetry_id = self.agent.telemetry_id();
1197
1198 self.thread_error.take();
1199 self.editing_message.take();
1200 self.thread_feedback.clear();
1201
1202 let Some(thread) = self.thread() else {
1203 return;
1204 };
1205 let thread = thread.downgrade();
1206 if self.should_be_following {
1207 self.workspace
1208 .update(cx, |workspace, cx| {
1209 workspace.follow(CollaboratorId::Agent, window, cx);
1210 })
1211 .ok();
1212 }
1213
1214 self.is_loading_contents = true;
1215 let guard = cx.new(|_| ());
1216 cx.observe_release(&guard, |this, _guard, cx| {
1217 this.is_loading_contents = false;
1218 cx.notify();
1219 })
1220 .detach();
1221
1222 let task = cx.spawn_in(window, async move |this, cx| {
1223 let (contents, tracked_buffers) = contents.await?;
1224
1225 if contents.is_empty() {
1226 return Ok(());
1227 }
1228
1229 this.update_in(cx, |this, window, cx| {
1230 this.set_editor_is_expanded(false, cx);
1231 this.scroll_to_bottom(cx);
1232 this.message_editor.update(cx, |message_editor, cx| {
1233 message_editor.clear(window, cx);
1234 });
1235 })?;
1236 let send = thread.update(cx, |thread, cx| {
1237 thread.action_log().update(cx, |action_log, cx| {
1238 for buffer in tracked_buffers {
1239 action_log.buffer_read(buffer, cx)
1240 }
1241 });
1242 drop(guard);
1243
1244 telemetry::event!("Agent Message Sent", agent = agent_telemetry_id);
1245
1246 thread.send(contents, cx)
1247 })?;
1248 send.await
1249 });
1250
1251 cx.spawn(async move |this, cx| {
1252 if let Err(err) = task.await {
1253 this.update(cx, |this, cx| {
1254 this.handle_thread_error(err, cx);
1255 })
1256 .ok();
1257 } else {
1258 this.update(cx, |this, cx| {
1259 this.should_be_following = this
1260 .workspace
1261 .update(cx, |workspace, _| {
1262 workspace.is_being_followed(CollaboratorId::Agent)
1263 })
1264 .unwrap_or_default();
1265 })
1266 .ok();
1267 }
1268 })
1269 .detach();
1270 }
1271
1272 fn cancel_editing(&mut self, _: &ClickEvent, window: &mut Window, cx: &mut Context<Self>) {
1273 let Some(thread) = self.thread().cloned() else {
1274 return;
1275 };
1276
1277 if let Some(index) = self.editing_message.take()
1278 && let Some(editor) = self
1279 .entry_view_state
1280 .read(cx)
1281 .entry(index)
1282 .and_then(|e| e.message_editor())
1283 .cloned()
1284 {
1285 editor.update(cx, |editor, cx| {
1286 if let Some(user_message) = thread
1287 .read(cx)
1288 .entries()
1289 .get(index)
1290 .and_then(|e| e.user_message())
1291 {
1292 editor.set_message(user_message.chunks.clone(), window, cx);
1293 }
1294 })
1295 };
1296 self.focus_handle(cx).focus(window);
1297 cx.notify();
1298 }
1299
1300 fn regenerate(
1301 &mut self,
1302 entry_ix: usize,
1303 message_editor: Entity<MessageEditor>,
1304 window: &mut Window,
1305 cx: &mut Context<Self>,
1306 ) {
1307 let Some(thread) = self.thread().cloned() else {
1308 return;
1309 };
1310 if self.is_loading_contents {
1311 return;
1312 }
1313
1314 let Some(user_message_id) = thread.update(cx, |thread, _| {
1315 thread.entries().get(entry_ix)?.user_message()?.id.clone()
1316 }) else {
1317 return;
1318 };
1319
1320 cx.spawn_in(window, async move |this, cx| {
1321 thread
1322 .update(cx, |thread, cx| thread.rewind(user_message_id, cx))?
1323 .await?;
1324 this.update_in(cx, |this, window, cx| {
1325 this.send_impl(message_editor, window, cx);
1326 })?;
1327 anyhow::Ok(())
1328 })
1329 .detach();
1330 }
1331
1332 fn open_edited_buffer(
1333 &mut self,
1334 buffer: &Entity<Buffer>,
1335 window: &mut Window,
1336 cx: &mut Context<Self>,
1337 ) {
1338 let Some(thread) = self.thread() else {
1339 return;
1340 };
1341
1342 let Some(diff) =
1343 AgentDiffPane::deploy(thread.clone(), self.workspace.clone(), window, cx).log_err()
1344 else {
1345 return;
1346 };
1347
1348 diff.update(cx, |diff, cx| {
1349 diff.move_to_path(PathKey::for_buffer(buffer, cx), window, cx)
1350 })
1351 }
1352
1353 fn handle_open_rules(&mut self, _: &ClickEvent, window: &mut Window, cx: &mut Context<Self>) {
1354 let Some(thread) = self.as_native_thread(cx) else {
1355 return;
1356 };
1357 let project_context = thread.read(cx).project_context().read(cx);
1358
1359 let project_entry_ids = project_context
1360 .worktrees
1361 .iter()
1362 .flat_map(|worktree| worktree.rules_file.as_ref())
1363 .map(|rules_file| ProjectEntryId::from_usize(rules_file.project_entry_id))
1364 .collect::<Vec<_>>();
1365
1366 self.workspace
1367 .update(cx, move |workspace, cx| {
1368 // TODO: Open a multibuffer instead? In some cases this doesn't make the set of rules
1369 // files clear. For example, if rules file 1 is already open but rules file 2 is not,
1370 // this would open and focus rules file 2 in a tab that is not next to rules file 1.
1371 let project = workspace.project().read(cx);
1372 let project_paths = project_entry_ids
1373 .into_iter()
1374 .flat_map(|entry_id| project.path_for_entry(entry_id, cx))
1375 .collect::<Vec<_>>();
1376 for project_path in project_paths {
1377 workspace
1378 .open_path(project_path, None, true, window, cx)
1379 .detach_and_log_err(cx);
1380 }
1381 })
1382 .ok();
1383 }
1384
1385 fn handle_thread_error(&mut self, error: anyhow::Error, cx: &mut Context<Self>) {
1386 self.thread_error = Some(ThreadError::from_err(error, &self.agent));
1387 cx.notify();
1388 }
1389
1390 fn clear_thread_error(&mut self, cx: &mut Context<Self>) {
1391 self.thread_error = None;
1392 cx.notify();
1393 }
1394
1395 fn handle_thread_event(
1396 &mut self,
1397 thread: &Entity<AcpThread>,
1398 event: &AcpThreadEvent,
1399 window: &mut Window,
1400 cx: &mut Context<Self>,
1401 ) {
1402 match event {
1403 AcpThreadEvent::NewEntry => {
1404 let len = thread.read(cx).entries().len();
1405 let index = len - 1;
1406 self.entry_view_state.update(cx, |view_state, cx| {
1407 view_state.sync_entry(index, thread, window, cx);
1408 self.list_state.splice_focusable(
1409 index..index,
1410 [view_state
1411 .entry(index)
1412 .and_then(|entry| entry.focus_handle(cx))],
1413 );
1414 });
1415 }
1416 AcpThreadEvent::EntryUpdated(index) => {
1417 self.entry_view_state.update(cx, |view_state, cx| {
1418 view_state.sync_entry(*index, thread, window, cx)
1419 });
1420 }
1421 AcpThreadEvent::EntriesRemoved(range) => {
1422 self.entry_view_state
1423 .update(cx, |view_state, _cx| view_state.remove(range.clone()));
1424 self.list_state.splice(range.clone(), 0);
1425 }
1426 AcpThreadEvent::ToolAuthorizationRequired => {
1427 self.notify_with_sound("Waiting for tool confirmation", IconName::Info, window, cx);
1428 }
1429 AcpThreadEvent::Retry(retry) => {
1430 self.thread_retry_status = Some(retry.clone());
1431 }
1432 AcpThreadEvent::Stopped => {
1433 self.thread_retry_status.take();
1434 let used_tools = thread.read(cx).used_tools_since_last_user_message();
1435 self.notify_with_sound(
1436 if used_tools {
1437 "Finished running tools"
1438 } else {
1439 "New message"
1440 },
1441 IconName::ZedAssistant,
1442 window,
1443 cx,
1444 );
1445 }
1446 AcpThreadEvent::Refusal => {
1447 self.thread_retry_status.take();
1448 self.thread_error = Some(ThreadError::Refusal);
1449 let model_or_agent_name = self.get_current_model_name(cx);
1450 let notification_message =
1451 format!("{} refused to respond to this request", model_or_agent_name);
1452 self.notify_with_sound(¬ification_message, IconName::Warning, window, cx);
1453 }
1454 AcpThreadEvent::Error => {
1455 self.thread_retry_status.take();
1456 self.notify_with_sound(
1457 "Agent stopped due to an error",
1458 IconName::Warning,
1459 window,
1460 cx,
1461 );
1462 }
1463 AcpThreadEvent::LoadError(error) => {
1464 self.thread_retry_status.take();
1465 self.thread_state = ThreadState::LoadError(error.clone());
1466 if self.message_editor.focus_handle(cx).is_focused(window) {
1467 self.focus_handle.focus(window)
1468 }
1469 }
1470 AcpThreadEvent::TitleUpdated => {
1471 let title = thread.read(cx).title();
1472 if let Some(title_editor) = self.title_editor() {
1473 title_editor.update(cx, |editor, cx| {
1474 if editor.text(cx) != title {
1475 editor.set_text(title, window, cx);
1476 }
1477 });
1478 }
1479 }
1480 AcpThreadEvent::PromptCapabilitiesUpdated => {
1481 self.prompt_capabilities
1482 .replace(thread.read(cx).prompt_capabilities());
1483 }
1484 AcpThreadEvent::TokenUsageUpdated => {}
1485 AcpThreadEvent::AvailableCommandsUpdated(available_commands) => {
1486 let mut available_commands = available_commands.clone();
1487
1488 // Add auth commands only for ACP agents
1489 if let Some(acp_agent) = &self.acp_agent {
1490 let is_remote = self.project.read(cx).is_via_remote_server();
1491 let login_commands = if is_remote {
1492 acp_agent.remote_login_commands()
1493 } else {
1494 acp_agent.local_login_commands()
1495 };
1496 let logout_commands = if is_remote {
1497 acp_agent.remote_logout_commands()
1498 } else {
1499 acp_agent.local_logout_commands()
1500 };
1501
1502 // Add login commands from the agent
1503 for command_name in login_commands {
1504 available_commands.push(acp::AvailableCommand {
1505 name: command_name,
1506 description: "Authenticate".to_owned(),
1507 input: None,
1508 meta: None,
1509 });
1510 }
1511
1512 // Add logout commands from the agent
1513 for command_name in logout_commands {
1514 available_commands.push(acp::AvailableCommand {
1515 name: command_name,
1516 description: "Authenticate".to_owned(),
1517 input: None,
1518 meta: None,
1519 });
1520 }
1521 }
1522
1523 self.available_commands.replace(available_commands);
1524 }
1525 AcpThreadEvent::ModeUpdated(_mode) => {
1526 // The connection keeps track of the mode
1527 cx.notify();
1528 }
1529 }
1530 cx.notify();
1531 }
1532
1533 fn authenticate(
1534 &mut self,
1535 method: acp::AuthMethodId,
1536 window: &mut Window,
1537 cx: &mut Context<Self>,
1538 ) {
1539 let ThreadState::Unauthenticated {
1540 connection,
1541 pending_auth_method,
1542 configuration_view,
1543 ..
1544 } = &mut self.thread_state
1545 else {
1546 return;
1547 };
1548
1549 if method.0.as_ref() == "gemini-api-key" {
1550 let registry = LanguageModelRegistry::global(cx);
1551 let provider = registry
1552 .read(cx)
1553 .provider(&language_model::GOOGLE_PROVIDER_ID)
1554 .unwrap();
1555 if !provider.is_authenticated(cx) {
1556 let this = cx.weak_entity();
1557 let agent = self.agent.clone();
1558 let connection = connection.clone();
1559 window.defer(cx, |window, cx| {
1560 Self::handle_auth_required(
1561 this,
1562 AuthRequired {
1563 description: Some("GEMINI_API_KEY must be set".to_owned()),
1564 provider_id: Some(language_model::GOOGLE_PROVIDER_ID),
1565 },
1566 agent,
1567 connection,
1568 window,
1569 cx,
1570 );
1571 });
1572 return;
1573 }
1574 } else if method.0.as_ref() == "anthropic-api-key" {
1575 let registry = LanguageModelRegistry::global(cx);
1576 let provider = registry
1577 .read(cx)
1578 .provider(&language_model::ANTHROPIC_PROVIDER_ID)
1579 .unwrap();
1580 let this = cx.weak_entity();
1581 let agent = self.agent.clone();
1582 let connection = connection.clone();
1583 window.defer(cx, move |window, cx| {
1584 if !provider.is_authenticated(cx) {
1585 Self::handle_auth_required(
1586 this,
1587 AuthRequired {
1588 description: Some("ANTHROPIC_API_KEY must be set".to_owned()),
1589 provider_id: Some(language_model::ANTHROPIC_PROVIDER_ID),
1590 },
1591 agent,
1592 connection,
1593 window,
1594 cx,
1595 );
1596 } else {
1597 this.update(cx, |this, cx| {
1598 this.thread_state = Self::initial_state(
1599 agent,
1600 None,
1601 this.workspace.clone(),
1602 this.project.clone(),
1603 window,
1604 cx,
1605 )
1606 })
1607 .ok();
1608 }
1609 });
1610 return;
1611 } else if method.0.as_ref() == "vertex-ai"
1612 && std::env::var("GOOGLE_API_KEY").is_err()
1613 && (std::env::var("GOOGLE_CLOUD_PROJECT").is_err()
1614 || (std::env::var("GOOGLE_CLOUD_PROJECT").is_err()))
1615 {
1616 let this = cx.weak_entity();
1617 let agent = self.agent.clone();
1618 let connection = connection.clone();
1619
1620 window.defer(cx, |window, cx| {
1621 Self::handle_auth_required(
1622 this,
1623 AuthRequired {
1624 description: Some(
1625 "GOOGLE_API_KEY must be set in the environment to use Vertex AI authentication for Gemini CLI. Please export it and restart Zed."
1626 .to_owned(),
1627 ),
1628 provider_id: None,
1629 },
1630 agent,
1631 connection,
1632 window,
1633 cx,
1634 )
1635 });
1636 return;
1637 }
1638
1639 self.thread_error.take();
1640 configuration_view.take();
1641 pending_auth_method.replace(method.clone());
1642 let authenticate = if let Some(login) = self.auth_commands.get(method.0.as_ref()).cloned() {
1643 if let Some(workspace) = self.workspace.upgrade() {
1644 Self::spawn_external_agent_login(login, workspace, false, window, cx)
1645 } else {
1646 Task::ready(Ok(()))
1647 }
1648 } else {
1649 connection.authenticate(method, cx)
1650 };
1651 cx.notify();
1652 self.auth_task =
1653 Some(cx.spawn_in(window, {
1654 let agent = self.agent.clone();
1655 async move |this, cx| {
1656 let result = authenticate.await;
1657
1658 match &result {
1659 Ok(_) => telemetry::event!(
1660 "Authenticate Agent Succeeded",
1661 agent = agent.telemetry_id()
1662 ),
1663 Err(_) => {
1664 telemetry::event!(
1665 "Authenticate Agent Failed",
1666 agent = agent.telemetry_id(),
1667 )
1668 }
1669 }
1670
1671 this.update_in(cx, |this, window, cx| {
1672 if let Err(err) = result {
1673 if let ThreadState::Unauthenticated {
1674 pending_auth_method,
1675 ..
1676 } = &mut this.thread_state
1677 {
1678 pending_auth_method.take();
1679 }
1680 this.handle_thread_error(err, cx);
1681 } else {
1682 this.reset(window, cx);
1683 }
1684 this.auth_task.take()
1685 })
1686 .ok();
1687 }
1688 }));
1689 }
1690
1691 fn spawn_external_agent_login(
1692 login: task::SpawnInTerminal,
1693 workspace: Entity<Workspace>,
1694 previous_attempt: bool,
1695 window: &mut Window,
1696 cx: &mut App,
1697 ) -> Task<Result<()>> {
1698 let Some(terminal_panel) = workspace.read(cx).panel::<TerminalPanel>(cx) else {
1699 return Task::ready(Ok(()));
1700 };
1701 let project = workspace.read(cx).project().clone();
1702
1703 window.spawn(cx, async move |cx| {
1704 let mut task = login.clone();
1705 task.shell = task::Shell::WithArguments {
1706 program: task.command.take().expect("login command should be set"),
1707 args: std::mem::take(&mut task.args),
1708 title_override: None
1709 };
1710 task.full_label = task.label.clone();
1711 task.id = task::TaskId(format!("external-agent-{}-login", task.label));
1712 task.command_label = task.label.clone();
1713 task.use_new_terminal = true;
1714 task.allow_concurrent_runs = true;
1715 task.hide = task::HideStrategy::Always;
1716
1717 let terminal = terminal_panel.update_in(cx, |terminal_panel, window, cx| {
1718 terminal_panel.spawn_task(&task, window, cx)
1719 })?;
1720
1721 let terminal = terminal.await?;
1722 let mut exit_status = terminal
1723 .read_with(cx, |terminal, cx| terminal.wait_for_completed_task(cx))?
1724 .fuse();
1725
1726 let logged_in = cx
1727 .spawn({
1728 let terminal = terminal.clone();
1729 async move |cx| {
1730 loop {
1731 cx.background_executor().timer(Duration::from_secs(1)).await;
1732 let content =
1733 terminal.update(cx, |terminal, _cx| terminal.get_content())?;
1734 if content.contains("Login successful")
1735 || content.contains("Type your message")
1736 {
1737 return anyhow::Ok(());
1738 }
1739 }
1740 }
1741 })
1742 .fuse();
1743 futures::pin_mut!(logged_in);
1744 futures::select_biased! {
1745 result = logged_in => {
1746 if let Err(e) = result {
1747 log::error!("{e}");
1748 return Err(anyhow!("exited before logging in"));
1749 }
1750 }
1751 _ = exit_status => {
1752 if !previous_attempt && project.read_with(cx, |project, _| project.is_via_remote_server())? && login.label.contains("gemini") {
1753 return cx.update(|window, cx| Self::spawn_external_agent_login(login, workspace, true, window, cx))?.await
1754 }
1755 return Err(anyhow!("exited before logging in"));
1756 }
1757 }
1758 terminal.update(cx, |terminal, _| terminal.kill_active_task())?;
1759 Ok(())
1760 })
1761 }
1762
1763 fn authorize_tool_call(
1764 &mut self,
1765 tool_call_id: acp::ToolCallId,
1766 option_id: acp::PermissionOptionId,
1767 option_kind: acp::PermissionOptionKind,
1768 window: &mut Window,
1769 cx: &mut Context<Self>,
1770 ) {
1771 let Some(thread) = self.thread() else {
1772 return;
1773 };
1774 thread.update(cx, |thread, cx| {
1775 thread.authorize_tool_call(tool_call_id, option_id, option_kind, cx);
1776 });
1777 if self.should_be_following {
1778 self.workspace
1779 .update(cx, |workspace, cx| {
1780 workspace.follow(CollaboratorId::Agent, window, cx);
1781 })
1782 .ok();
1783 }
1784 cx.notify();
1785 }
1786
1787 fn restore_checkpoint(&mut self, message_id: &UserMessageId, cx: &mut Context<Self>) {
1788 let Some(thread) = self.thread() else {
1789 return;
1790 };
1791
1792 thread
1793 .update(cx, |thread, cx| {
1794 thread.restore_checkpoint(message_id.clone(), cx)
1795 })
1796 .detach_and_log_err(cx);
1797 }
1798
1799 fn render_entry(
1800 &self,
1801 entry_ix: usize,
1802 total_entries: usize,
1803 entry: &AgentThreadEntry,
1804 window: &mut Window,
1805 cx: &Context<Self>,
1806 ) -> AnyElement {
1807 let primary = match &entry {
1808 AgentThreadEntry::UserMessage(message) => {
1809 let Some(editor) = self
1810 .entry_view_state
1811 .read(cx)
1812 .entry(entry_ix)
1813 .and_then(|entry| entry.message_editor())
1814 .cloned()
1815 else {
1816 return Empty.into_any_element();
1817 };
1818
1819 let editing = self.editing_message == Some(entry_ix);
1820 let editor_focus = editor.focus_handle(cx).is_focused(window);
1821 let focus_border = cx.theme().colors().border_focused;
1822
1823 let rules_item = if entry_ix == 0 {
1824 self.render_rules_item(cx)
1825 } else {
1826 None
1827 };
1828
1829 let has_checkpoint_button = message
1830 .checkpoint
1831 .as_ref()
1832 .is_some_and(|checkpoint| checkpoint.show);
1833
1834 let agent_name = self.agent.name();
1835
1836 v_flex()
1837 .id(("user_message", entry_ix))
1838 .map(|this| {
1839 if entry_ix == 0 && !has_checkpoint_button && rules_item.is_none() {
1840 this.pt(rems_from_px(18.))
1841 } else if rules_item.is_some() {
1842 this.pt_3()
1843 } else {
1844 this.pt_2()
1845 }
1846 })
1847 .pb_3()
1848 .px_2()
1849 .gap_1p5()
1850 .w_full()
1851 .children(rules_item)
1852 .children(message.id.clone().and_then(|message_id| {
1853 message.checkpoint.as_ref()?.show.then(|| {
1854 h_flex()
1855 .px_3()
1856 .gap_2()
1857 .child(Divider::horizontal())
1858 .child(
1859 Button::new("restore-checkpoint", "Restore Checkpoint")
1860 .icon(IconName::Undo)
1861 .icon_size(IconSize::XSmall)
1862 .icon_position(IconPosition::Start)
1863 .label_size(LabelSize::XSmall)
1864 .icon_color(Color::Muted)
1865 .color(Color::Muted)
1866 .tooltip(Tooltip::text("Restores all files in the project to the content they had at this point in the conversation."))
1867 .on_click(cx.listener(move |this, _, _window, cx| {
1868 this.restore_checkpoint(&message_id, cx);
1869 }))
1870 )
1871 .child(Divider::horizontal())
1872 })
1873 }))
1874 .child(
1875 div()
1876 .relative()
1877 .child(
1878 div()
1879 .py_3()
1880 .px_2()
1881 .rounded_md()
1882 .shadow_md()
1883 .bg(cx.theme().colors().editor_background)
1884 .border_1()
1885 .when(editing && !editor_focus, |this| this.border_dashed())
1886 .border_color(cx.theme().colors().border)
1887 .map(|this|{
1888 if editing && editor_focus {
1889 this.border_color(focus_border)
1890 } else if message.id.is_some() {
1891 this.hover(|s| s.border_color(focus_border.opacity(0.8)))
1892 } else {
1893 this
1894 }
1895 })
1896 .text_xs()
1897 .child(editor.clone().into_any_element()),
1898 )
1899 .when(editor_focus, |this| {
1900 let base_container = h_flex()
1901 .absolute()
1902 .top_neg_3p5()
1903 .right_3()
1904 .gap_1()
1905 .rounded_sm()
1906 .border_1()
1907 .border_color(cx.theme().colors().border)
1908 .bg(cx.theme().colors().editor_background)
1909 .overflow_hidden();
1910
1911 if message.id.is_some() {
1912 this.child(
1913 base_container
1914 .child(
1915 IconButton::new("cancel", IconName::Close)
1916 .disabled(self.is_loading_contents)
1917 .icon_color(Color::Error)
1918 .icon_size(IconSize::XSmall)
1919 .on_click(cx.listener(Self::cancel_editing))
1920 )
1921 .child(
1922 if self.is_loading_contents {
1923 div()
1924 .id("loading-edited-message-content")
1925 .tooltip(Tooltip::text("Loading Added Context…"))
1926 .child(loading_contents_spinner(IconSize::XSmall))
1927 .into_any_element()
1928 } else {
1929 IconButton::new("regenerate", IconName::Return)
1930 .icon_color(Color::Muted)
1931 .icon_size(IconSize::XSmall)
1932 .tooltip(Tooltip::text(
1933 "Editing will restart the thread from this point."
1934 ))
1935 .on_click(cx.listener({
1936 let editor = editor.clone();
1937 move |this, _, window, cx| {
1938 this.regenerate(
1939 entry_ix, editor.clone(), window, cx,
1940 );
1941 }
1942 })).into_any_element()
1943 }
1944 )
1945 )
1946 } else {
1947 this.child(
1948 base_container
1949 .border_dashed()
1950 .child(
1951 IconButton::new("editing_unavailable", IconName::PencilUnavailable)
1952 .icon_size(IconSize::Small)
1953 .icon_color(Color::Muted)
1954 .style(ButtonStyle::Transparent)
1955 .tooltip(move |_window, cx| {
1956 cx.new(|_| UnavailableEditingTooltip::new(agent_name.clone()))
1957 .into()
1958 })
1959 )
1960 )
1961 }
1962 }),
1963 )
1964 .into_any()
1965 }
1966 AgentThreadEntry::AssistantMessage(AssistantMessage { chunks }) => {
1967 let is_last = entry_ix + 1 == total_entries;
1968
1969 let style = default_markdown_style(false, false, window, cx);
1970 let message_body = v_flex()
1971 .w_full()
1972 .gap_3()
1973 .children(chunks.iter().enumerate().filter_map(
1974 |(chunk_ix, chunk)| match chunk {
1975 AssistantMessageChunk::Message { block } => {
1976 block.markdown().map(|md| {
1977 self.render_markdown(md.clone(), style.clone())
1978 .into_any_element()
1979 })
1980 }
1981 AssistantMessageChunk::Thought { block } => {
1982 block.markdown().map(|md| {
1983 self.render_thinking_block(
1984 entry_ix,
1985 chunk_ix,
1986 md.clone(),
1987 window,
1988 cx,
1989 )
1990 .into_any_element()
1991 })
1992 }
1993 },
1994 ))
1995 .into_any();
1996
1997 v_flex()
1998 .px_5()
1999 .py_1p5()
2000 .when(is_last, |this| this.pb_4())
2001 .w_full()
2002 .text_ui(cx)
2003 .child(message_body)
2004 .into_any()
2005 }
2006 AgentThreadEntry::ToolCall(tool_call) => {
2007 let has_terminals = tool_call.terminals().next().is_some();
2008
2009 div().w_full().map(|this| {
2010 if has_terminals {
2011 this.children(tool_call.terminals().map(|terminal| {
2012 self.render_terminal_tool_call(
2013 entry_ix, terminal, tool_call, window, cx,
2014 )
2015 }))
2016 } else {
2017 this.child(self.render_tool_call(entry_ix, tool_call, window, cx))
2018 }
2019 })
2020 }
2021 .into_any(),
2022 };
2023
2024 let Some(thread) = self.thread() else {
2025 return primary;
2026 };
2027
2028 let primary = if entry_ix == total_entries - 1 {
2029 v_flex()
2030 .w_full()
2031 .child(primary)
2032 .child(self.render_thread_controls(&thread, cx))
2033 .when_some(
2034 self.thread_feedback.comments_editor.clone(),
2035 |this, editor| this.child(Self::render_feedback_feedback_editor(editor, cx)),
2036 )
2037 .into_any_element()
2038 } else {
2039 primary
2040 };
2041
2042 if let Some(editing_index) = self.editing_message.as_ref()
2043 && *editing_index < entry_ix
2044 {
2045 let backdrop = div()
2046 .id(("backdrop", entry_ix))
2047 .size_full()
2048 .absolute()
2049 .inset_0()
2050 .bg(cx.theme().colors().panel_background)
2051 .opacity(0.8)
2052 .block_mouse_except_scroll()
2053 .on_click(cx.listener(Self::cancel_editing));
2054
2055 div()
2056 .relative()
2057 .child(primary)
2058 .child(backdrop)
2059 .into_any_element()
2060 } else {
2061 primary
2062 }
2063 }
2064
2065 fn tool_card_header_bg(&self, cx: &Context<Self>) -> Hsla {
2066 cx.theme()
2067 .colors()
2068 .element_background
2069 .blend(cx.theme().colors().editor_foreground.opacity(0.025))
2070 }
2071
2072 fn tool_card_border_color(&self, cx: &Context<Self>) -> Hsla {
2073 cx.theme().colors().border.opacity(0.8)
2074 }
2075
2076 fn tool_name_font_size(&self) -> Rems {
2077 rems_from_px(13.)
2078 }
2079
2080 fn render_thinking_block(
2081 &self,
2082 entry_ix: usize,
2083 chunk_ix: usize,
2084 chunk: Entity<Markdown>,
2085 window: &Window,
2086 cx: &Context<Self>,
2087 ) -> AnyElement {
2088 let header_id = SharedString::from(format!("thinking-block-header-{}", entry_ix));
2089 let card_header_id = SharedString::from("inner-card-header");
2090
2091 let key = (entry_ix, chunk_ix);
2092
2093 let is_open = self.expanded_thinking_blocks.contains(&key);
2094
2095 let scroll_handle = self
2096 .entry_view_state
2097 .read(cx)
2098 .entry(entry_ix)
2099 .and_then(|entry| entry.scroll_handle_for_assistant_message_chunk(chunk_ix));
2100
2101 let thinking_content = {
2102 div()
2103 .id(("thinking-content", chunk_ix))
2104 .when_some(scroll_handle, |this, scroll_handle| {
2105 this.track_scroll(&scroll_handle)
2106 })
2107 .text_ui_sm(cx)
2108 .overflow_hidden()
2109 .child(
2110 self.render_markdown(chunk, default_markdown_style(false, false, window, cx)),
2111 )
2112 };
2113
2114 v_flex()
2115 .gap_1()
2116 .child(
2117 h_flex()
2118 .id(header_id)
2119 .group(&card_header_id)
2120 .relative()
2121 .w_full()
2122 .pr_1()
2123 .justify_between()
2124 .child(
2125 h_flex()
2126 .h(window.line_height() - px(2.))
2127 .gap_1p5()
2128 .overflow_hidden()
2129 .child(
2130 Icon::new(IconName::ToolThink)
2131 .size(IconSize::Small)
2132 .color(Color::Muted),
2133 )
2134 .child(
2135 div()
2136 .text_size(self.tool_name_font_size())
2137 .text_color(cx.theme().colors().text_muted)
2138 .child("Thinking"),
2139 ),
2140 )
2141 .child(
2142 Disclosure::new(("expand", entry_ix), is_open)
2143 .opened_icon(IconName::ChevronUp)
2144 .closed_icon(IconName::ChevronDown)
2145 .visible_on_hover(&card_header_id)
2146 .on_click(cx.listener({
2147 move |this, _event, _window, cx| {
2148 if is_open {
2149 this.expanded_thinking_blocks.remove(&key);
2150 } else {
2151 this.expanded_thinking_blocks.insert(key);
2152 }
2153 cx.notify();
2154 }
2155 })),
2156 )
2157 .on_click(cx.listener({
2158 move |this, _event, _window, cx| {
2159 if is_open {
2160 this.expanded_thinking_blocks.remove(&key);
2161 } else {
2162 this.expanded_thinking_blocks.insert(key);
2163 }
2164 cx.notify();
2165 }
2166 })),
2167 )
2168 .when(is_open, |this| {
2169 this.child(
2170 div()
2171 .ml_1p5()
2172 .pl_3p5()
2173 .border_l_1()
2174 .border_color(self.tool_card_border_color(cx))
2175 .child(thinking_content),
2176 )
2177 })
2178 .into_any_element()
2179 }
2180
2181 fn render_tool_call(
2182 &self,
2183 entry_ix: usize,
2184 tool_call: &ToolCall,
2185 window: &Window,
2186 cx: &Context<Self>,
2187 ) -> Div {
2188 let has_location = tool_call.locations.len() == 1;
2189 let card_header_id = SharedString::from("inner-tool-call-header");
2190
2191 let failed_or_canceled = match &tool_call.status {
2192 ToolCallStatus::Rejected | ToolCallStatus::Canceled | ToolCallStatus::Failed => true,
2193 _ => false,
2194 };
2195
2196 let needs_confirmation = matches!(
2197 tool_call.status,
2198 ToolCallStatus::WaitingForConfirmation { .. }
2199 );
2200 let is_terminal_tool = matches!(tool_call.kind, acp::ToolKind::Execute);
2201 let is_edit =
2202 matches!(tool_call.kind, acp::ToolKind::Edit) || tool_call.diffs().next().is_some();
2203
2204 let use_card_layout = needs_confirmation || is_edit || is_terminal_tool;
2205
2206 let is_collapsible = !tool_call.content.is_empty() && !needs_confirmation;
2207
2208 let is_open = needs_confirmation || self.expanded_tool_calls.contains(&tool_call.id);
2209
2210 let tool_output_display =
2211 if is_open {
2212 match &tool_call.status {
2213 ToolCallStatus::WaitingForConfirmation { options, .. } => v_flex()
2214 .w_full()
2215 .children(tool_call.content.iter().enumerate().map(
2216 |(content_ix, content)| {
2217 div()
2218 .child(self.render_tool_call_content(
2219 entry_ix,
2220 content,
2221 content_ix,
2222 tool_call,
2223 use_card_layout,
2224 window,
2225 cx,
2226 ))
2227 .into_any_element()
2228 },
2229 ))
2230 .child(self.render_permission_buttons(
2231 tool_call.kind,
2232 options,
2233 entry_ix,
2234 tool_call.id.clone(),
2235 window,
2236 cx,
2237 ))
2238 .into_any(),
2239 ToolCallStatus::Pending | ToolCallStatus::InProgress
2240 if is_edit
2241 && tool_call.content.is_empty()
2242 && self.as_native_connection(cx).is_some() =>
2243 {
2244 self.render_diff_loading(cx).into_any()
2245 }
2246 ToolCallStatus::Pending
2247 | ToolCallStatus::InProgress
2248 | ToolCallStatus::Completed
2249 | ToolCallStatus::Failed
2250 | ToolCallStatus::Canceled => v_flex()
2251 .w_full()
2252 .children(tool_call.content.iter().enumerate().map(
2253 |(content_ix, content)| {
2254 div().child(self.render_tool_call_content(
2255 entry_ix,
2256 content,
2257 content_ix,
2258 tool_call,
2259 use_card_layout,
2260 window,
2261 cx,
2262 ))
2263 },
2264 ))
2265 .into_any(),
2266 ToolCallStatus::Rejected => Empty.into_any(),
2267 }
2268 .into()
2269 } else {
2270 None
2271 };
2272
2273 v_flex()
2274 .map(|this| {
2275 if use_card_layout {
2276 this.my_1p5()
2277 .rounded_md()
2278 .border_1()
2279 .border_color(self.tool_card_border_color(cx))
2280 .bg(cx.theme().colors().editor_background)
2281 .overflow_hidden()
2282 } else {
2283 this.my_1()
2284 }
2285 })
2286 .map(|this| {
2287 if has_location && !use_card_layout {
2288 this.ml_4()
2289 } else {
2290 this.ml_5()
2291 }
2292 })
2293 .mr_5()
2294 .map(|this| {
2295 if is_terminal_tool {
2296 this.child(
2297 v_flex()
2298 .p_1p5()
2299 .gap_0p5()
2300 .text_ui_sm(cx)
2301 .bg(self.tool_card_header_bg(cx))
2302 .child(
2303 Label::new("Run Command")
2304 .buffer_font(cx)
2305 .size(LabelSize::XSmall)
2306 .color(Color::Muted),
2307 )
2308 .child(
2309 MarkdownElement::new(
2310 tool_call.label.clone(),
2311 terminal_command_markdown_style(window, cx),
2312 )
2313 .code_block_renderer(
2314 markdown::CodeBlockRenderer::Default {
2315 copy_button: false,
2316 copy_button_on_hover: false,
2317 border: false,
2318 },
2319 )
2320 ),
2321 )
2322 } else {
2323 this.child(
2324 h_flex()
2325 .group(&card_header_id)
2326 .relative()
2327 .w_full()
2328 .gap_1()
2329 .justify_between()
2330 .when(use_card_layout, |this| {
2331 this.p_0p5()
2332 .rounded_t(rems_from_px(5.))
2333 .bg(self.tool_card_header_bg(cx))
2334 })
2335 .child(self.render_tool_call_label(
2336 entry_ix,
2337 tool_call,
2338 is_edit,
2339 use_card_layout,
2340 window,
2341 cx,
2342 ))
2343 .when(is_collapsible || failed_or_canceled, |this| {
2344 this.child(
2345 h_flex()
2346 .px_1()
2347 .gap_px()
2348 .when(is_collapsible, |this| {
2349 this.child(
2350 Disclosure::new(("expand", entry_ix), is_open)
2351 .opened_icon(IconName::ChevronUp)
2352 .closed_icon(IconName::ChevronDown)
2353 .visible_on_hover(&card_header_id)
2354 .on_click(cx.listener({
2355 let id = tool_call.id.clone();
2356 move |this: &mut Self, _, _, cx: &mut Context<Self>| {
2357 if is_open {
2358 this.expanded_tool_calls.remove(&id);
2359 } else {
2360 this.expanded_tool_calls.insert(id.clone());
2361 }
2362 cx.notify();
2363 }
2364 })),
2365 )
2366 })
2367 .when(failed_or_canceled, |this| {
2368 this.child(
2369 Icon::new(IconName::Close)
2370 .color(Color::Error)
2371 .size(IconSize::Small),
2372 )
2373 }),
2374 )
2375 }),
2376 )
2377 }
2378 })
2379 .children(tool_output_display)
2380 }
2381
2382 fn render_tool_call_label(
2383 &self,
2384 entry_ix: usize,
2385 tool_call: &ToolCall,
2386 is_edit: bool,
2387 use_card_layout: bool,
2388 window: &Window,
2389 cx: &Context<Self>,
2390 ) -> Div {
2391 let has_location = tool_call.locations.len() == 1;
2392
2393 let tool_icon = if tool_call.kind == acp::ToolKind::Edit && has_location {
2394 FileIcons::get_icon(&tool_call.locations[0].path, cx)
2395 .map(Icon::from_path)
2396 .unwrap_or(Icon::new(IconName::ToolPencil))
2397 } else {
2398 Icon::new(match tool_call.kind {
2399 acp::ToolKind::Read => IconName::ToolSearch,
2400 acp::ToolKind::Edit => IconName::ToolPencil,
2401 acp::ToolKind::Delete => IconName::ToolDeleteFile,
2402 acp::ToolKind::Move => IconName::ArrowRightLeft,
2403 acp::ToolKind::Search => IconName::ToolSearch,
2404 acp::ToolKind::Execute => IconName::ToolTerminal,
2405 acp::ToolKind::Think => IconName::ToolThink,
2406 acp::ToolKind::Fetch => IconName::ToolWeb,
2407 acp::ToolKind::SwitchMode => IconName::ArrowRightLeft,
2408 acp::ToolKind::Other => IconName::ToolHammer,
2409 })
2410 }
2411 .size(IconSize::Small)
2412 .color(Color::Muted);
2413
2414 let gradient_overlay = {
2415 div()
2416 .absolute()
2417 .top_0()
2418 .right_0()
2419 .w_12()
2420 .h_full()
2421 .map(|this| {
2422 if use_card_layout {
2423 this.bg(linear_gradient(
2424 90.,
2425 linear_color_stop(self.tool_card_header_bg(cx), 1.),
2426 linear_color_stop(self.tool_card_header_bg(cx).opacity(0.2), 0.),
2427 ))
2428 } else {
2429 this.bg(linear_gradient(
2430 90.,
2431 linear_color_stop(cx.theme().colors().panel_background, 1.),
2432 linear_color_stop(
2433 cx.theme().colors().panel_background.opacity(0.2),
2434 0.,
2435 ),
2436 ))
2437 }
2438 })
2439 };
2440
2441 h_flex()
2442 .relative()
2443 .w_full()
2444 .h(window.line_height() - px(2.))
2445 .text_size(self.tool_name_font_size())
2446 .gap_1p5()
2447 .when(has_location || use_card_layout, |this| this.px_1())
2448 .when(has_location, |this| {
2449 this.cursor(CursorStyle::PointingHand)
2450 .rounded(rems_from_px(3.)) // Concentric border radius
2451 .hover(|s| s.bg(cx.theme().colors().element_hover.opacity(0.5)))
2452 })
2453 .overflow_hidden()
2454 .child(tool_icon)
2455 .child(if has_location {
2456 h_flex()
2457 .id(("open-tool-call-location", entry_ix))
2458 .w_full()
2459 .map(|this| {
2460 if use_card_layout {
2461 this.text_color(cx.theme().colors().text)
2462 } else {
2463 this.text_color(cx.theme().colors().text_muted)
2464 }
2465 })
2466 .child(self.render_markdown(
2467 tool_call.label.clone(),
2468 MarkdownStyle {
2469 prevent_mouse_interaction: true,
2470 ..default_markdown_style(false, true, window, cx)
2471 },
2472 ))
2473 .tooltip(Tooltip::text("Jump to File"))
2474 .on_click(cx.listener(move |this, _, window, cx| {
2475 this.open_tool_call_location(entry_ix, 0, window, cx);
2476 }))
2477 .into_any_element()
2478 } else {
2479 h_flex()
2480 .w_full()
2481 .child(self.render_markdown(
2482 tool_call.label.clone(),
2483 default_markdown_style(false, true, window, cx),
2484 ))
2485 .into_any()
2486 })
2487 .when(!is_edit, |this| this.child(gradient_overlay))
2488 }
2489
2490 fn render_tool_call_content(
2491 &self,
2492 entry_ix: usize,
2493 content: &ToolCallContent,
2494 context_ix: usize,
2495 tool_call: &ToolCall,
2496 card_layout: bool,
2497 window: &Window,
2498 cx: &Context<Self>,
2499 ) -> AnyElement {
2500 match content {
2501 ToolCallContent::ContentBlock(content) => {
2502 if let Some(resource_link) = content.resource_link() {
2503 self.render_resource_link(resource_link, cx)
2504 } else if let Some(markdown) = content.markdown() {
2505 self.render_markdown_output(
2506 markdown.clone(),
2507 tool_call.id.clone(),
2508 context_ix,
2509 card_layout,
2510 window,
2511 cx,
2512 )
2513 } else {
2514 Empty.into_any_element()
2515 }
2516 }
2517 ToolCallContent::Diff(diff) => self.render_diff_editor(entry_ix, diff, tool_call, cx),
2518 ToolCallContent::Terminal(terminal) => {
2519 self.render_terminal_tool_call(entry_ix, terminal, tool_call, window, cx)
2520 }
2521 }
2522 }
2523
2524 fn render_markdown_output(
2525 &self,
2526 markdown: Entity<Markdown>,
2527 tool_call_id: acp::ToolCallId,
2528 context_ix: usize,
2529 card_layout: bool,
2530 window: &Window,
2531 cx: &Context<Self>,
2532 ) -> AnyElement {
2533 let button_id = SharedString::from(format!("tool_output-{:?}", tool_call_id));
2534
2535 v_flex()
2536 .mt_1p5()
2537 .gap_2()
2538 .when(!card_layout, |this| {
2539 this.ml(rems(0.4))
2540 .px_3p5()
2541 .border_l_1()
2542 .border_color(self.tool_card_border_color(cx))
2543 })
2544 .when(card_layout, |this| {
2545 this.px_2().pb_2().when(context_ix > 0, |this| {
2546 this.border_t_1()
2547 .pt_2()
2548 .border_color(self.tool_card_border_color(cx))
2549 })
2550 })
2551 .text_xs()
2552 .text_color(cx.theme().colors().text_muted)
2553 .child(self.render_markdown(markdown, default_markdown_style(false, false, window, cx)))
2554 .when(!card_layout, |this| {
2555 this.child(
2556 IconButton::new(button_id, IconName::ChevronUp)
2557 .full_width()
2558 .style(ButtonStyle::Outlined)
2559 .icon_color(Color::Muted)
2560 .on_click(cx.listener({
2561 move |this: &mut Self, _, _, cx: &mut Context<Self>| {
2562 this.expanded_tool_calls.remove(&tool_call_id);
2563 cx.notify();
2564 }
2565 })),
2566 )
2567 })
2568 .into_any_element()
2569 }
2570
2571 fn render_resource_link(
2572 &self,
2573 resource_link: &acp::ResourceLink,
2574 cx: &Context<Self>,
2575 ) -> AnyElement {
2576 let uri: SharedString = resource_link.uri.clone().into();
2577 let is_file = resource_link.uri.strip_prefix("file://");
2578
2579 let label: SharedString = if let Some(abs_path) = is_file {
2580 if let Some(project_path) = self
2581 .project
2582 .read(cx)
2583 .project_path_for_absolute_path(&Path::new(abs_path), cx)
2584 && let Some(worktree) = self
2585 .project
2586 .read(cx)
2587 .worktree_for_id(project_path.worktree_id, cx)
2588 {
2589 worktree
2590 .read(cx)
2591 .full_path(&project_path.path)
2592 .to_string_lossy()
2593 .to_string()
2594 .into()
2595 } else {
2596 abs_path.to_string().into()
2597 }
2598 } else {
2599 uri.clone()
2600 };
2601
2602 let button_id = SharedString::from(format!("item-{}", uri));
2603
2604 div()
2605 .ml(rems(0.4))
2606 .pl_2p5()
2607 .border_l_1()
2608 .border_color(self.tool_card_border_color(cx))
2609 .overflow_hidden()
2610 .child(
2611 Button::new(button_id, label)
2612 .label_size(LabelSize::Small)
2613 .color(Color::Muted)
2614 .truncate(true)
2615 .when(is_file.is_none(), |this| {
2616 this.icon(IconName::ArrowUpRight)
2617 .icon_size(IconSize::XSmall)
2618 .icon_color(Color::Muted)
2619 })
2620 .on_click(cx.listener({
2621 let workspace = self.workspace.clone();
2622 move |_, _, window, cx: &mut Context<Self>| {
2623 Self::open_link(uri.clone(), &workspace, window, cx);
2624 }
2625 })),
2626 )
2627 .into_any_element()
2628 }
2629
2630 fn render_permission_buttons(
2631 &self,
2632 kind: acp::ToolKind,
2633 options: &[acp::PermissionOption],
2634 entry_ix: usize,
2635 tool_call_id: acp::ToolCallId,
2636 window: &Window,
2637 cx: &Context<Self>,
2638 ) -> Div {
2639 let is_first = self.thread().is_some_and(|thread| {
2640 thread
2641 .read(cx)
2642 .first_tool_awaiting_confirmation()
2643 .is_some_and(|call| call.id == tool_call_id)
2644 });
2645 let mut seen_kinds: ArrayVec<acp::PermissionOptionKind, 3> = ArrayVec::new();
2646
2647 div()
2648 .p_1()
2649 .border_t_1()
2650 .border_color(self.tool_card_border_color(cx))
2651 .w_full()
2652 .map(|this| {
2653 if kind == acp::ToolKind::SwitchMode {
2654 this.v_flex()
2655 } else {
2656 this.h_flex().justify_end().flex_wrap()
2657 }
2658 })
2659 .gap_0p5()
2660 .children(options.iter().map(move |option| {
2661 let option_id = SharedString::from(option.id.0.clone());
2662 Button::new((option_id, entry_ix), option.name.clone())
2663 .map(|this| {
2664 let (this, action) = match option.kind {
2665 acp::PermissionOptionKind::AllowOnce => (
2666 this.icon(IconName::Check).icon_color(Color::Success),
2667 Some(&AllowOnce as &dyn Action),
2668 ),
2669 acp::PermissionOptionKind::AllowAlways => (
2670 this.icon(IconName::CheckDouble).icon_color(Color::Success),
2671 Some(&AllowAlways as &dyn Action),
2672 ),
2673 acp::PermissionOptionKind::RejectOnce => (
2674 this.icon(IconName::Close).icon_color(Color::Error),
2675 Some(&RejectOnce as &dyn Action),
2676 ),
2677 acp::PermissionOptionKind::RejectAlways => {
2678 (this.icon(IconName::Close).icon_color(Color::Error), None)
2679 }
2680 };
2681
2682 let Some(action) = action else {
2683 return this;
2684 };
2685
2686 if !is_first || seen_kinds.contains(&option.kind) {
2687 return this;
2688 }
2689
2690 seen_kinds.push(option.kind);
2691
2692 this.key_binding(
2693 KeyBinding::for_action_in(action, &self.focus_handle, window, cx)
2694 .map(|kb| kb.size(rems_from_px(10.))),
2695 )
2696 })
2697 .icon_position(IconPosition::Start)
2698 .icon_size(IconSize::XSmall)
2699 .label_size(LabelSize::Small)
2700 .on_click(cx.listener({
2701 let tool_call_id = tool_call_id.clone();
2702 let option_id = option.id.clone();
2703 let option_kind = option.kind;
2704 move |this, _, window, cx| {
2705 this.authorize_tool_call(
2706 tool_call_id.clone(),
2707 option_id.clone(),
2708 option_kind,
2709 window,
2710 cx,
2711 );
2712 }
2713 }))
2714 }))
2715 }
2716
2717 fn render_diff_loading(&self, cx: &Context<Self>) -> AnyElement {
2718 let bar = |n: u64, width_class: &str| {
2719 let bg_color = cx.theme().colors().element_active;
2720 let base = h_flex().h_1().rounded_full();
2721
2722 let modified = match width_class {
2723 "w_4_5" => base.w_3_4(),
2724 "w_1_4" => base.w_1_4(),
2725 "w_2_4" => base.w_2_4(),
2726 "w_3_5" => base.w_3_5(),
2727 "w_2_5" => base.w_2_5(),
2728 _ => base.w_1_2(),
2729 };
2730
2731 modified.with_animation(
2732 ElementId::Integer(n),
2733 Animation::new(Duration::from_secs(2)).repeat(),
2734 move |tab, delta| {
2735 let delta = (delta - 0.15 * n as f32) / 0.7;
2736 let delta = 1.0 - (0.5 - delta).abs() * 2.;
2737 let delta = ease_in_out(delta.clamp(0., 1.));
2738 let delta = 0.1 + 0.9 * delta;
2739
2740 tab.bg(bg_color.opacity(delta))
2741 },
2742 )
2743 };
2744
2745 v_flex()
2746 .p_3()
2747 .gap_1()
2748 .rounded_b_md()
2749 .bg(cx.theme().colors().editor_background)
2750 .child(bar(0, "w_4_5"))
2751 .child(bar(1, "w_1_4"))
2752 .child(bar(2, "w_2_4"))
2753 .child(bar(3, "w_3_5"))
2754 .child(bar(4, "w_2_5"))
2755 .into_any_element()
2756 }
2757
2758 fn render_diff_editor(
2759 &self,
2760 entry_ix: usize,
2761 diff: &Entity<acp_thread::Diff>,
2762 tool_call: &ToolCall,
2763 cx: &Context<Self>,
2764 ) -> AnyElement {
2765 let tool_progress = matches!(
2766 &tool_call.status,
2767 ToolCallStatus::InProgress | ToolCallStatus::Pending
2768 );
2769
2770 v_flex()
2771 .h_full()
2772 .border_t_1()
2773 .border_color(self.tool_card_border_color(cx))
2774 .child(
2775 if let Some(entry) = self.entry_view_state.read(cx).entry(entry_ix)
2776 && let Some(editor) = entry.editor_for_diff(diff)
2777 && diff.read(cx).has_revealed_range(cx)
2778 {
2779 editor.into_any_element()
2780 } else if tool_progress && self.as_native_connection(cx).is_some() {
2781 self.render_diff_loading(cx)
2782 } else {
2783 Empty.into_any()
2784 },
2785 )
2786 .into_any()
2787 }
2788
2789 fn render_terminal_tool_call(
2790 &self,
2791 entry_ix: usize,
2792 terminal: &Entity<acp_thread::Terminal>,
2793 tool_call: &ToolCall,
2794 window: &Window,
2795 cx: &Context<Self>,
2796 ) -> AnyElement {
2797 let terminal_data = terminal.read(cx);
2798 let working_dir = terminal_data.working_dir();
2799 let command = terminal_data.command();
2800 let started_at = terminal_data.started_at();
2801
2802 let tool_failed = matches!(
2803 &tool_call.status,
2804 ToolCallStatus::Rejected | ToolCallStatus::Canceled | ToolCallStatus::Failed
2805 );
2806
2807 let output = terminal_data.output();
2808 let command_finished = output.is_some();
2809 let truncated_output =
2810 output.is_some_and(|output| output.original_content_len > output.content.len());
2811 let output_line_count = output.map(|output| output.content_line_count).unwrap_or(0);
2812
2813 let command_failed = command_finished
2814 && output.is_some_and(|o| o.exit_status.is_some_and(|status| !status.success()));
2815
2816 let time_elapsed = if let Some(output) = output {
2817 output.ended_at.duration_since(started_at)
2818 } else {
2819 started_at.elapsed()
2820 };
2821
2822 let header_id =
2823 SharedString::from(format!("terminal-tool-header-{}", terminal.entity_id()));
2824 let header_group = SharedString::from(format!(
2825 "terminal-tool-header-group-{}",
2826 terminal.entity_id()
2827 ));
2828 let header_bg = cx
2829 .theme()
2830 .colors()
2831 .element_background
2832 .blend(cx.theme().colors().editor_foreground.opacity(0.025));
2833 let border_color = cx.theme().colors().border.opacity(0.6);
2834
2835 let working_dir = working_dir
2836 .as_ref()
2837 .map(|path| path.display().to_string())
2838 .unwrap_or_else(|| "current directory".to_string());
2839
2840 let is_expanded = self.expanded_tool_calls.contains(&tool_call.id);
2841
2842 let header = h_flex()
2843 .id(header_id)
2844 .flex_none()
2845 .gap_1()
2846 .justify_between()
2847 .rounded_t_md()
2848 .child(
2849 div()
2850 .id(("command-target-path", terminal.entity_id()))
2851 .w_full()
2852 .max_w_full()
2853 .overflow_x_scroll()
2854 .child(
2855 Label::new(working_dir)
2856 .buffer_font(cx)
2857 .size(LabelSize::XSmall)
2858 .color(Color::Muted),
2859 ),
2860 )
2861 .when(!command_finished, |header| {
2862 header
2863 .gap_1p5()
2864 .child(
2865 Button::new(
2866 SharedString::from(format!("stop-terminal-{}", terminal.entity_id())),
2867 "Stop",
2868 )
2869 .icon(IconName::Stop)
2870 .icon_position(IconPosition::Start)
2871 .icon_size(IconSize::Small)
2872 .icon_color(Color::Error)
2873 .label_size(LabelSize::Small)
2874 .tooltip(move |window, cx| {
2875 Tooltip::with_meta(
2876 "Stop This Command",
2877 None,
2878 "Also possible by placing your cursor inside the terminal and using regular terminal bindings.",
2879 window,
2880 cx,
2881 )
2882 })
2883 .on_click({
2884 let terminal = terminal.clone();
2885 cx.listener(move |_this, _event, _window, cx| {
2886 let inner_terminal = terminal.read(cx).inner().clone();
2887 inner_terminal.update(cx, |inner_terminal, _cx| {
2888 inner_terminal.kill_active_task();
2889 });
2890 })
2891 }),
2892 )
2893 .child(Divider::vertical())
2894 .child(
2895 Icon::new(IconName::ArrowCircle)
2896 .size(IconSize::XSmall)
2897 .color(Color::Info)
2898 .with_rotate_animation(2)
2899 )
2900 })
2901 .when(truncated_output, |header| {
2902 let tooltip = if let Some(output) = output {
2903 if output_line_count + 10 > terminal::MAX_SCROLL_HISTORY_LINES {
2904 format!("Output exceeded terminal max lines and was \
2905 truncated, the model received the first {}.", format_file_size(output.content.len() as u64, true))
2906 } else {
2907 format!(
2908 "Output is {} long, and to avoid unexpected token usage, \
2909 only {} was sent back to the agent.",
2910 format_file_size(output.original_content_len as u64, true),
2911 format_file_size(output.content.len() as u64, true)
2912 )
2913 }
2914 } else {
2915 "Output was truncated".to_string()
2916 };
2917
2918 header.child(
2919 h_flex()
2920 .id(("terminal-tool-truncated-label", terminal.entity_id()))
2921 .gap_1()
2922 .child(
2923 Icon::new(IconName::Info)
2924 .size(IconSize::XSmall)
2925 .color(Color::Ignored),
2926 )
2927 .child(
2928 Label::new("Truncated")
2929 .color(Color::Muted)
2930 .size(LabelSize::XSmall),
2931 )
2932 .tooltip(Tooltip::text(tooltip)),
2933 )
2934 })
2935 .when(time_elapsed > Duration::from_secs(10), |header| {
2936 header.child(
2937 Label::new(format!("({})", duration_alt_display(time_elapsed)))
2938 .buffer_font(cx)
2939 .color(Color::Muted)
2940 .size(LabelSize::XSmall),
2941 )
2942 })
2943 .when(tool_failed || command_failed, |header| {
2944 header.child(
2945 div()
2946 .id(("terminal-tool-error-code-indicator", terminal.entity_id()))
2947 .child(
2948 Icon::new(IconName::Close)
2949 .size(IconSize::Small)
2950 .color(Color::Error),
2951 )
2952 .when_some(output.and_then(|o| o.exit_status), |this, status| {
2953 this.tooltip(Tooltip::text(format!(
2954 "Exited with code {}",
2955 status.code().unwrap_or(-1),
2956 )))
2957 }),
2958 )
2959 })
2960 .child(
2961 Disclosure::new(
2962 SharedString::from(format!(
2963 "terminal-tool-disclosure-{}",
2964 terminal.entity_id()
2965 )),
2966 is_expanded,
2967 )
2968 .opened_icon(IconName::ChevronUp)
2969 .closed_icon(IconName::ChevronDown)
2970 .visible_on_hover(&header_group)
2971 .on_click(cx.listener({
2972 let id = tool_call.id.clone();
2973 move |this, _event, _window, _cx| {
2974 if is_expanded {
2975 this.expanded_tool_calls.remove(&id);
2976 } else {
2977 this.expanded_tool_calls.insert(id.clone());
2978 }
2979 }
2980 })),
2981 );
2982
2983 let terminal_view = self
2984 .entry_view_state
2985 .read(cx)
2986 .entry(entry_ix)
2987 .and_then(|entry| entry.terminal(terminal));
2988 let show_output = is_expanded && terminal_view.is_some();
2989
2990 v_flex()
2991 .my_1p5()
2992 .mx_5()
2993 .border_1()
2994 .when(tool_failed || command_failed, |card| card.border_dashed())
2995 .border_color(border_color)
2996 .rounded_md()
2997 .overflow_hidden()
2998 .child(
2999 v_flex()
3000 .group(&header_group)
3001 .py_1p5()
3002 .pr_1p5()
3003 .pl_2()
3004 .gap_0p5()
3005 .bg(header_bg)
3006 .text_xs()
3007 .child(header)
3008 .child(
3009 MarkdownElement::new(
3010 command.clone(),
3011 terminal_command_markdown_style(window, cx),
3012 )
3013 .code_block_renderer(
3014 markdown::CodeBlockRenderer::Default {
3015 copy_button: false,
3016 copy_button_on_hover: true,
3017 border: false,
3018 },
3019 ),
3020 ),
3021 )
3022 .when(show_output, |this| {
3023 this.child(
3024 div()
3025 .pt_2()
3026 .border_t_1()
3027 .when(tool_failed || command_failed, |card| card.border_dashed())
3028 .border_color(border_color)
3029 .bg(cx.theme().colors().editor_background)
3030 .rounded_b_md()
3031 .text_ui_sm(cx)
3032 .h_full()
3033 .children(terminal_view.map(|terminal_view| {
3034 if terminal_view
3035 .read(cx)
3036 .content_mode(window, cx)
3037 .is_scrollable()
3038 {
3039 div().h_72().child(terminal_view).into_any_element()
3040 } else {
3041 terminal_view.into_any_element()
3042 }
3043 })),
3044 )
3045 })
3046 .into_any()
3047 }
3048
3049 fn render_rules_item(&self, cx: &Context<Self>) -> Option<AnyElement> {
3050 let project_context = self
3051 .as_native_thread(cx)?
3052 .read(cx)
3053 .project_context()
3054 .read(cx);
3055
3056 let user_rules_text = if project_context.user_rules.is_empty() {
3057 None
3058 } else if project_context.user_rules.len() == 1 {
3059 let user_rules = &project_context.user_rules[0];
3060
3061 match user_rules.title.as_ref() {
3062 Some(title) => Some(format!("Using \"{title}\" user rule")),
3063 None => Some("Using user rule".into()),
3064 }
3065 } else {
3066 Some(format!(
3067 "Using {} user rules",
3068 project_context.user_rules.len()
3069 ))
3070 };
3071
3072 let first_user_rules_id = project_context
3073 .user_rules
3074 .first()
3075 .map(|user_rules| user_rules.uuid.0);
3076
3077 let rules_files = project_context
3078 .worktrees
3079 .iter()
3080 .filter_map(|worktree| worktree.rules_file.as_ref())
3081 .collect::<Vec<_>>();
3082
3083 let rules_file_text = match rules_files.as_slice() {
3084 &[] => None,
3085 &[rules_file] => Some(format!(
3086 "Using project {:?} file",
3087 rules_file.path_in_worktree
3088 )),
3089 rules_files => Some(format!("Using {} project rules files", rules_files.len())),
3090 };
3091
3092 if user_rules_text.is_none() && rules_file_text.is_none() {
3093 return None;
3094 }
3095
3096 let has_both = user_rules_text.is_some() && rules_file_text.is_some();
3097
3098 Some(
3099 h_flex()
3100 .px_2p5()
3101 .child(
3102 Icon::new(IconName::Attach)
3103 .size(IconSize::XSmall)
3104 .color(Color::Disabled),
3105 )
3106 .when_some(user_rules_text, |parent, user_rules_text| {
3107 parent.child(
3108 h_flex()
3109 .id("user-rules")
3110 .ml_1()
3111 .mr_1p5()
3112 .child(
3113 Label::new(user_rules_text)
3114 .size(LabelSize::XSmall)
3115 .color(Color::Muted)
3116 .truncate(),
3117 )
3118 .hover(|s| s.bg(cx.theme().colors().element_hover))
3119 .tooltip(Tooltip::text("View User Rules"))
3120 .on_click(move |_event, window, cx| {
3121 window.dispatch_action(
3122 Box::new(OpenRulesLibrary {
3123 prompt_to_select: first_user_rules_id,
3124 }),
3125 cx,
3126 )
3127 }),
3128 )
3129 })
3130 .when(has_both, |this| {
3131 this.child(
3132 Label::new("•")
3133 .size(LabelSize::XSmall)
3134 .color(Color::Disabled),
3135 )
3136 })
3137 .when_some(rules_file_text, |parent, rules_file_text| {
3138 parent.child(
3139 h_flex()
3140 .id("project-rules")
3141 .ml_1p5()
3142 .child(
3143 Label::new(rules_file_text)
3144 .size(LabelSize::XSmall)
3145 .color(Color::Muted),
3146 )
3147 .hover(|s| s.bg(cx.theme().colors().element_hover))
3148 .tooltip(Tooltip::text("View Project Rules"))
3149 .on_click(cx.listener(Self::handle_open_rules)),
3150 )
3151 })
3152 .into_any(),
3153 )
3154 }
3155
3156 fn render_empty_state_section_header(
3157 &self,
3158 label: impl Into<SharedString>,
3159 action_slot: Option<AnyElement>,
3160 cx: &mut Context<Self>,
3161 ) -> impl IntoElement {
3162 div().pl_1().pr_1p5().child(
3163 h_flex()
3164 .mt_2()
3165 .pl_1p5()
3166 .pb_1()
3167 .w_full()
3168 .justify_between()
3169 .border_b_1()
3170 .border_color(cx.theme().colors().border_variant)
3171 .child(
3172 Label::new(label.into())
3173 .size(LabelSize::Small)
3174 .color(Color::Muted),
3175 )
3176 .children(action_slot),
3177 )
3178 }
3179
3180 fn render_recent_history(&self, window: &mut Window, cx: &mut Context<Self>) -> AnyElement {
3181 let render_history = self
3182 .agent
3183 .clone()
3184 .downcast::<agent::NativeAgentServer>()
3185 .is_some()
3186 && self
3187 .history_store
3188 .update(cx, |history_store, cx| !history_store.is_empty(cx));
3189
3190 v_flex()
3191 .size_full()
3192 .when(render_history, |this| {
3193 let recent_history: Vec<_> = self.history_store.update(cx, |history_store, _| {
3194 history_store.entries().take(3).collect()
3195 });
3196 this.justify_end().child(
3197 v_flex()
3198 .child(
3199 self.render_empty_state_section_header(
3200 "Recent",
3201 Some(
3202 Button::new("view-history", "View All")
3203 .style(ButtonStyle::Subtle)
3204 .label_size(LabelSize::Small)
3205 .key_binding(
3206 KeyBinding::for_action_in(
3207 &OpenHistory,
3208 &self.focus_handle(cx),
3209 window,
3210 cx,
3211 )
3212 .map(|kb| kb.size(rems_from_px(12.))),
3213 )
3214 .on_click(move |_event, window, cx| {
3215 window.dispatch_action(OpenHistory.boxed_clone(), cx);
3216 })
3217 .into_any_element(),
3218 ),
3219 cx,
3220 ),
3221 )
3222 .child(
3223 v_flex().p_1().pr_1p5().gap_1().children(
3224 recent_history
3225 .into_iter()
3226 .enumerate()
3227 .map(|(index, entry)| {
3228 // TODO: Add keyboard navigation.
3229 let is_hovered =
3230 self.hovered_recent_history_item == Some(index);
3231 crate::acp::thread_history::AcpHistoryEntryElement::new(
3232 entry,
3233 cx.entity().downgrade(),
3234 )
3235 .hovered(is_hovered)
3236 .on_hover(cx.listener(
3237 move |this, is_hovered, _window, cx| {
3238 if *is_hovered {
3239 this.hovered_recent_history_item = Some(index);
3240 } else if this.hovered_recent_history_item
3241 == Some(index)
3242 {
3243 this.hovered_recent_history_item = None;
3244 }
3245 cx.notify();
3246 },
3247 ))
3248 .into_any_element()
3249 }),
3250 ),
3251 ),
3252 )
3253 })
3254 .into_any()
3255 }
3256
3257 fn render_auth_required_state(
3258 &self,
3259 connection: &Rc<dyn AgentConnection>,
3260 description: Option<&Entity<Markdown>>,
3261 configuration_view: Option<&AnyView>,
3262 pending_auth_method: Option<&acp::AuthMethodId>,
3263 window: &mut Window,
3264 cx: &Context<Self>,
3265 ) -> Div {
3266 let show_description =
3267 configuration_view.is_none() && description.is_none() && pending_auth_method.is_none();
3268
3269 let auth_methods = connection.auth_methods();
3270
3271 v_flex().flex_1().size_full().justify_end().child(
3272 v_flex()
3273 .p_2()
3274 .pr_3()
3275 .w_full()
3276 .gap_1()
3277 .border_t_1()
3278 .border_color(cx.theme().colors().border)
3279 .bg(cx.theme().status().warning.opacity(0.04))
3280 .child(
3281 h_flex()
3282 .gap_1p5()
3283 .child(
3284 Icon::new(IconName::Warning)
3285 .color(Color::Warning)
3286 .size(IconSize::Small),
3287 )
3288 .child(Label::new("Authentication Required").size(LabelSize::Small)),
3289 )
3290 .children(description.map(|desc| {
3291 div().text_ui(cx).child(self.render_markdown(
3292 desc.clone(),
3293 default_markdown_style(false, false, window, cx),
3294 ))
3295 }))
3296 .children(
3297 configuration_view
3298 .cloned()
3299 .map(|view| div().w_full().child(view)),
3300 )
3301 .when(show_description, |el| {
3302 el.child(
3303 Label::new(format!(
3304 "You are not currently authenticated with {}.{}",
3305 self.agent.name(),
3306 if auth_methods.len() > 1 {
3307 " Please choose one of the following options:"
3308 } else {
3309 ""
3310 }
3311 ))
3312 .size(LabelSize::Small)
3313 .color(Color::Muted)
3314 .mb_1()
3315 .ml_5(),
3316 )
3317 })
3318 .when_some(pending_auth_method, |el, _| {
3319 el.child(
3320 h_flex()
3321 .py_4()
3322 .w_full()
3323 .justify_center()
3324 .gap_1()
3325 .child(
3326 Icon::new(IconName::ArrowCircle)
3327 .size(IconSize::Small)
3328 .color(Color::Muted)
3329 .with_rotate_animation(2),
3330 )
3331 .child(Label::new("Authenticating…").size(LabelSize::Small)),
3332 )
3333 })
3334 .when(!auth_methods.is_empty(), |this| {
3335 this.child(
3336 h_flex()
3337 .justify_end()
3338 .flex_wrap()
3339 .gap_1()
3340 .when(!show_description, |this| {
3341 this.border_t_1()
3342 .mt_1()
3343 .pt_2()
3344 .border_color(cx.theme().colors().border.opacity(0.8))
3345 })
3346 .children(connection.auth_methods().iter().enumerate().rev().map(
3347 |(ix, method)| {
3348 let method_id = method.id.clone();
3349 let method_id_str = method.id.0.to_string();
3350 Button::new(
3351 SharedString::from(method.id.0.clone()),
3352 method.name.clone(),
3353 )
3354 .label_size(LabelSize::Small)
3355 .map(|this| {
3356 if ix == 0 {
3357 this.style(ButtonStyle::Tinted(TintColor::Warning))
3358 } else {
3359 this.style(ButtonStyle::Outlined)
3360 }
3361 })
3362 .when_some(method.description.clone(), |this, description| {
3363 this.tooltip(Tooltip::text(description))
3364 })
3365 .on_click({
3366 cx.listener(move |this, _, window, cx| {
3367 telemetry::event!(
3368 "Authenticate Agent Started",
3369 agent = this.agent.telemetry_id(),
3370 method = method_id_str
3371 );
3372
3373 this.authenticate(method_id.clone(), window, cx)
3374 })
3375 })
3376 },
3377 )),
3378 )
3379 }),
3380 )
3381 }
3382
3383 fn render_load_error(
3384 &self,
3385 e: &LoadError,
3386 window: &mut Window,
3387 cx: &mut Context<Self>,
3388 ) -> AnyElement {
3389 let (title, message, action_slot): (_, SharedString, _) = match e {
3390 LoadError::Unsupported {
3391 command: path,
3392 current_version,
3393 minimum_version,
3394 } => {
3395 return self.render_unsupported(path, current_version, minimum_version, window, cx);
3396 }
3397 LoadError::FailedToInstall(msg) => (
3398 "Failed to Install",
3399 msg.into(),
3400 Some(self.create_copy_button(msg.to_string()).into_any_element()),
3401 ),
3402 LoadError::Exited { status } => (
3403 "Failed to Launch",
3404 format!("Server exited with status {status}").into(),
3405 None,
3406 ),
3407 LoadError::Other(msg) => (
3408 "Failed to Launch",
3409 msg.into(),
3410 Some(self.create_copy_button(msg.to_string()).into_any_element()),
3411 ),
3412 };
3413
3414 Callout::new()
3415 .severity(Severity::Error)
3416 .icon(IconName::XCircleFilled)
3417 .title(title)
3418 .description(message)
3419 .actions_slot(div().children(action_slot))
3420 .into_any_element()
3421 }
3422
3423 fn render_unsupported(
3424 &self,
3425 path: &SharedString,
3426 version: &SharedString,
3427 minimum_version: &SharedString,
3428 _window: &mut Window,
3429 cx: &mut Context<Self>,
3430 ) -> AnyElement {
3431 let (heading_label, description_label) = (
3432 format!("Upgrade {} to work with Zed", self.agent.name()),
3433 if version.is_empty() {
3434 format!(
3435 "Currently using {}, which does not report a valid --version",
3436 path,
3437 )
3438 } else {
3439 format!(
3440 "Currently using {}, which is only version {} (need at least {minimum_version})",
3441 path, version
3442 )
3443 },
3444 );
3445
3446 v_flex()
3447 .w_full()
3448 .p_3p5()
3449 .gap_2p5()
3450 .border_t_1()
3451 .border_color(cx.theme().colors().border)
3452 .bg(linear_gradient(
3453 180.,
3454 linear_color_stop(cx.theme().colors().editor_background.opacity(0.4), 4.),
3455 linear_color_stop(cx.theme().status().info_background.opacity(0.), 0.),
3456 ))
3457 .child(
3458 v_flex().gap_0p5().child(Label::new(heading_label)).child(
3459 Label::new(description_label)
3460 .size(LabelSize::Small)
3461 .color(Color::Muted),
3462 ),
3463 )
3464 .into_any_element()
3465 }
3466
3467 fn activity_bar_bg(&self, cx: &Context<Self>) -> Hsla {
3468 let editor_bg_color = cx.theme().colors().editor_background;
3469 let active_color = cx.theme().colors().element_selected;
3470 editor_bg_color.blend(active_color.opacity(0.3))
3471 }
3472
3473 fn render_activity_bar(
3474 &self,
3475 thread_entity: &Entity<AcpThread>,
3476 window: &mut Window,
3477 cx: &Context<Self>,
3478 ) -> Option<AnyElement> {
3479 let thread = thread_entity.read(cx);
3480 let action_log = thread.action_log();
3481 let changed_buffers = action_log.read(cx).changed_buffers(cx);
3482 let plan = thread.plan();
3483
3484 if changed_buffers.is_empty() && plan.is_empty() {
3485 return None;
3486 }
3487
3488 // Temporarily always enable ACP edit controls. This is temporary, to lessen the
3489 // impact of a nasty bug that causes them to sometimes be disabled when they shouldn't
3490 // be, which blocks you from being able to accept or reject edits. This switches the
3491 // bug to be that sometimes it's enabled when it shouldn't be, which at least doesn't
3492 // block you from using the panel.
3493 let pending_edits = false;
3494
3495 v_flex()
3496 .mt_1()
3497 .mx_2()
3498 .bg(self.activity_bar_bg(cx))
3499 .border_1()
3500 .border_b_0()
3501 .border_color(cx.theme().colors().border)
3502 .rounded_t_md()
3503 .shadow(vec![gpui::BoxShadow {
3504 color: gpui::black().opacity(0.15),
3505 offset: point(px(1.), px(-1.)),
3506 blur_radius: px(3.),
3507 spread_radius: px(0.),
3508 }])
3509 .when(!plan.is_empty(), |this| {
3510 this.child(self.render_plan_summary(plan, window, cx))
3511 .when(self.plan_expanded, |parent| {
3512 parent.child(self.render_plan_entries(plan, window, cx))
3513 })
3514 })
3515 .when(!plan.is_empty() && !changed_buffers.is_empty(), |this| {
3516 this.child(Divider::horizontal().color(DividerColor::Border))
3517 })
3518 .when(!changed_buffers.is_empty(), |this| {
3519 this.child(self.render_edits_summary(
3520 &changed_buffers,
3521 self.edits_expanded,
3522 pending_edits,
3523 window,
3524 cx,
3525 ))
3526 .when(self.edits_expanded, |parent| {
3527 parent.child(self.render_edited_files(
3528 action_log,
3529 &changed_buffers,
3530 pending_edits,
3531 cx,
3532 ))
3533 })
3534 })
3535 .into_any()
3536 .into()
3537 }
3538
3539 fn render_plan_summary(
3540 &self,
3541 plan: &Plan,
3542 window: &mut Window,
3543 cx: &Context<Self>,
3544 ) -> impl IntoElement {
3545 let stats = plan.stats();
3546
3547 let title = if let Some(entry) = stats.in_progress_entry
3548 && !self.plan_expanded
3549 {
3550 h_flex()
3551 .cursor_default()
3552 .relative()
3553 .w_full()
3554 .gap_1()
3555 .truncate()
3556 .child(
3557 Label::new("Current:")
3558 .size(LabelSize::Small)
3559 .color(Color::Muted),
3560 )
3561 .child(
3562 div()
3563 .text_xs()
3564 .text_color(cx.theme().colors().text_muted)
3565 .line_clamp(1)
3566 .child(MarkdownElement::new(
3567 entry.content.clone(),
3568 plan_label_markdown_style(&entry.status, window, cx),
3569 )),
3570 )
3571 .when(stats.pending > 0, |this| {
3572 this.child(
3573 h_flex()
3574 .absolute()
3575 .top_0()
3576 .right_0()
3577 .h_full()
3578 .child(div().min_w_8().h_full().bg(linear_gradient(
3579 90.,
3580 linear_color_stop(self.activity_bar_bg(cx), 1.),
3581 linear_color_stop(self.activity_bar_bg(cx).opacity(0.2), 0.),
3582 )))
3583 .child(
3584 div().pr_0p5().bg(self.activity_bar_bg(cx)).child(
3585 Label::new(format!("{} left", stats.pending))
3586 .size(LabelSize::Small)
3587 .color(Color::Muted),
3588 ),
3589 ),
3590 )
3591 })
3592 } else {
3593 let status_label = if stats.pending == 0 {
3594 "All Done".to_string()
3595 } else if stats.completed == 0 {
3596 format!("{} Tasks", plan.entries.len())
3597 } else {
3598 format!("{}/{}", stats.completed, plan.entries.len())
3599 };
3600
3601 h_flex()
3602 .w_full()
3603 .gap_1()
3604 .justify_between()
3605 .child(
3606 Label::new("Plan")
3607 .size(LabelSize::Small)
3608 .color(Color::Muted),
3609 )
3610 .child(
3611 Label::new(status_label)
3612 .size(LabelSize::Small)
3613 .color(Color::Muted)
3614 .mr_1(),
3615 )
3616 };
3617
3618 h_flex()
3619 .id("plan_summary")
3620 .p_1()
3621 .w_full()
3622 .gap_1()
3623 .when(self.plan_expanded, |this| {
3624 this.border_b_1().border_color(cx.theme().colors().border)
3625 })
3626 .child(Disclosure::new("plan_disclosure", self.plan_expanded))
3627 .child(title)
3628 .on_click(cx.listener(|this, _, _, cx| {
3629 this.plan_expanded = !this.plan_expanded;
3630 cx.notify();
3631 }))
3632 }
3633
3634 fn render_plan_entries(&self, plan: &Plan, window: &mut Window, cx: &Context<Self>) -> Div {
3635 v_flex().children(plan.entries.iter().enumerate().flat_map(|(index, entry)| {
3636 let element = h_flex()
3637 .py_1()
3638 .px_2()
3639 .gap_2()
3640 .justify_between()
3641 .bg(cx.theme().colors().editor_background)
3642 .when(index < plan.entries.len() - 1, |parent| {
3643 parent.border_color(cx.theme().colors().border).border_b_1()
3644 })
3645 .child(
3646 h_flex()
3647 .id(("plan_entry", index))
3648 .gap_1p5()
3649 .max_w_full()
3650 .overflow_x_scroll()
3651 .text_xs()
3652 .text_color(cx.theme().colors().text_muted)
3653 .child(match entry.status {
3654 acp::PlanEntryStatus::Pending => Icon::new(IconName::TodoPending)
3655 .size(IconSize::Small)
3656 .color(Color::Muted)
3657 .into_any_element(),
3658 acp::PlanEntryStatus::InProgress => Icon::new(IconName::TodoProgress)
3659 .size(IconSize::Small)
3660 .color(Color::Accent)
3661 .with_rotate_animation(2)
3662 .into_any_element(),
3663 acp::PlanEntryStatus::Completed => Icon::new(IconName::TodoComplete)
3664 .size(IconSize::Small)
3665 .color(Color::Success)
3666 .into_any_element(),
3667 })
3668 .child(MarkdownElement::new(
3669 entry.content.clone(),
3670 plan_label_markdown_style(&entry.status, window, cx),
3671 )),
3672 );
3673
3674 Some(element)
3675 }))
3676 }
3677
3678 fn render_edits_summary(
3679 &self,
3680 changed_buffers: &BTreeMap<Entity<Buffer>, Entity<BufferDiff>>,
3681 expanded: bool,
3682 pending_edits: bool,
3683 window: &mut Window,
3684 cx: &Context<Self>,
3685 ) -> Div {
3686 const EDIT_NOT_READY_TOOLTIP_LABEL: &str = "Wait until file edits are complete.";
3687
3688 let focus_handle = self.focus_handle(cx);
3689
3690 h_flex()
3691 .p_1()
3692 .justify_between()
3693 .flex_wrap()
3694 .when(expanded, |this| {
3695 this.border_b_1().border_color(cx.theme().colors().border)
3696 })
3697 .child(
3698 h_flex()
3699 .id("edits-container")
3700 .gap_1()
3701 .child(Disclosure::new("edits-disclosure", expanded))
3702 .map(|this| {
3703 if pending_edits {
3704 this.child(
3705 Label::new(format!(
3706 "Editing {} {}…",
3707 changed_buffers.len(),
3708 if changed_buffers.len() == 1 {
3709 "file"
3710 } else {
3711 "files"
3712 }
3713 ))
3714 .color(Color::Muted)
3715 .size(LabelSize::Small)
3716 .with_animation(
3717 "edit-label",
3718 Animation::new(Duration::from_secs(2))
3719 .repeat()
3720 .with_easing(pulsating_between(0.3, 0.7)),
3721 |label, delta| label.alpha(delta),
3722 ),
3723 )
3724 } else {
3725 this.child(
3726 Label::new("Edits")
3727 .size(LabelSize::Small)
3728 .color(Color::Muted),
3729 )
3730 .child(Label::new("•").size(LabelSize::XSmall).color(Color::Muted))
3731 .child(
3732 Label::new(format!(
3733 "{} {}",
3734 changed_buffers.len(),
3735 if changed_buffers.len() == 1 {
3736 "file"
3737 } else {
3738 "files"
3739 }
3740 ))
3741 .size(LabelSize::Small)
3742 .color(Color::Muted),
3743 )
3744 }
3745 })
3746 .on_click(cx.listener(|this, _, _, cx| {
3747 this.edits_expanded = !this.edits_expanded;
3748 cx.notify();
3749 })),
3750 )
3751 .child(
3752 h_flex()
3753 .gap_1()
3754 .child(
3755 IconButton::new("review-changes", IconName::ListTodo)
3756 .icon_size(IconSize::Small)
3757 .tooltip({
3758 let focus_handle = focus_handle.clone();
3759 move |window, cx| {
3760 Tooltip::for_action_in(
3761 "Review Changes",
3762 &OpenAgentDiff,
3763 &focus_handle,
3764 window,
3765 cx,
3766 )
3767 }
3768 })
3769 .on_click(cx.listener(|_, _, window, cx| {
3770 window.dispatch_action(OpenAgentDiff.boxed_clone(), cx);
3771 })),
3772 )
3773 .child(Divider::vertical().color(DividerColor::Border))
3774 .child(
3775 Button::new("reject-all-changes", "Reject All")
3776 .label_size(LabelSize::Small)
3777 .disabled(pending_edits)
3778 .when(pending_edits, |this| {
3779 this.tooltip(Tooltip::text(EDIT_NOT_READY_TOOLTIP_LABEL))
3780 })
3781 .key_binding(
3782 KeyBinding::for_action_in(
3783 &RejectAll,
3784 &focus_handle.clone(),
3785 window,
3786 cx,
3787 )
3788 .map(|kb| kb.size(rems_from_px(10.))),
3789 )
3790 .on_click(cx.listener(move |this, _, window, cx| {
3791 this.reject_all(&RejectAll, window, cx);
3792 })),
3793 )
3794 .child(
3795 Button::new("keep-all-changes", "Keep All")
3796 .label_size(LabelSize::Small)
3797 .disabled(pending_edits)
3798 .when(pending_edits, |this| {
3799 this.tooltip(Tooltip::text(EDIT_NOT_READY_TOOLTIP_LABEL))
3800 })
3801 .key_binding(
3802 KeyBinding::for_action_in(&KeepAll, &focus_handle, window, cx)
3803 .map(|kb| kb.size(rems_from_px(10.))),
3804 )
3805 .on_click(cx.listener(move |this, _, window, cx| {
3806 this.keep_all(&KeepAll, window, cx);
3807 })),
3808 ),
3809 )
3810 }
3811
3812 fn render_edited_files(
3813 &self,
3814 action_log: &Entity<ActionLog>,
3815 changed_buffers: &BTreeMap<Entity<Buffer>, Entity<BufferDiff>>,
3816 pending_edits: bool,
3817 cx: &Context<Self>,
3818 ) -> Div {
3819 let editor_bg_color = cx.theme().colors().editor_background;
3820
3821 v_flex().children(changed_buffers.iter().enumerate().flat_map(
3822 |(index, (buffer, _diff))| {
3823 let file = buffer.read(cx).file()?;
3824 let path = file.path();
3825 let path_style = file.path_style(cx);
3826 let separator = file.path_style(cx).separator();
3827
3828 let file_path = path.parent().and_then(|parent| {
3829 if parent.is_empty() {
3830 None
3831 } else {
3832 Some(
3833 Label::new(format!("{}{separator}", parent.display(path_style)))
3834 .color(Color::Muted)
3835 .size(LabelSize::XSmall)
3836 .buffer_font(cx),
3837 )
3838 }
3839 });
3840
3841 let file_name = path.file_name().map(|name| {
3842 Label::new(name.to_string())
3843 .size(LabelSize::XSmall)
3844 .buffer_font(cx)
3845 });
3846
3847 let file_icon = FileIcons::get_icon(path.as_std_path(), cx)
3848 .map(Icon::from_path)
3849 .map(|icon| icon.color(Color::Muted).size(IconSize::Small))
3850 .unwrap_or_else(|| {
3851 Icon::new(IconName::File)
3852 .color(Color::Muted)
3853 .size(IconSize::Small)
3854 });
3855
3856 let overlay_gradient = linear_gradient(
3857 90.,
3858 linear_color_stop(editor_bg_color, 1.),
3859 linear_color_stop(editor_bg_color.opacity(0.2), 0.),
3860 );
3861
3862 let element = h_flex()
3863 .group("edited-code")
3864 .id(("file-container", index))
3865 .py_1()
3866 .pl_2()
3867 .pr_1()
3868 .gap_2()
3869 .justify_between()
3870 .bg(editor_bg_color)
3871 .when(index < changed_buffers.len() - 1, |parent| {
3872 parent.border_color(cx.theme().colors().border).border_b_1()
3873 })
3874 .child(
3875 h_flex()
3876 .relative()
3877 .id(("file-name", index))
3878 .pr_8()
3879 .gap_1p5()
3880 .w_full()
3881 .overflow_x_scroll()
3882 .child(file_icon)
3883 .child(h_flex().gap_0p5().children(file_name).children(file_path))
3884 .child(
3885 div()
3886 .absolute()
3887 .h_full()
3888 .w_12()
3889 .top_0()
3890 .bottom_0()
3891 .right_0()
3892 .bg(overlay_gradient),
3893 )
3894 .on_click({
3895 let buffer = buffer.clone();
3896 cx.listener(move |this, _, window, cx| {
3897 this.open_edited_buffer(&buffer, window, cx);
3898 })
3899 }),
3900 )
3901 .child(
3902 h_flex()
3903 .gap_1()
3904 .visible_on_hover("edited-code")
3905 .child(
3906 Button::new("review", "Review")
3907 .label_size(LabelSize::Small)
3908 .on_click({
3909 let buffer = buffer.clone();
3910 cx.listener(move |this, _, window, cx| {
3911 this.open_edited_buffer(&buffer, window, cx);
3912 })
3913 }),
3914 )
3915 .child(Divider::vertical().color(DividerColor::BorderVariant))
3916 .child(
3917 Button::new("reject-file", "Reject")
3918 .label_size(LabelSize::Small)
3919 .disabled(pending_edits)
3920 .on_click({
3921 let buffer = buffer.clone();
3922 let action_log = action_log.clone();
3923 move |_, _, cx| {
3924 action_log.update(cx, |action_log, cx| {
3925 action_log
3926 .reject_edits_in_ranges(
3927 buffer.clone(),
3928 vec![Anchor::MIN..Anchor::MAX],
3929 cx,
3930 )
3931 .detach_and_log_err(cx);
3932 })
3933 }
3934 }),
3935 )
3936 .child(
3937 Button::new("keep-file", "Keep")
3938 .label_size(LabelSize::Small)
3939 .disabled(pending_edits)
3940 .on_click({
3941 let buffer = buffer.clone();
3942 let action_log = action_log.clone();
3943 move |_, _, cx| {
3944 action_log.update(cx, |action_log, cx| {
3945 action_log.keep_edits_in_range(
3946 buffer.clone(),
3947 Anchor::MIN..Anchor::MAX,
3948 cx,
3949 );
3950 })
3951 }
3952 }),
3953 ),
3954 );
3955
3956 Some(element)
3957 },
3958 ))
3959 }
3960
3961 fn render_message_editor(&mut self, window: &mut Window, cx: &mut Context<Self>) -> AnyElement {
3962 let focus_handle = self.message_editor.focus_handle(cx);
3963 let editor_bg_color = cx.theme().colors().editor_background;
3964 let (expand_icon, expand_tooltip) = if self.editor_expanded {
3965 (IconName::Minimize, "Minimize Message Editor")
3966 } else {
3967 (IconName::Maximize, "Expand Message Editor")
3968 };
3969
3970 let backdrop = div()
3971 .size_full()
3972 .absolute()
3973 .inset_0()
3974 .bg(cx.theme().colors().panel_background)
3975 .opacity(0.8)
3976 .block_mouse_except_scroll();
3977
3978 let enable_editor = match self.thread_state {
3979 ThreadState::Loading { .. } | ThreadState::Ready { .. } => true,
3980 ThreadState::Unauthenticated { .. } | ThreadState::LoadError(..) => false,
3981 };
3982
3983 v_flex()
3984 .on_action(cx.listener(Self::expand_message_editor))
3985 .on_action(cx.listener(|this, _: &ToggleProfileSelector, window, cx| {
3986 if let Some(profile_selector) = this.profile_selector.as_ref() {
3987 profile_selector.read(cx).menu_handle().toggle(window, cx);
3988 } else if let Some(mode_selector) = this.mode_selector() {
3989 mode_selector.read(cx).menu_handle().toggle(window, cx);
3990 }
3991 }))
3992 .on_action(cx.listener(|this, _: &CycleModeSelector, window, cx| {
3993 if let Some(mode_selector) = this.mode_selector() {
3994 mode_selector.update(cx, |mode_selector, cx| {
3995 mode_selector.cycle_mode(window, cx);
3996 });
3997 }
3998 }))
3999 .on_action(cx.listener(|this, _: &ToggleModelSelector, window, cx| {
4000 if let Some(model_selector) = this.model_selector.as_ref() {
4001 model_selector
4002 .update(cx, |model_selector, cx| model_selector.toggle(window, cx));
4003 }
4004 }))
4005 .p_2()
4006 .gap_2()
4007 .border_t_1()
4008 .border_color(cx.theme().colors().border)
4009 .bg(editor_bg_color)
4010 .when(self.editor_expanded, |this| {
4011 this.h(vh(0.8, window)).size_full().justify_between()
4012 })
4013 .child(
4014 v_flex()
4015 .relative()
4016 .size_full()
4017 .pt_1()
4018 .pr_2p5()
4019 .child(self.message_editor.clone())
4020 .child(
4021 h_flex()
4022 .absolute()
4023 .top_0()
4024 .right_0()
4025 .opacity(0.5)
4026 .hover(|this| this.opacity(1.0))
4027 .child(
4028 IconButton::new("toggle-height", expand_icon)
4029 .icon_size(IconSize::Small)
4030 .icon_color(Color::Muted)
4031 .tooltip({
4032 move |window, cx| {
4033 Tooltip::for_action_in(
4034 expand_tooltip,
4035 &ExpandMessageEditor,
4036 &focus_handle,
4037 window,
4038 cx,
4039 )
4040 }
4041 })
4042 .on_click(cx.listener(|_, _, window, cx| {
4043 window.dispatch_action(Box::new(ExpandMessageEditor), cx);
4044 })),
4045 ),
4046 ),
4047 )
4048 .child(
4049 h_flex()
4050 .flex_none()
4051 .flex_wrap()
4052 .justify_between()
4053 .child(
4054 h_flex()
4055 .child(self.render_follow_toggle(cx))
4056 .children(self.render_burn_mode_toggle(cx)),
4057 )
4058 .child(
4059 h_flex()
4060 .gap_1()
4061 .children(self.render_token_usage(cx))
4062 .children(self.profile_selector.clone())
4063 .children(self.mode_selector().cloned())
4064 .children(self.model_selector.clone())
4065 .child(self.render_send_button(cx)),
4066 ),
4067 )
4068 .when(!enable_editor, |this| this.child(backdrop))
4069 .into_any()
4070 }
4071
4072 pub(crate) fn as_native_connection(
4073 &self,
4074 cx: &App,
4075 ) -> Option<Rc<agent::NativeAgentConnection>> {
4076 let acp_thread = self.thread()?.read(cx);
4077 acp_thread.connection().clone().downcast()
4078 }
4079
4080 pub(crate) fn as_native_thread(&self, cx: &App) -> Option<Entity<agent::Thread>> {
4081 let acp_thread = self.thread()?.read(cx);
4082 self.as_native_connection(cx)?
4083 .thread(acp_thread.session_id(), cx)
4084 }
4085
4086 fn is_using_zed_ai_models(&self, cx: &App) -> bool {
4087 self.as_native_thread(cx)
4088 .and_then(|thread| thread.read(cx).model())
4089 .is_some_and(|model| model.provider_id() == language_model::ZED_CLOUD_PROVIDER_ID)
4090 }
4091
4092 fn render_token_usage(&self, cx: &mut Context<Self>) -> Option<Div> {
4093 let thread = self.thread()?.read(cx);
4094 let usage = thread.token_usage()?;
4095 let is_generating = thread.status() != ThreadStatus::Idle;
4096
4097 let used = crate::text_thread_editor::humanize_token_count(usage.used_tokens);
4098 let max = crate::text_thread_editor::humanize_token_count(usage.max_tokens);
4099
4100 Some(
4101 h_flex()
4102 .flex_shrink_0()
4103 .gap_0p5()
4104 .mr_1p5()
4105 .child(
4106 Label::new(used)
4107 .size(LabelSize::Small)
4108 .color(Color::Muted)
4109 .map(|label| {
4110 if is_generating {
4111 label
4112 .with_animation(
4113 "used-tokens-label",
4114 Animation::new(Duration::from_secs(2))
4115 .repeat()
4116 .with_easing(pulsating_between(0.3, 0.8)),
4117 |label, delta| label.alpha(delta),
4118 )
4119 .into_any()
4120 } else {
4121 label.into_any_element()
4122 }
4123 }),
4124 )
4125 .child(
4126 Label::new("/")
4127 .size(LabelSize::Small)
4128 .color(Color::Custom(cx.theme().colors().text_muted.opacity(0.5))),
4129 )
4130 .child(Label::new(max).size(LabelSize::Small).color(Color::Muted)),
4131 )
4132 }
4133
4134 fn toggle_burn_mode(
4135 &mut self,
4136 _: &ToggleBurnMode,
4137 _window: &mut Window,
4138 cx: &mut Context<Self>,
4139 ) {
4140 let Some(thread) = self.as_native_thread(cx) else {
4141 return;
4142 };
4143
4144 thread.update(cx, |thread, cx| {
4145 let current_mode = thread.completion_mode();
4146 thread.set_completion_mode(
4147 match current_mode {
4148 CompletionMode::Burn => CompletionMode::Normal,
4149 CompletionMode::Normal => CompletionMode::Burn,
4150 },
4151 cx,
4152 );
4153 });
4154 }
4155
4156 fn keep_all(&mut self, _: &KeepAll, _window: &mut Window, cx: &mut Context<Self>) {
4157 let Some(thread) = self.thread() else {
4158 return;
4159 };
4160 let action_log = thread.read(cx).action_log().clone();
4161 action_log.update(cx, |action_log, cx| action_log.keep_all_edits(cx));
4162 }
4163
4164 fn reject_all(&mut self, _: &RejectAll, _window: &mut Window, cx: &mut Context<Self>) {
4165 let Some(thread) = self.thread() else {
4166 return;
4167 };
4168 let action_log = thread.read(cx).action_log().clone();
4169 action_log
4170 .update(cx, |action_log, cx| action_log.reject_all_edits(cx))
4171 .detach();
4172 }
4173
4174 fn allow_always(&mut self, _: &AllowAlways, window: &mut Window, cx: &mut Context<Self>) {
4175 self.authorize_pending_tool_call(acp::PermissionOptionKind::AllowAlways, window, cx);
4176 }
4177
4178 fn allow_once(&mut self, _: &AllowOnce, window: &mut Window, cx: &mut Context<Self>) {
4179 self.authorize_pending_tool_call(acp::PermissionOptionKind::AllowOnce, window, cx);
4180 }
4181
4182 fn reject_once(&mut self, _: &RejectOnce, window: &mut Window, cx: &mut Context<Self>) {
4183 self.authorize_pending_tool_call(acp::PermissionOptionKind::RejectOnce, window, cx);
4184 }
4185
4186 fn authorize_pending_tool_call(
4187 &mut self,
4188 kind: acp::PermissionOptionKind,
4189 window: &mut Window,
4190 cx: &mut Context<Self>,
4191 ) -> Option<()> {
4192 let thread = self.thread()?.read(cx);
4193 let tool_call = thread.first_tool_awaiting_confirmation()?;
4194 let ToolCallStatus::WaitingForConfirmation { options, .. } = &tool_call.status else {
4195 return None;
4196 };
4197 let option = options.iter().find(|o| o.kind == kind)?;
4198
4199 self.authorize_tool_call(
4200 tool_call.id.clone(),
4201 option.id.clone(),
4202 option.kind,
4203 window,
4204 cx,
4205 );
4206
4207 Some(())
4208 }
4209
4210 fn render_burn_mode_toggle(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
4211 let thread = self.as_native_thread(cx)?.read(cx);
4212
4213 if thread
4214 .model()
4215 .is_none_or(|model| !model.supports_burn_mode())
4216 {
4217 return None;
4218 }
4219
4220 let active_completion_mode = thread.completion_mode();
4221 let burn_mode_enabled = active_completion_mode == CompletionMode::Burn;
4222 let icon = if burn_mode_enabled {
4223 IconName::ZedBurnModeOn
4224 } else {
4225 IconName::ZedBurnMode
4226 };
4227
4228 Some(
4229 IconButton::new("burn-mode", icon)
4230 .icon_size(IconSize::Small)
4231 .icon_color(Color::Muted)
4232 .toggle_state(burn_mode_enabled)
4233 .selected_icon_color(Color::Error)
4234 .on_click(cx.listener(|this, _event, window, cx| {
4235 this.toggle_burn_mode(&ToggleBurnMode, window, cx);
4236 }))
4237 .tooltip(move |_window, cx| {
4238 cx.new(|_| BurnModeTooltip::new().selected(burn_mode_enabled))
4239 .into()
4240 })
4241 .into_any_element(),
4242 )
4243 }
4244
4245 fn render_send_button(&self, cx: &mut Context<Self>) -> AnyElement {
4246 let is_editor_empty = self.message_editor.read(cx).is_empty(cx);
4247 let is_generating = self
4248 .thread()
4249 .is_some_and(|thread| thread.read(cx).status() != ThreadStatus::Idle);
4250
4251 if self.is_loading_contents {
4252 div()
4253 .id("loading-message-content")
4254 .px_1()
4255 .tooltip(Tooltip::text("Loading Added Context…"))
4256 .child(loading_contents_spinner(IconSize::default()))
4257 .into_any_element()
4258 } else if is_generating && is_editor_empty {
4259 IconButton::new("stop-generation", IconName::Stop)
4260 .icon_color(Color::Error)
4261 .style(ButtonStyle::Tinted(ui::TintColor::Error))
4262 .tooltip(move |window, cx| {
4263 Tooltip::for_action("Stop Generation", &editor::actions::Cancel, window, cx)
4264 })
4265 .on_click(cx.listener(|this, _event, _, cx| this.cancel_generation(cx)))
4266 .into_any_element()
4267 } else {
4268 let send_btn_tooltip = if is_editor_empty && !is_generating {
4269 "Type to Send"
4270 } else if is_generating {
4271 "Stop and Send Message"
4272 } else {
4273 "Send"
4274 };
4275
4276 IconButton::new("send-message", IconName::Send)
4277 .style(ButtonStyle::Filled)
4278 .map(|this| {
4279 if is_editor_empty && !is_generating {
4280 this.disabled(true).icon_color(Color::Muted)
4281 } else {
4282 this.icon_color(Color::Accent)
4283 }
4284 })
4285 .tooltip(move |window, cx| Tooltip::for_action(send_btn_tooltip, &Chat, window, cx))
4286 .on_click(cx.listener(|this, _, window, cx| {
4287 this.send(window, cx);
4288 }))
4289 .into_any_element()
4290 }
4291 }
4292
4293 fn is_following(&self, cx: &App) -> bool {
4294 match self.thread().map(|thread| thread.read(cx).status()) {
4295 Some(ThreadStatus::Generating) => self
4296 .workspace
4297 .read_with(cx, |workspace, _| {
4298 workspace.is_being_followed(CollaboratorId::Agent)
4299 })
4300 .unwrap_or(false),
4301 _ => self.should_be_following,
4302 }
4303 }
4304
4305 fn toggle_following(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4306 let following = self.is_following(cx);
4307
4308 self.should_be_following = !following;
4309 if self.thread().map(|thread| thread.read(cx).status()) == Some(ThreadStatus::Generating) {
4310 self.workspace
4311 .update(cx, |workspace, cx| {
4312 if following {
4313 workspace.unfollow(CollaboratorId::Agent, window, cx);
4314 } else {
4315 workspace.follow(CollaboratorId::Agent, window, cx);
4316 }
4317 })
4318 .ok();
4319 }
4320
4321 telemetry::event!("Follow Agent Selected", following = !following);
4322 }
4323
4324 fn render_follow_toggle(&self, cx: &mut Context<Self>) -> impl IntoElement {
4325 let following = self.is_following(cx);
4326
4327 let tooltip_label = if following {
4328 if self.agent.name() == "Zed Agent" {
4329 format!("Stop Following the {}", self.agent.name())
4330 } else {
4331 format!("Stop Following {}", self.agent.name())
4332 }
4333 } else {
4334 if self.agent.name() == "Zed Agent" {
4335 format!("Follow the {}", self.agent.name())
4336 } else {
4337 format!("Follow {}", self.agent.name())
4338 }
4339 };
4340
4341 IconButton::new("follow-agent", IconName::Crosshair)
4342 .icon_size(IconSize::Small)
4343 .icon_color(Color::Muted)
4344 .toggle_state(following)
4345 .selected_icon_color(Some(Color::Custom(cx.theme().players().agent().cursor)))
4346 .tooltip(move |window, cx| {
4347 if following {
4348 Tooltip::for_action(tooltip_label.clone(), &Follow, window, cx)
4349 } else {
4350 Tooltip::with_meta(
4351 tooltip_label.clone(),
4352 Some(&Follow),
4353 "Track the agent's location as it reads and edits files.",
4354 window,
4355 cx,
4356 )
4357 }
4358 })
4359 .on_click(cx.listener(move |this, _, window, cx| {
4360 this.toggle_following(window, cx);
4361 }))
4362 }
4363
4364 fn render_markdown(&self, markdown: Entity<Markdown>, style: MarkdownStyle) -> MarkdownElement {
4365 let workspace = self.workspace.clone();
4366 MarkdownElement::new(markdown, style).on_url_click(move |text, window, cx| {
4367 Self::open_link(text, &workspace, window, cx);
4368 })
4369 }
4370
4371 fn open_link(
4372 url: SharedString,
4373 workspace: &WeakEntity<Workspace>,
4374 window: &mut Window,
4375 cx: &mut App,
4376 ) {
4377 let Some(workspace) = workspace.upgrade() else {
4378 cx.open_url(&url);
4379 return;
4380 };
4381
4382 if let Some(mention) = MentionUri::parse(&url).log_err() {
4383 workspace.update(cx, |workspace, cx| match mention {
4384 MentionUri::File { abs_path } => {
4385 let project = workspace.project();
4386 let Some(path) =
4387 project.update(cx, |project, cx| project.find_project_path(abs_path, cx))
4388 else {
4389 return;
4390 };
4391
4392 workspace
4393 .open_path(path, None, true, window, cx)
4394 .detach_and_log_err(cx);
4395 }
4396 MentionUri::PastedImage => {}
4397 MentionUri::Directory { abs_path } => {
4398 let project = workspace.project();
4399 let Some(entry_id) = project.update(cx, |project, cx| {
4400 let path = project.find_project_path(abs_path, cx)?;
4401 project.entry_for_path(&path, cx).map(|entry| entry.id)
4402 }) else {
4403 return;
4404 };
4405
4406 project.update(cx, |_, cx| {
4407 cx.emit(project::Event::RevealInProjectPanel(entry_id));
4408 });
4409 }
4410 MentionUri::Symbol {
4411 abs_path: path,
4412 line_range,
4413 ..
4414 }
4415 | MentionUri::Selection {
4416 abs_path: Some(path),
4417 line_range,
4418 } => {
4419 let project = workspace.project();
4420 let Some(path) =
4421 project.update(cx, |project, cx| project.find_project_path(path, cx))
4422 else {
4423 return;
4424 };
4425
4426 let item = workspace.open_path(path, None, true, window, cx);
4427 window
4428 .spawn(cx, async move |cx| {
4429 let Some(editor) = item.await?.downcast::<Editor>() else {
4430 return Ok(());
4431 };
4432 let range = Point::new(*line_range.start(), 0)
4433 ..Point::new(*line_range.start(), 0);
4434 editor
4435 .update_in(cx, |editor, window, cx| {
4436 editor.change_selections(
4437 SelectionEffects::scroll(Autoscroll::center()),
4438 window,
4439 cx,
4440 |s| s.select_ranges(vec![range]),
4441 );
4442 })
4443 .ok();
4444 anyhow::Ok(())
4445 })
4446 .detach_and_log_err(cx);
4447 }
4448 MentionUri::Selection { abs_path: None, .. } => {}
4449 MentionUri::Thread { id, name } => {
4450 if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
4451 panel.update(cx, |panel, cx| {
4452 panel.load_agent_thread(
4453 DbThreadMetadata {
4454 id,
4455 title: name.into(),
4456 updated_at: Default::default(),
4457 },
4458 window,
4459 cx,
4460 )
4461 });
4462 }
4463 }
4464 MentionUri::TextThread { path, .. } => {
4465 if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
4466 panel.update(cx, |panel, cx| {
4467 panel
4468 .open_saved_text_thread(path.as_path().into(), window, cx)
4469 .detach_and_log_err(cx);
4470 });
4471 }
4472 }
4473 MentionUri::Rule { id, .. } => {
4474 let PromptId::User { uuid } = id else {
4475 return;
4476 };
4477 window.dispatch_action(
4478 Box::new(OpenRulesLibrary {
4479 prompt_to_select: Some(uuid.0),
4480 }),
4481 cx,
4482 )
4483 }
4484 MentionUri::Fetch { url } => {
4485 cx.open_url(url.as_str());
4486 }
4487 })
4488 } else {
4489 cx.open_url(&url);
4490 }
4491 }
4492
4493 fn open_tool_call_location(
4494 &self,
4495 entry_ix: usize,
4496 location_ix: usize,
4497 window: &mut Window,
4498 cx: &mut Context<Self>,
4499 ) -> Option<()> {
4500 let (tool_call_location, agent_location) = self
4501 .thread()?
4502 .read(cx)
4503 .entries()
4504 .get(entry_ix)?
4505 .location(location_ix)?;
4506
4507 let project_path = self
4508 .project
4509 .read(cx)
4510 .find_project_path(&tool_call_location.path, cx)?;
4511
4512 let open_task = self
4513 .workspace
4514 .update(cx, |workspace, cx| {
4515 workspace.open_path(project_path, None, true, window, cx)
4516 })
4517 .log_err()?;
4518 window
4519 .spawn(cx, async move |cx| {
4520 let item = open_task.await?;
4521
4522 let Some(active_editor) = item.downcast::<Editor>() else {
4523 return anyhow::Ok(());
4524 };
4525
4526 active_editor.update_in(cx, |editor, window, cx| {
4527 let multibuffer = editor.buffer().read(cx);
4528 let buffer = multibuffer.as_singleton();
4529 if agent_location.buffer.upgrade() == buffer {
4530 let excerpt_id = multibuffer.excerpt_ids().first().cloned();
4531 let anchor = editor::Anchor::in_buffer(
4532 excerpt_id.unwrap(),
4533 buffer.unwrap().read(cx).remote_id(),
4534 agent_location.position,
4535 );
4536 editor.change_selections(Default::default(), window, cx, |selections| {
4537 selections.select_anchor_ranges([anchor..anchor]);
4538 })
4539 } else {
4540 let row = tool_call_location.line.unwrap_or_default();
4541 editor.change_selections(Default::default(), window, cx, |selections| {
4542 selections.select_ranges([Point::new(row, 0)..Point::new(row, 0)]);
4543 })
4544 }
4545 })?;
4546
4547 anyhow::Ok(())
4548 })
4549 .detach_and_log_err(cx);
4550
4551 None
4552 }
4553
4554 pub fn open_thread_as_markdown(
4555 &self,
4556 workspace: Entity<Workspace>,
4557 window: &mut Window,
4558 cx: &mut App,
4559 ) -> Task<Result<()>> {
4560 let markdown_language_task = workspace
4561 .read(cx)
4562 .app_state()
4563 .languages
4564 .language_for_name("Markdown");
4565
4566 let (thread_summary, markdown) = if let Some(thread) = self.thread() {
4567 let thread = thread.read(cx);
4568 (thread.title().to_string(), thread.to_markdown(cx))
4569 } else {
4570 return Task::ready(Ok(()));
4571 };
4572
4573 window.spawn(cx, async move |cx| {
4574 let markdown_language = markdown_language_task.await?;
4575
4576 workspace.update_in(cx, |workspace, window, cx| {
4577 let project = workspace.project().clone();
4578
4579 if !project.read(cx).is_local() {
4580 bail!("failed to open active thread as markdown in remote project");
4581 }
4582
4583 let buffer = project.update(cx, |project, cx| {
4584 project.create_local_buffer(&markdown, Some(markdown_language), true, cx)
4585 });
4586 let buffer = cx.new(|cx| {
4587 MultiBuffer::singleton(buffer, cx).with_title(thread_summary.clone())
4588 });
4589
4590 workspace.add_item_to_active_pane(
4591 Box::new(cx.new(|cx| {
4592 let mut editor =
4593 Editor::for_multibuffer(buffer, Some(project.clone()), window, cx);
4594 editor.set_breadcrumb_header(thread_summary);
4595 editor
4596 })),
4597 None,
4598 true,
4599 window,
4600 cx,
4601 );
4602
4603 anyhow::Ok(())
4604 })??;
4605 anyhow::Ok(())
4606 })
4607 }
4608
4609 fn scroll_to_top(&mut self, cx: &mut Context<Self>) {
4610 self.list_state.scroll_to(ListOffset::default());
4611 cx.notify();
4612 }
4613
4614 pub fn scroll_to_bottom(&mut self, cx: &mut Context<Self>) {
4615 if let Some(thread) = self.thread() {
4616 let entry_count = thread.read(cx).entries().len();
4617 self.list_state.reset(entry_count);
4618 cx.notify();
4619 }
4620 }
4621
4622 fn notify_with_sound(
4623 &mut self,
4624 caption: impl Into<SharedString>,
4625 icon: IconName,
4626 window: &mut Window,
4627 cx: &mut Context<Self>,
4628 ) {
4629 self.play_notification_sound(window, cx);
4630 self.show_notification(caption, icon, window, cx);
4631 }
4632
4633 fn play_notification_sound(&self, window: &Window, cx: &mut App) {
4634 let settings = AgentSettings::get_global(cx);
4635 if settings.play_sound_when_agent_done && !window.is_window_active() {
4636 Audio::play_sound(Sound::AgentDone, cx);
4637 }
4638 }
4639
4640 fn show_notification(
4641 &mut self,
4642 caption: impl Into<SharedString>,
4643 icon: IconName,
4644 window: &mut Window,
4645 cx: &mut Context<Self>,
4646 ) {
4647 if window.is_window_active() || !self.notifications.is_empty() {
4648 return;
4649 }
4650
4651 // TODO: Change this once we have title summarization for external agents.
4652 let title = self.agent.name();
4653
4654 match AgentSettings::get_global(cx).notify_when_agent_waiting {
4655 NotifyWhenAgentWaiting::PrimaryScreen => {
4656 if let Some(primary) = cx.primary_display() {
4657 self.pop_up(icon, caption.into(), title, window, primary, cx);
4658 }
4659 }
4660 NotifyWhenAgentWaiting::AllScreens => {
4661 let caption = caption.into();
4662 for screen in cx.displays() {
4663 self.pop_up(icon, caption.clone(), title.clone(), window, screen, cx);
4664 }
4665 }
4666 NotifyWhenAgentWaiting::Never => {
4667 // Don't show anything
4668 }
4669 }
4670 }
4671
4672 fn pop_up(
4673 &mut self,
4674 icon: IconName,
4675 caption: SharedString,
4676 title: SharedString,
4677 window: &mut Window,
4678 screen: Rc<dyn PlatformDisplay>,
4679 cx: &mut Context<Self>,
4680 ) {
4681 let options = AgentNotification::window_options(screen, cx);
4682
4683 let project_name = self.workspace.upgrade().and_then(|workspace| {
4684 workspace
4685 .read(cx)
4686 .project()
4687 .read(cx)
4688 .visible_worktrees(cx)
4689 .next()
4690 .map(|worktree| worktree.read(cx).root_name_str().to_string())
4691 });
4692
4693 if let Some(screen_window) = cx
4694 .open_window(options, |_, cx| {
4695 cx.new(|_| {
4696 AgentNotification::new(title.clone(), caption.clone(), icon, project_name)
4697 })
4698 })
4699 .log_err()
4700 && let Some(pop_up) = screen_window.entity(cx).log_err()
4701 {
4702 self.notification_subscriptions
4703 .entry(screen_window)
4704 .or_insert_with(Vec::new)
4705 .push(cx.subscribe_in(&pop_up, window, {
4706 |this, _, event, window, cx| match event {
4707 AgentNotificationEvent::Accepted => {
4708 let handle = window.window_handle();
4709 cx.activate(true);
4710
4711 let workspace_handle = this.workspace.clone();
4712
4713 // If there are multiple Zed windows, activate the correct one.
4714 cx.defer(move |cx| {
4715 handle
4716 .update(cx, |_view, window, _cx| {
4717 window.activate_window();
4718
4719 if let Some(workspace) = workspace_handle.upgrade() {
4720 workspace.update(_cx, |workspace, cx| {
4721 workspace.focus_panel::<AgentPanel>(window, cx);
4722 });
4723 }
4724 })
4725 .log_err();
4726 });
4727
4728 this.dismiss_notifications(cx);
4729 }
4730 AgentNotificationEvent::Dismissed => {
4731 this.dismiss_notifications(cx);
4732 }
4733 }
4734 }));
4735
4736 self.notifications.push(screen_window);
4737
4738 // If the user manually refocuses the original window, dismiss the popup.
4739 self.notification_subscriptions
4740 .entry(screen_window)
4741 .or_insert_with(Vec::new)
4742 .push({
4743 let pop_up_weak = pop_up.downgrade();
4744
4745 cx.observe_window_activation(window, move |_, window, cx| {
4746 if window.is_window_active()
4747 && let Some(pop_up) = pop_up_weak.upgrade()
4748 {
4749 pop_up.update(cx, |_, cx| {
4750 cx.emit(AgentNotificationEvent::Dismissed);
4751 });
4752 }
4753 })
4754 });
4755 }
4756 }
4757
4758 fn dismiss_notifications(&mut self, cx: &mut Context<Self>) {
4759 for window in self.notifications.drain(..) {
4760 window
4761 .update(cx, |_, window, _| {
4762 window.remove_window();
4763 })
4764 .ok();
4765
4766 self.notification_subscriptions.remove(&window);
4767 }
4768 }
4769
4770 fn render_thread_controls(
4771 &self,
4772 thread: &Entity<AcpThread>,
4773 cx: &Context<Self>,
4774 ) -> impl IntoElement {
4775 let is_generating = matches!(thread.read(cx).status(), ThreadStatus::Generating);
4776 if is_generating {
4777 return h_flex().id("thread-controls-container").child(
4778 div()
4779 .py_2()
4780 .px(rems_from_px(22.))
4781 .child(SpinnerLabel::new().size(LabelSize::Small)),
4782 );
4783 }
4784
4785 let open_as_markdown = IconButton::new("open-as-markdown", IconName::FileMarkdown)
4786 .shape(ui::IconButtonShape::Square)
4787 .icon_size(IconSize::Small)
4788 .icon_color(Color::Ignored)
4789 .tooltip(Tooltip::text("Open Thread as Markdown"))
4790 .on_click(cx.listener(move |this, _, window, cx| {
4791 if let Some(workspace) = this.workspace.upgrade() {
4792 this.open_thread_as_markdown(workspace, window, cx)
4793 .detach_and_log_err(cx);
4794 }
4795 }));
4796
4797 let scroll_to_top = IconButton::new("scroll_to_top", IconName::ArrowUp)
4798 .shape(ui::IconButtonShape::Square)
4799 .icon_size(IconSize::Small)
4800 .icon_color(Color::Ignored)
4801 .tooltip(Tooltip::text("Scroll To Top"))
4802 .on_click(cx.listener(move |this, _, _, cx| {
4803 this.scroll_to_top(cx);
4804 }));
4805
4806 let mut container = h_flex()
4807 .id("thread-controls-container")
4808 .group("thread-controls-container")
4809 .w_full()
4810 .py_2()
4811 .px_5()
4812 .gap_px()
4813 .opacity(0.6)
4814 .hover(|style| style.opacity(1.))
4815 .flex_wrap()
4816 .justify_end();
4817
4818 if AgentSettings::get_global(cx).enable_feedback
4819 && self
4820 .thread()
4821 .is_some_and(|thread| thread.read(cx).connection().telemetry().is_some())
4822 {
4823 let feedback = self.thread_feedback.feedback;
4824
4825 container = container
4826 .child(
4827 div().visible_on_hover("thread-controls-container").child(
4828 Label::new(match feedback {
4829 Some(ThreadFeedback::Positive) => "Thanks for your feedback!",
4830 Some(ThreadFeedback::Negative) => {
4831 "We appreciate your feedback and will use it to improve."
4832 }
4833 None => {
4834 "Rating the thread sends all of your current conversation to the Zed team."
4835 }
4836 })
4837 .color(Color::Muted)
4838 .size(LabelSize::XSmall)
4839 .truncate(),
4840 ),
4841 )
4842 .child(
4843 IconButton::new("feedback-thumbs-up", IconName::ThumbsUp)
4844 .shape(ui::IconButtonShape::Square)
4845 .icon_size(IconSize::Small)
4846 .icon_color(match feedback {
4847 Some(ThreadFeedback::Positive) => Color::Accent,
4848 _ => Color::Ignored,
4849 })
4850 .tooltip(Tooltip::text("Helpful Response"))
4851 .on_click(cx.listener(move |this, _, window, cx| {
4852 this.handle_feedback_click(ThreadFeedback::Positive, window, cx);
4853 })),
4854 )
4855 .child(
4856 IconButton::new("feedback-thumbs-down", IconName::ThumbsDown)
4857 .shape(ui::IconButtonShape::Square)
4858 .icon_size(IconSize::Small)
4859 .icon_color(match feedback {
4860 Some(ThreadFeedback::Negative) => Color::Accent,
4861 _ => Color::Ignored,
4862 })
4863 .tooltip(Tooltip::text("Not Helpful"))
4864 .on_click(cx.listener(move |this, _, window, cx| {
4865 this.handle_feedback_click(ThreadFeedback::Negative, window, cx);
4866 })),
4867 );
4868 }
4869
4870 container.child(open_as_markdown).child(scroll_to_top)
4871 }
4872
4873 fn render_feedback_feedback_editor(editor: Entity<Editor>, cx: &Context<Self>) -> Div {
4874 h_flex()
4875 .key_context("AgentFeedbackMessageEditor")
4876 .on_action(cx.listener(move |this, _: &menu::Cancel, _, cx| {
4877 this.thread_feedback.dismiss_comments();
4878 cx.notify();
4879 }))
4880 .on_action(cx.listener(move |this, _: &menu::Confirm, _window, cx| {
4881 this.submit_feedback_message(cx);
4882 }))
4883 .p_2()
4884 .mb_2()
4885 .mx_5()
4886 .gap_1()
4887 .rounded_md()
4888 .border_1()
4889 .border_color(cx.theme().colors().border)
4890 .bg(cx.theme().colors().editor_background)
4891 .child(div().w_full().child(editor))
4892 .child(
4893 h_flex()
4894 .child(
4895 IconButton::new("dismiss-feedback-message", IconName::Close)
4896 .icon_color(Color::Error)
4897 .icon_size(IconSize::XSmall)
4898 .shape(ui::IconButtonShape::Square)
4899 .on_click(cx.listener(move |this, _, _window, cx| {
4900 this.thread_feedback.dismiss_comments();
4901 cx.notify();
4902 })),
4903 )
4904 .child(
4905 IconButton::new("submit-feedback-message", IconName::Return)
4906 .icon_size(IconSize::XSmall)
4907 .shape(ui::IconButtonShape::Square)
4908 .on_click(cx.listener(move |this, _, _window, cx| {
4909 this.submit_feedback_message(cx);
4910 })),
4911 ),
4912 )
4913 }
4914
4915 fn handle_feedback_click(
4916 &mut self,
4917 feedback: ThreadFeedback,
4918 window: &mut Window,
4919 cx: &mut Context<Self>,
4920 ) {
4921 let Some(thread) = self.thread().cloned() else {
4922 return;
4923 };
4924
4925 self.thread_feedback.submit(thread, feedback, window, cx);
4926 cx.notify();
4927 }
4928
4929 fn submit_feedback_message(&mut self, cx: &mut Context<Self>) {
4930 let Some(thread) = self.thread().cloned() else {
4931 return;
4932 };
4933
4934 self.thread_feedback.submit_comments(thread, cx);
4935 cx.notify();
4936 }
4937
4938 fn render_token_limit_callout(
4939 &self,
4940 line_height: Pixels,
4941 cx: &mut Context<Self>,
4942 ) -> Option<Callout> {
4943 let token_usage = self.thread()?.read(cx).token_usage()?;
4944 let ratio = token_usage.ratio();
4945
4946 let (severity, title) = match ratio {
4947 acp_thread::TokenUsageRatio::Normal => return None,
4948 acp_thread::TokenUsageRatio::Warning => {
4949 (Severity::Warning, "Thread reaching the token limit soon")
4950 }
4951 acp_thread::TokenUsageRatio::Exceeded => {
4952 (Severity::Error, "Thread reached the token limit")
4953 }
4954 };
4955
4956 let burn_mode_available = self.as_native_thread(cx).is_some_and(|thread| {
4957 thread.read(cx).completion_mode() == CompletionMode::Normal
4958 && thread
4959 .read(cx)
4960 .model()
4961 .is_some_and(|model| model.supports_burn_mode())
4962 });
4963
4964 let description = if burn_mode_available {
4965 "To continue, start a new thread from a summary or turn Burn Mode on."
4966 } else {
4967 "To continue, start a new thread from a summary."
4968 };
4969
4970 Some(
4971 Callout::new()
4972 .severity(severity)
4973 .line_height(line_height)
4974 .title(title)
4975 .description(description)
4976 .actions_slot(
4977 h_flex()
4978 .gap_0p5()
4979 .child(
4980 Button::new("start-new-thread", "Start New Thread")
4981 .label_size(LabelSize::Small)
4982 .on_click(cx.listener(|this, _, window, cx| {
4983 let Some(thread) = this.thread() else {
4984 return;
4985 };
4986 let session_id = thread.read(cx).session_id().clone();
4987 window.dispatch_action(
4988 crate::NewNativeAgentThreadFromSummary {
4989 from_session_id: session_id,
4990 }
4991 .boxed_clone(),
4992 cx,
4993 );
4994 })),
4995 )
4996 .when(burn_mode_available, |this| {
4997 this.child(
4998 IconButton::new("burn-mode-callout", IconName::ZedBurnMode)
4999 .icon_size(IconSize::XSmall)
5000 .on_click(cx.listener(|this, _event, window, cx| {
5001 this.toggle_burn_mode(&ToggleBurnMode, window, cx);
5002 })),
5003 )
5004 }),
5005 ),
5006 )
5007 }
5008
5009 fn render_usage_callout(&self, line_height: Pixels, cx: &mut Context<Self>) -> Option<Div> {
5010 if !self.is_using_zed_ai_models(cx) {
5011 return None;
5012 }
5013
5014 let user_store = self.project.read(cx).user_store().read(cx);
5015 if user_store.is_usage_based_billing_enabled() {
5016 return None;
5017 }
5018
5019 let plan = user_store
5020 .plan()
5021 .unwrap_or(cloud_llm_client::Plan::V1(PlanV1::ZedFree));
5022
5023 let usage = user_store.model_request_usage()?;
5024
5025 Some(
5026 div()
5027 .child(UsageCallout::new(plan, usage))
5028 .line_height(line_height),
5029 )
5030 }
5031
5032 fn agent_ui_font_size_changed(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
5033 self.entry_view_state.update(cx, |entry_view_state, cx| {
5034 entry_view_state.agent_ui_font_size_changed(cx);
5035 });
5036 }
5037
5038 pub(crate) fn insert_dragged_files(
5039 &self,
5040 paths: Vec<project::ProjectPath>,
5041 added_worktrees: Vec<Entity<project::Worktree>>,
5042 window: &mut Window,
5043 cx: &mut Context<Self>,
5044 ) {
5045 self.message_editor.update(cx, |message_editor, cx| {
5046 message_editor.insert_dragged_files(paths, added_worktrees, window, cx);
5047 })
5048 }
5049
5050 /// Inserts the selected text into the message editor or the message being
5051 /// edited, if any.
5052 pub(crate) fn insert_selections(&self, window: &mut Window, cx: &mut Context<Self>) {
5053 self.active_editor(cx).update(cx, |editor, cx| {
5054 editor.insert_selections(window, cx);
5055 });
5056 }
5057
5058 fn render_thread_retry_status_callout(
5059 &self,
5060 _window: &mut Window,
5061 _cx: &mut Context<Self>,
5062 ) -> Option<Callout> {
5063 let state = self.thread_retry_status.as_ref()?;
5064
5065 let next_attempt_in = state
5066 .duration
5067 .saturating_sub(Instant::now().saturating_duration_since(state.started_at));
5068 if next_attempt_in.is_zero() {
5069 return None;
5070 }
5071
5072 let next_attempt_in_secs = next_attempt_in.as_secs() + 1;
5073
5074 let retry_message = if state.max_attempts == 1 {
5075 if next_attempt_in_secs == 1 {
5076 "Retrying. Next attempt in 1 second.".to_string()
5077 } else {
5078 format!("Retrying. Next attempt in {next_attempt_in_secs} seconds.")
5079 }
5080 } else if next_attempt_in_secs == 1 {
5081 format!(
5082 "Retrying. Next attempt in 1 second (Attempt {} of {}).",
5083 state.attempt, state.max_attempts,
5084 )
5085 } else {
5086 format!(
5087 "Retrying. Next attempt in {next_attempt_in_secs} seconds (Attempt {} of {}).",
5088 state.attempt, state.max_attempts,
5089 )
5090 };
5091
5092 Some(
5093 Callout::new()
5094 .severity(Severity::Warning)
5095 .title(state.last_error.clone())
5096 .description(retry_message),
5097 )
5098 }
5099
5100 #[cfg(target_os = "windows")]
5101 fn render_codex_windows_warning(&self, cx: &mut Context<Self>) -> Option<Callout> {
5102 if self.show_codex_windows_warning {
5103 Some(
5104 Callout::new()
5105 .icon(IconName::Warning)
5106 .severity(Severity::Warning)
5107 .title("Codex on Windows")
5108 .description(
5109 "For best performance, run Codex in Windows Subsystem for Linux (WSL2)",
5110 )
5111 .actions_slot(
5112 Button::new("open-wsl-modal", "Open in WSL")
5113 .icon_size(IconSize::Small)
5114 .icon_color(Color::Muted)
5115 .on_click(cx.listener({
5116 move |_, _, window, cx| {
5117 window.dispatch_action(
5118 zed_actions::wsl_actions::OpenWsl::default().boxed_clone(),
5119 cx,
5120 );
5121 cx.notify();
5122 }
5123 })),
5124 )
5125 .dismiss_action(
5126 IconButton::new("dismiss", IconName::Close)
5127 .icon_size(IconSize::Small)
5128 .icon_color(Color::Muted)
5129 .tooltip(Tooltip::text("Dismiss Warning"))
5130 .on_click(cx.listener({
5131 move |this, _, _, cx| {
5132 this.show_codex_windows_warning = false;
5133 cx.notify();
5134 }
5135 })),
5136 ),
5137 )
5138 } else {
5139 None
5140 }
5141 }
5142
5143 fn render_thread_error(&self, window: &mut Window, cx: &mut Context<Self>) -> Option<Div> {
5144 let content = match self.thread_error.as_ref()? {
5145 ThreadError::Other(error) => self.render_any_thread_error(error.clone(), cx),
5146 ThreadError::Refusal => self.render_refusal_error(cx),
5147 ThreadError::AuthenticationRequired(error) => {
5148 self.render_authentication_required_error(error.clone(), cx)
5149 }
5150 ThreadError::PaymentRequired => self.render_payment_required_error(cx),
5151 ThreadError::ModelRequestLimitReached(plan) => {
5152 self.render_model_request_limit_reached_error(*plan, cx)
5153 }
5154 ThreadError::ToolUseLimitReached => {
5155 self.render_tool_use_limit_reached_error(window, cx)?
5156 }
5157 };
5158
5159 Some(div().child(content))
5160 }
5161
5162 fn render_new_version_callout(&self, version: &SharedString, cx: &mut Context<Self>) -> Div {
5163 v_flex().w_full().justify_end().child(
5164 h_flex()
5165 .p_2()
5166 .pr_3()
5167 .w_full()
5168 .gap_1p5()
5169 .border_t_1()
5170 .border_color(cx.theme().colors().border)
5171 .bg(cx.theme().colors().element_background)
5172 .child(
5173 h_flex()
5174 .flex_1()
5175 .gap_1p5()
5176 .child(
5177 Icon::new(IconName::Download)
5178 .color(Color::Accent)
5179 .size(IconSize::Small),
5180 )
5181 .child(Label::new("New version available").size(LabelSize::Small)),
5182 )
5183 .child(
5184 Button::new("update-button", format!("Update to v{}", version))
5185 .label_size(LabelSize::Small)
5186 .style(ButtonStyle::Tinted(TintColor::Accent))
5187 .on_click(cx.listener(|this, _, window, cx| {
5188 this.reset(window, cx);
5189 })),
5190 ),
5191 )
5192 }
5193
5194 fn get_current_model_name(&self, cx: &App) -> SharedString {
5195 // For native agent (Zed Agent), use the specific model name (e.g., "Claude 3.5 Sonnet")
5196 // For ACP agents, use the agent name (e.g., "Claude Code", "Gemini CLI")
5197 // This provides better clarity about what refused the request
5198 if self
5199 .agent
5200 .clone()
5201 .downcast::<agent::NativeAgentServer>()
5202 .is_some()
5203 {
5204 // Native agent - use the model name
5205 self.model_selector
5206 .as_ref()
5207 .and_then(|selector| selector.read(cx).active_model_name(cx))
5208 .unwrap_or_else(|| SharedString::from("The model"))
5209 } else {
5210 // ACP agent - use the agent name (e.g., "Claude Code", "Gemini CLI")
5211 self.agent.name()
5212 }
5213 }
5214
5215 fn render_refusal_error(&self, cx: &mut Context<'_, Self>) -> Callout {
5216 let model_or_agent_name = self.get_current_model_name(cx);
5217 let refusal_message = format!(
5218 "{} refused to respond to this prompt. This can happen when a model believes the prompt violates its content policy or safety guidelines, so rephrasing it can sometimes address the issue.",
5219 model_or_agent_name
5220 );
5221
5222 Callout::new()
5223 .severity(Severity::Error)
5224 .title("Request Refused")
5225 .icon(IconName::XCircle)
5226 .description(refusal_message.clone())
5227 .actions_slot(self.create_copy_button(&refusal_message))
5228 .dismiss_action(self.dismiss_error_button(cx))
5229 }
5230
5231 fn render_any_thread_error(&self, error: SharedString, cx: &mut Context<'_, Self>) -> Callout {
5232 let can_resume = self
5233 .thread()
5234 .map_or(false, |thread| thread.read(cx).can_resume(cx));
5235
5236 let can_enable_burn_mode = self.as_native_thread(cx).map_or(false, |thread| {
5237 let thread = thread.read(cx);
5238 let supports_burn_mode = thread
5239 .model()
5240 .map_or(false, |model| model.supports_burn_mode());
5241 supports_burn_mode && thread.completion_mode() == CompletionMode::Normal
5242 });
5243
5244 Callout::new()
5245 .severity(Severity::Error)
5246 .title("Error")
5247 .icon(IconName::XCircle)
5248 .description(error.clone())
5249 .actions_slot(
5250 h_flex()
5251 .gap_0p5()
5252 .when(can_resume && can_enable_burn_mode, |this| {
5253 this.child(
5254 Button::new("enable-burn-mode-and-retry", "Enable Burn Mode and Retry")
5255 .icon(IconName::ZedBurnMode)
5256 .icon_position(IconPosition::Start)
5257 .icon_size(IconSize::Small)
5258 .label_size(LabelSize::Small)
5259 .on_click(cx.listener(|this, _, window, cx| {
5260 this.toggle_burn_mode(&ToggleBurnMode, window, cx);
5261 this.resume_chat(cx);
5262 })),
5263 )
5264 })
5265 .when(can_resume, |this| {
5266 this.child(
5267 Button::new("retry", "Retry")
5268 .icon(IconName::RotateCw)
5269 .icon_position(IconPosition::Start)
5270 .icon_size(IconSize::Small)
5271 .label_size(LabelSize::Small)
5272 .on_click(cx.listener(|this, _, _window, cx| {
5273 this.resume_chat(cx);
5274 })),
5275 )
5276 })
5277 .child(self.create_copy_button(error.to_string())),
5278 )
5279 .dismiss_action(self.dismiss_error_button(cx))
5280 }
5281
5282 fn render_payment_required_error(&self, cx: &mut Context<Self>) -> Callout {
5283 const ERROR_MESSAGE: &str =
5284 "You reached your free usage limit. Upgrade to Zed Pro for more prompts.";
5285
5286 Callout::new()
5287 .severity(Severity::Error)
5288 .icon(IconName::XCircle)
5289 .title("Free Usage Exceeded")
5290 .description(ERROR_MESSAGE)
5291 .actions_slot(
5292 h_flex()
5293 .gap_0p5()
5294 .child(self.upgrade_button(cx))
5295 .child(self.create_copy_button(ERROR_MESSAGE)),
5296 )
5297 .dismiss_action(self.dismiss_error_button(cx))
5298 }
5299
5300 fn render_authentication_required_error(
5301 &self,
5302 error: SharedString,
5303 cx: &mut Context<Self>,
5304 ) -> Callout {
5305 Callout::new()
5306 .severity(Severity::Error)
5307 .title("Authentication Required")
5308 .icon(IconName::XCircle)
5309 .description(error.clone())
5310 .actions_slot(
5311 h_flex()
5312 .gap_0p5()
5313 .child(self.authenticate_button(cx))
5314 .child(self.create_copy_button(error)),
5315 )
5316 .dismiss_action(self.dismiss_error_button(cx))
5317 }
5318
5319 fn render_model_request_limit_reached_error(
5320 &self,
5321 plan: cloud_llm_client::Plan,
5322 cx: &mut Context<Self>,
5323 ) -> Callout {
5324 let error_message = match plan {
5325 cloud_llm_client::Plan::V1(PlanV1::ZedPro) => {
5326 "Upgrade to usage-based billing for more prompts."
5327 }
5328 cloud_llm_client::Plan::V1(PlanV1::ZedProTrial)
5329 | cloud_llm_client::Plan::V1(PlanV1::ZedFree) => "Upgrade to Zed Pro for more prompts.",
5330 cloud_llm_client::Plan::V2(_) => "",
5331 };
5332
5333 Callout::new()
5334 .severity(Severity::Error)
5335 .title("Model Prompt Limit Reached")
5336 .icon(IconName::XCircle)
5337 .description(error_message)
5338 .actions_slot(
5339 h_flex()
5340 .gap_0p5()
5341 .child(self.upgrade_button(cx))
5342 .child(self.create_copy_button(error_message)),
5343 )
5344 .dismiss_action(self.dismiss_error_button(cx))
5345 }
5346
5347 fn render_tool_use_limit_reached_error(
5348 &self,
5349 window: &mut Window,
5350 cx: &mut Context<Self>,
5351 ) -> Option<Callout> {
5352 let thread = self.as_native_thread(cx)?;
5353 let supports_burn_mode = thread
5354 .read(cx)
5355 .model()
5356 .is_some_and(|model| model.supports_burn_mode());
5357
5358 let focus_handle = self.focus_handle(cx);
5359
5360 Some(
5361 Callout::new()
5362 .icon(IconName::Info)
5363 .title("Consecutive tool use limit reached.")
5364 .actions_slot(
5365 h_flex()
5366 .gap_0p5()
5367 .when(supports_burn_mode, |this| {
5368 this.child(
5369 Button::new("continue-burn-mode", "Continue with Burn Mode")
5370 .style(ButtonStyle::Filled)
5371 .style(ButtonStyle::Tinted(ui::TintColor::Accent))
5372 .layer(ElevationIndex::ModalSurface)
5373 .label_size(LabelSize::Small)
5374 .key_binding(
5375 KeyBinding::for_action_in(
5376 &ContinueWithBurnMode,
5377 &focus_handle,
5378 window,
5379 cx,
5380 )
5381 .map(|kb| kb.size(rems_from_px(10.))),
5382 )
5383 .tooltip(Tooltip::text(
5384 "Enable Burn Mode for unlimited tool use.",
5385 ))
5386 .on_click({
5387 cx.listener(move |this, _, _window, cx| {
5388 thread.update(cx, |thread, cx| {
5389 thread
5390 .set_completion_mode(CompletionMode::Burn, cx);
5391 });
5392 this.resume_chat(cx);
5393 })
5394 }),
5395 )
5396 })
5397 .child(
5398 Button::new("continue-conversation", "Continue")
5399 .layer(ElevationIndex::ModalSurface)
5400 .label_size(LabelSize::Small)
5401 .key_binding(
5402 KeyBinding::for_action_in(
5403 &ContinueThread,
5404 &focus_handle,
5405 window,
5406 cx,
5407 )
5408 .map(|kb| kb.size(rems_from_px(10.))),
5409 )
5410 .on_click(cx.listener(|this, _, _window, cx| {
5411 this.resume_chat(cx);
5412 })),
5413 ),
5414 ),
5415 )
5416 }
5417
5418 fn create_copy_button(&self, message: impl Into<String>) -> impl IntoElement {
5419 let message = message.into();
5420
5421 IconButton::new("copy", IconName::Copy)
5422 .icon_size(IconSize::Small)
5423 .icon_color(Color::Muted)
5424 .tooltip(Tooltip::text("Copy Error Message"))
5425 .on_click(move |_, _, cx| {
5426 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
5427 })
5428 }
5429
5430 fn dismiss_error_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
5431 IconButton::new("dismiss", IconName::Close)
5432 .icon_size(IconSize::Small)
5433 .icon_color(Color::Muted)
5434 .tooltip(Tooltip::text("Dismiss Error"))
5435 .on_click(cx.listener({
5436 move |this, _, _, cx| {
5437 this.clear_thread_error(cx);
5438 cx.notify();
5439 }
5440 }))
5441 }
5442
5443 fn authenticate_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
5444 Button::new("authenticate", "Authenticate")
5445 .label_size(LabelSize::Small)
5446 .style(ButtonStyle::Filled)
5447 .on_click(cx.listener({
5448 move |this, _, window, cx| {
5449 let agent = this.agent.clone();
5450 let ThreadState::Ready { thread, .. } = &this.thread_state else {
5451 return;
5452 };
5453
5454 let connection = thread.read(cx).connection().clone();
5455 let err = AuthRequired {
5456 description: None,
5457 provider_id: None,
5458 };
5459 this.clear_thread_error(cx);
5460 let this = cx.weak_entity();
5461 window.defer(cx, |window, cx| {
5462 Self::handle_auth_required(this, err, agent, connection, window, cx);
5463 })
5464 }
5465 }))
5466 }
5467
5468 pub(crate) fn reauthenticate(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5469 let agent = self.agent.clone();
5470 let ThreadState::Ready { thread, .. } = &self.thread_state else {
5471 return;
5472 };
5473
5474 let connection = thread.read(cx).connection().clone();
5475 let err = AuthRequired {
5476 description: None,
5477 provider_id: None,
5478 };
5479 self.clear_thread_error(cx);
5480 let this = cx.weak_entity();
5481 window.defer(cx, |window, cx| {
5482 Self::handle_auth_required(this, err, agent, connection, window, cx);
5483 })
5484 }
5485
5486 fn upgrade_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
5487 Button::new("upgrade", "Upgrade")
5488 .label_size(LabelSize::Small)
5489 .style(ButtonStyle::Tinted(ui::TintColor::Accent))
5490 .on_click(cx.listener({
5491 move |this, _, _, cx| {
5492 this.clear_thread_error(cx);
5493 cx.open_url(&zed_urls::upgrade_to_zed_pro_url(cx));
5494 }
5495 }))
5496 }
5497
5498 pub fn delete_history_entry(&mut self, entry: HistoryEntry, cx: &mut Context<Self>) {
5499 let task = match entry {
5500 HistoryEntry::AcpThread(thread) => self.history_store.update(cx, |history, cx| {
5501 history.delete_thread(thread.id.clone(), cx)
5502 }),
5503 HistoryEntry::TextThread(context) => self.history_store.update(cx, |history, cx| {
5504 history.delete_text_thread(context.path.clone(), cx)
5505 }),
5506 };
5507 task.detach_and_log_err(cx);
5508 }
5509
5510 /// Returns the currently active editor, either for a message that is being
5511 /// edited or the editor for a new message.
5512 fn active_editor(&self, cx: &App) -> Entity<MessageEditor> {
5513 if let Some(index) = self.editing_message
5514 && let Some(editor) = self
5515 .entry_view_state
5516 .read(cx)
5517 .entry(index)
5518 .and_then(|e| e.message_editor())
5519 .cloned()
5520 {
5521 editor
5522 } else {
5523 self.message_editor.clone()
5524 }
5525 }
5526}
5527
5528fn loading_contents_spinner(size: IconSize) -> AnyElement {
5529 Icon::new(IconName::LoadCircle)
5530 .size(size)
5531 .color(Color::Accent)
5532 .with_rotate_animation(3)
5533 .into_any_element()
5534}
5535
5536impl Focusable for AcpThreadView {
5537 fn focus_handle(&self, cx: &App) -> FocusHandle {
5538 match self.thread_state {
5539 ThreadState::Loading { .. } | ThreadState::Ready { .. } => {
5540 self.active_editor(cx).focus_handle(cx)
5541 }
5542 ThreadState::LoadError(_) | ThreadState::Unauthenticated { .. } => {
5543 self.focus_handle.clone()
5544 }
5545 }
5546 }
5547}
5548
5549impl Render for AcpThreadView {
5550 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
5551 let has_messages = self.list_state.item_count() > 0;
5552 let line_height = TextSize::Small.rems(cx).to_pixels(window.rem_size()) * 1.5;
5553
5554 v_flex()
5555 .size_full()
5556 .key_context("AcpThread")
5557 .on_action(cx.listener(Self::toggle_burn_mode))
5558 .on_action(cx.listener(Self::keep_all))
5559 .on_action(cx.listener(Self::reject_all))
5560 .on_action(cx.listener(Self::allow_always))
5561 .on_action(cx.listener(Self::allow_once))
5562 .on_action(cx.listener(Self::reject_once))
5563 .track_focus(&self.focus_handle)
5564 .bg(cx.theme().colors().panel_background)
5565 .child(match &self.thread_state {
5566 ThreadState::Unauthenticated {
5567 connection,
5568 description,
5569 configuration_view,
5570 pending_auth_method,
5571 ..
5572 } => self
5573 .render_auth_required_state(
5574 connection,
5575 description.as_ref(),
5576 configuration_view.as_ref(),
5577 pending_auth_method.as_ref(),
5578 window,
5579 cx,
5580 )
5581 .into_any(),
5582 ThreadState::Loading { .. } => v_flex()
5583 .flex_1()
5584 .child(self.render_recent_history(window, cx))
5585 .into_any(),
5586 ThreadState::LoadError(e) => v_flex()
5587 .flex_1()
5588 .size_full()
5589 .items_center()
5590 .justify_end()
5591 .child(self.render_load_error(e, window, cx))
5592 .into_any(),
5593 ThreadState::Ready { .. } => v_flex().flex_1().map(|this| {
5594 if has_messages {
5595 this.child(
5596 list(
5597 self.list_state.clone(),
5598 cx.processor(|this, index: usize, window, cx| {
5599 let Some((entry, len)) = this.thread().and_then(|thread| {
5600 let entries = &thread.read(cx).entries();
5601 Some((entries.get(index)?, entries.len()))
5602 }) else {
5603 return Empty.into_any();
5604 };
5605 this.render_entry(index, len, entry, window, cx)
5606 }),
5607 )
5608 .with_sizing_behavior(gpui::ListSizingBehavior::Auto)
5609 .flex_grow()
5610 .into_any(),
5611 )
5612 .vertical_scrollbar_for(self.list_state.clone(), window, cx)
5613 .into_any()
5614 } else {
5615 this.child(self.render_recent_history(window, cx))
5616 .into_any()
5617 }
5618 }),
5619 })
5620 // The activity bar is intentionally rendered outside of the ThreadState::Ready match
5621 // above so that the scrollbar doesn't render behind it. The current setup allows
5622 // the scrollbar to stop exactly at the activity bar start.
5623 .when(has_messages, |this| match &self.thread_state {
5624 ThreadState::Ready { thread, .. } => {
5625 this.children(self.render_activity_bar(thread, window, cx))
5626 }
5627 _ => this,
5628 })
5629 .children(self.render_thread_retry_status_callout(window, cx))
5630 .children({
5631 #[cfg(target_os = "windows")]
5632 {
5633 self.render_codex_windows_warning(cx)
5634 }
5635 #[cfg(not(target_os = "windows"))]
5636 {
5637 Vec::<Empty>::new()
5638 }
5639 })
5640 .children(self.render_thread_error(window, cx))
5641 .when_some(
5642 self.new_server_version_available.as_ref().filter(|_| {
5643 !has_messages || !matches!(self.thread_state, ThreadState::Ready { .. })
5644 }),
5645 |this, version| this.child(self.render_new_version_callout(&version, cx)),
5646 )
5647 .children(
5648 if let Some(usage_callout) = self.render_usage_callout(line_height, cx) {
5649 Some(usage_callout.into_any_element())
5650 } else {
5651 self.render_token_limit_callout(line_height, cx)
5652 .map(|token_limit_callout| token_limit_callout.into_any_element())
5653 },
5654 )
5655 .child(self.render_message_editor(window, cx))
5656 }
5657}
5658
5659fn default_markdown_style(
5660 buffer_font: bool,
5661 muted_text: bool,
5662 window: &Window,
5663 cx: &App,
5664) -> MarkdownStyle {
5665 let theme_settings = ThemeSettings::get_global(cx);
5666 let colors = cx.theme().colors();
5667
5668 let buffer_font_size = TextSize::Small.rems(cx);
5669
5670 let mut text_style = window.text_style();
5671 let line_height = buffer_font_size * 1.75;
5672
5673 let font_family = if buffer_font {
5674 theme_settings.buffer_font.family.clone()
5675 } else {
5676 theme_settings.ui_font.family.clone()
5677 };
5678
5679 let font_size = if buffer_font {
5680 TextSize::Small.rems(cx)
5681 } else {
5682 TextSize::Default.rems(cx)
5683 };
5684
5685 let text_color = if muted_text {
5686 colors.text_muted
5687 } else {
5688 colors.text
5689 };
5690
5691 text_style.refine(&TextStyleRefinement {
5692 font_family: Some(font_family),
5693 font_fallbacks: theme_settings.ui_font.fallbacks.clone(),
5694 font_features: Some(theme_settings.ui_font.features.clone()),
5695 font_size: Some(font_size.into()),
5696 line_height: Some(line_height.into()),
5697 color: Some(text_color),
5698 ..Default::default()
5699 });
5700
5701 MarkdownStyle {
5702 base_text_style: text_style.clone(),
5703 syntax: cx.theme().syntax().clone(),
5704 selection_background_color: colors.element_selection_background,
5705 code_block_overflow_x_scroll: true,
5706 table_overflow_x_scroll: true,
5707 heading_level_styles: Some(HeadingLevelStyles {
5708 h1: Some(TextStyleRefinement {
5709 font_size: Some(rems(1.15).into()),
5710 ..Default::default()
5711 }),
5712 h2: Some(TextStyleRefinement {
5713 font_size: Some(rems(1.1).into()),
5714 ..Default::default()
5715 }),
5716 h3: Some(TextStyleRefinement {
5717 font_size: Some(rems(1.05).into()),
5718 ..Default::default()
5719 }),
5720 h4: Some(TextStyleRefinement {
5721 font_size: Some(rems(1.).into()),
5722 ..Default::default()
5723 }),
5724 h5: Some(TextStyleRefinement {
5725 font_size: Some(rems(0.95).into()),
5726 ..Default::default()
5727 }),
5728 h6: Some(TextStyleRefinement {
5729 font_size: Some(rems(0.875).into()),
5730 ..Default::default()
5731 }),
5732 }),
5733 code_block: StyleRefinement {
5734 padding: EdgesRefinement {
5735 top: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(px(8.)))),
5736 left: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(px(8.)))),
5737 right: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(px(8.)))),
5738 bottom: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(px(8.)))),
5739 },
5740 margin: EdgesRefinement {
5741 top: Some(Length::Definite(px(8.).into())),
5742 left: Some(Length::Definite(px(0.).into())),
5743 right: Some(Length::Definite(px(0.).into())),
5744 bottom: Some(Length::Definite(px(12.).into())),
5745 },
5746 border_style: Some(BorderStyle::Solid),
5747 border_widths: EdgesRefinement {
5748 top: Some(AbsoluteLength::Pixels(px(1.))),
5749 left: Some(AbsoluteLength::Pixels(px(1.))),
5750 right: Some(AbsoluteLength::Pixels(px(1.))),
5751 bottom: Some(AbsoluteLength::Pixels(px(1.))),
5752 },
5753 border_color: Some(colors.border_variant),
5754 background: Some(colors.editor_background.into()),
5755 text: Some(TextStyleRefinement {
5756 font_family: Some(theme_settings.buffer_font.family.clone()),
5757 font_fallbacks: theme_settings.buffer_font.fallbacks.clone(),
5758 font_features: Some(theme_settings.buffer_font.features.clone()),
5759 font_size: Some(buffer_font_size.into()),
5760 ..Default::default()
5761 }),
5762 ..Default::default()
5763 },
5764 inline_code: TextStyleRefinement {
5765 font_family: Some(theme_settings.buffer_font.family.clone()),
5766 font_fallbacks: theme_settings.buffer_font.fallbacks.clone(),
5767 font_features: Some(theme_settings.buffer_font.features.clone()),
5768 font_size: Some(buffer_font_size.into()),
5769 background_color: Some(colors.editor_foreground.opacity(0.08)),
5770 ..Default::default()
5771 },
5772 link: TextStyleRefinement {
5773 background_color: Some(colors.editor_foreground.opacity(0.025)),
5774 underline: Some(UnderlineStyle {
5775 color: Some(colors.text_accent.opacity(0.5)),
5776 thickness: px(1.),
5777 ..Default::default()
5778 }),
5779 ..Default::default()
5780 },
5781 ..Default::default()
5782 }
5783}
5784
5785fn plan_label_markdown_style(
5786 status: &acp::PlanEntryStatus,
5787 window: &Window,
5788 cx: &App,
5789) -> MarkdownStyle {
5790 let default_md_style = default_markdown_style(false, false, window, cx);
5791
5792 MarkdownStyle {
5793 base_text_style: TextStyle {
5794 color: cx.theme().colors().text_muted,
5795 strikethrough: if matches!(status, acp::PlanEntryStatus::Completed) {
5796 Some(gpui::StrikethroughStyle {
5797 thickness: px(1.),
5798 color: Some(cx.theme().colors().text_muted.opacity(0.8)),
5799 })
5800 } else {
5801 None
5802 },
5803 ..default_md_style.base_text_style
5804 },
5805 ..default_md_style
5806 }
5807}
5808
5809fn terminal_command_markdown_style(window: &Window, cx: &App) -> MarkdownStyle {
5810 let default_md_style = default_markdown_style(true, false, window, cx);
5811
5812 MarkdownStyle {
5813 base_text_style: TextStyle {
5814 ..default_md_style.base_text_style
5815 },
5816 selection_background_color: cx.theme().colors().element_selection_background,
5817 ..Default::default()
5818 }
5819}
5820
5821#[cfg(test)]
5822pub(crate) mod tests {
5823 use acp_thread::StubAgentConnection;
5824 use agent_client_protocol::SessionId;
5825 use assistant_context::ContextStore;
5826 use editor::EditorSettings;
5827 use fs::FakeFs;
5828 use gpui::{EventEmitter, SemanticVersion, TestAppContext, VisualTestContext};
5829 use project::Project;
5830 use serde_json::json;
5831 use settings::SettingsStore;
5832 use std::any::Any;
5833 use std::path::Path;
5834 use workspace::Item;
5835
5836 use super::*;
5837
5838 #[gpui::test]
5839 async fn test_drop(cx: &mut TestAppContext) {
5840 init_test(cx);
5841
5842 let (thread_view, _cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
5843 let weak_view = thread_view.downgrade();
5844 drop(thread_view);
5845 assert!(!weak_view.is_upgradable());
5846 }
5847
5848 #[gpui::test]
5849 async fn test_notification_for_stop_event(cx: &mut TestAppContext) {
5850 init_test(cx);
5851
5852 let (thread_view, cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
5853
5854 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
5855 message_editor.update_in(cx, |editor, window, cx| {
5856 editor.set_text("Hello", window, cx);
5857 });
5858
5859 cx.deactivate_window();
5860
5861 thread_view.update_in(cx, |thread_view, window, cx| {
5862 thread_view.send(window, cx);
5863 });
5864
5865 cx.run_until_parked();
5866
5867 assert!(
5868 cx.windows()
5869 .iter()
5870 .any(|window| window.downcast::<AgentNotification>().is_some())
5871 );
5872 }
5873
5874 #[gpui::test]
5875 async fn test_notification_for_error(cx: &mut TestAppContext) {
5876 init_test(cx);
5877
5878 let (thread_view, cx) =
5879 setup_thread_view(StubAgentServer::new(SaboteurAgentConnection), cx).await;
5880
5881 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
5882 message_editor.update_in(cx, |editor, window, cx| {
5883 editor.set_text("Hello", window, cx);
5884 });
5885
5886 cx.deactivate_window();
5887
5888 thread_view.update_in(cx, |thread_view, window, cx| {
5889 thread_view.send(window, cx);
5890 });
5891
5892 cx.run_until_parked();
5893
5894 assert!(
5895 cx.windows()
5896 .iter()
5897 .any(|window| window.downcast::<AgentNotification>().is_some())
5898 );
5899 }
5900
5901 #[gpui::test]
5902 async fn test_refusal_handling(cx: &mut TestAppContext) {
5903 init_test(cx);
5904
5905 let (thread_view, cx) =
5906 setup_thread_view(StubAgentServer::new(RefusalAgentConnection), cx).await;
5907
5908 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
5909 message_editor.update_in(cx, |editor, window, cx| {
5910 editor.set_text("Do something harmful", window, cx);
5911 });
5912
5913 thread_view.update_in(cx, |thread_view, window, cx| {
5914 thread_view.send(window, cx);
5915 });
5916
5917 cx.run_until_parked();
5918
5919 // Check that the refusal error is set
5920 thread_view.read_with(cx, |thread_view, _cx| {
5921 assert!(
5922 matches!(thread_view.thread_error, Some(ThreadError::Refusal)),
5923 "Expected refusal error to be set"
5924 );
5925 });
5926 }
5927
5928 #[gpui::test]
5929 async fn test_notification_for_tool_authorization(cx: &mut TestAppContext) {
5930 init_test(cx);
5931
5932 let tool_call_id = acp::ToolCallId("1".into());
5933 let tool_call = acp::ToolCall {
5934 id: tool_call_id.clone(),
5935 title: "Label".into(),
5936 kind: acp::ToolKind::Edit,
5937 status: acp::ToolCallStatus::Pending,
5938 content: vec!["hi".into()],
5939 locations: vec![],
5940 raw_input: None,
5941 raw_output: None,
5942 meta: None,
5943 };
5944 let connection =
5945 StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
5946 tool_call_id,
5947 vec![acp::PermissionOption {
5948 id: acp::PermissionOptionId("1".into()),
5949 name: "Allow".into(),
5950 kind: acp::PermissionOptionKind::AllowOnce,
5951 meta: None,
5952 }],
5953 )]));
5954
5955 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
5956
5957 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
5958
5959 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
5960 message_editor.update_in(cx, |editor, window, cx| {
5961 editor.set_text("Hello", window, cx);
5962 });
5963
5964 cx.deactivate_window();
5965
5966 thread_view.update_in(cx, |thread_view, window, cx| {
5967 thread_view.send(window, cx);
5968 });
5969
5970 cx.run_until_parked();
5971
5972 assert!(
5973 cx.windows()
5974 .iter()
5975 .any(|window| window.downcast::<AgentNotification>().is_some())
5976 );
5977 }
5978
5979 async fn setup_thread_view(
5980 agent: impl AgentServer + 'static,
5981 cx: &mut TestAppContext,
5982 ) -> (Entity<AcpThreadView>, &mut VisualTestContext) {
5983 let fs = FakeFs::new(cx.executor());
5984 let project = Project::test(fs, [], cx).await;
5985 let (workspace, cx) =
5986 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5987
5988 let context_store =
5989 cx.update(|_window, cx| cx.new(|cx| ContextStore::fake(project.clone(), cx)));
5990 let history_store =
5991 cx.update(|_window, cx| cx.new(|cx| HistoryStore::new(context_store, cx)));
5992
5993 let thread_view = cx.update(|window, cx| {
5994 cx.new(|cx| {
5995 AcpThreadView::new(
5996 Rc::new(agent),
5997 None,
5998 None,
5999 workspace.downgrade(),
6000 project,
6001 history_store,
6002 None,
6003 window,
6004 cx,
6005 )
6006 })
6007 });
6008 cx.run_until_parked();
6009 (thread_view, cx)
6010 }
6011
6012 fn add_to_workspace(thread_view: Entity<AcpThreadView>, cx: &mut VisualTestContext) {
6013 let workspace = thread_view.read_with(cx, |thread_view, _cx| thread_view.workspace.clone());
6014
6015 workspace
6016 .update_in(cx, |workspace, window, cx| {
6017 workspace.add_item_to_active_pane(
6018 Box::new(cx.new(|_| ThreadViewItem(thread_view.clone()))),
6019 None,
6020 true,
6021 window,
6022 cx,
6023 );
6024 })
6025 .unwrap();
6026 }
6027
6028 struct ThreadViewItem(Entity<AcpThreadView>);
6029
6030 impl Item for ThreadViewItem {
6031 type Event = ();
6032
6033 fn include_in_nav_history() -> bool {
6034 false
6035 }
6036
6037 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
6038 "Test".into()
6039 }
6040 }
6041
6042 impl EventEmitter<()> for ThreadViewItem {}
6043
6044 impl Focusable for ThreadViewItem {
6045 fn focus_handle(&self, cx: &App) -> FocusHandle {
6046 self.0.read(cx).focus_handle(cx)
6047 }
6048 }
6049
6050 impl Render for ThreadViewItem {
6051 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
6052 self.0.clone().into_any_element()
6053 }
6054 }
6055
6056 struct StubAgentServer<C> {
6057 connection: C,
6058 }
6059
6060 impl<C> StubAgentServer<C> {
6061 fn new(connection: C) -> Self {
6062 Self { connection }
6063 }
6064 }
6065
6066 impl StubAgentServer<StubAgentConnection> {
6067 fn default_response() -> Self {
6068 let conn = StubAgentConnection::new();
6069 conn.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk {
6070 content: "Default response".into(),
6071 }]);
6072 Self::new(conn)
6073 }
6074 }
6075
6076 impl<C> AgentServer for StubAgentServer<C>
6077 where
6078 C: 'static + AgentConnection + Send + Clone,
6079 {
6080 fn telemetry_id(&self) -> &'static str {
6081 "test"
6082 }
6083
6084 fn logo(&self) -> ui::IconName {
6085 ui::IconName::Ai
6086 }
6087
6088 fn name(&self) -> SharedString {
6089 "Test".into()
6090 }
6091
6092 fn connect(
6093 &self,
6094 _root_dir: Option<&Path>,
6095 _delegate: AgentServerDelegate,
6096 _cx: &mut App,
6097 ) -> Task<
6098 gpui::Result<(
6099 Rc<dyn AgentConnection>,
6100 HashMap<String, task::SpawnInTerminal>,
6101 )>,
6102 > {
6103 Task::ready(Ok((Rc::new(self.connection.clone()), HashMap::default())))
6104 }
6105
6106 fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
6107 self
6108 }
6109 }
6110
6111 #[derive(Clone)]
6112 struct SaboteurAgentConnection;
6113
6114 impl AgentConnection for SaboteurAgentConnection {
6115 fn new_thread(
6116 self: Rc<Self>,
6117 project: Entity<Project>,
6118 _cwd: &Path,
6119 cx: &mut gpui::App,
6120 ) -> Task<gpui::Result<Entity<AcpThread>>> {
6121 Task::ready(Ok(cx.new(|cx| {
6122 let action_log = cx.new(|_| ActionLog::new(project.clone()));
6123 AcpThread::new(
6124 "SaboteurAgentConnection",
6125 self,
6126 project,
6127 action_log,
6128 SessionId("test".into()),
6129 watch::Receiver::constant(acp::PromptCapabilities {
6130 image: true,
6131 audio: true,
6132 embedded_context: true,
6133 meta: None,
6134 }),
6135 cx,
6136 )
6137 })))
6138 }
6139
6140 fn auth_methods(&self) -> &[acp::AuthMethod] {
6141 &[]
6142 }
6143
6144 fn authenticate(
6145 &self,
6146 _method_id: acp::AuthMethodId,
6147 _cx: &mut App,
6148 ) -> Task<gpui::Result<()>> {
6149 unimplemented!()
6150 }
6151
6152 fn prompt(
6153 &self,
6154 _id: Option<acp_thread::UserMessageId>,
6155 _params: acp::PromptRequest,
6156 _cx: &mut App,
6157 ) -> Task<gpui::Result<acp::PromptResponse>> {
6158 Task::ready(Err(anyhow::anyhow!("Error prompting")))
6159 }
6160
6161 fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {
6162 unimplemented!()
6163 }
6164
6165 fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
6166 self
6167 }
6168 }
6169
6170 /// Simulates a model which always returns a refusal response
6171 #[derive(Clone)]
6172 struct RefusalAgentConnection;
6173
6174 impl AgentConnection for RefusalAgentConnection {
6175 fn new_thread(
6176 self: Rc<Self>,
6177 project: Entity<Project>,
6178 _cwd: &Path,
6179 cx: &mut gpui::App,
6180 ) -> Task<gpui::Result<Entity<AcpThread>>> {
6181 Task::ready(Ok(cx.new(|cx| {
6182 let action_log = cx.new(|_| ActionLog::new(project.clone()));
6183 AcpThread::new(
6184 "RefusalAgentConnection",
6185 self,
6186 project,
6187 action_log,
6188 SessionId("test".into()),
6189 watch::Receiver::constant(acp::PromptCapabilities {
6190 image: true,
6191 audio: true,
6192 embedded_context: true,
6193 meta: None,
6194 }),
6195 cx,
6196 )
6197 })))
6198 }
6199
6200 fn auth_methods(&self) -> &[acp::AuthMethod] {
6201 &[]
6202 }
6203
6204 fn authenticate(
6205 &self,
6206 _method_id: acp::AuthMethodId,
6207 _cx: &mut App,
6208 ) -> Task<gpui::Result<()>> {
6209 unimplemented!()
6210 }
6211
6212 fn prompt(
6213 &self,
6214 _id: Option<acp_thread::UserMessageId>,
6215 _params: acp::PromptRequest,
6216 _cx: &mut App,
6217 ) -> Task<gpui::Result<acp::PromptResponse>> {
6218 Task::ready(Ok(acp::PromptResponse {
6219 stop_reason: acp::StopReason::Refusal,
6220 meta: None,
6221 }))
6222 }
6223
6224 fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {
6225 unimplemented!()
6226 }
6227
6228 fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
6229 self
6230 }
6231 }
6232
6233 pub(crate) fn init_test(cx: &mut TestAppContext) {
6234 cx.update(|cx| {
6235 let settings_store = SettingsStore::test(cx);
6236 cx.set_global(settings_store);
6237 language::init(cx);
6238 Project::init_settings(cx);
6239 AgentSettings::register(cx);
6240 workspace::init_settings(cx);
6241 theme::init(theme::LoadThemes::JustBase, cx);
6242 release_channel::init(SemanticVersion::default(), cx);
6243 EditorSettings::register(cx);
6244 prompt_store::init(cx)
6245 });
6246 }
6247
6248 #[gpui::test]
6249 async fn test_rewind_views(cx: &mut TestAppContext) {
6250 init_test(cx);
6251
6252 let fs = FakeFs::new(cx.executor());
6253 fs.insert_tree(
6254 "/project",
6255 json!({
6256 "test1.txt": "old content 1",
6257 "test2.txt": "old content 2"
6258 }),
6259 )
6260 .await;
6261 let project = Project::test(fs, [Path::new("/project")], cx).await;
6262 let (workspace, cx) =
6263 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6264
6265 let context_store =
6266 cx.update(|_window, cx| cx.new(|cx| ContextStore::fake(project.clone(), cx)));
6267 let history_store =
6268 cx.update(|_window, cx| cx.new(|cx| HistoryStore::new(context_store, cx)));
6269
6270 let connection = Rc::new(StubAgentConnection::new());
6271 let thread_view = cx.update(|window, cx| {
6272 cx.new(|cx| {
6273 AcpThreadView::new(
6274 Rc::new(StubAgentServer::new(connection.as_ref().clone())),
6275 None,
6276 None,
6277 workspace.downgrade(),
6278 project.clone(),
6279 history_store.clone(),
6280 None,
6281 window,
6282 cx,
6283 )
6284 })
6285 });
6286
6287 cx.run_until_parked();
6288
6289 let thread = thread_view
6290 .read_with(cx, |view, _| view.thread().cloned())
6291 .unwrap();
6292
6293 // First user message
6294 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(acp::ToolCall {
6295 id: acp::ToolCallId("tool1".into()),
6296 title: "Edit file 1".into(),
6297 kind: acp::ToolKind::Edit,
6298 status: acp::ToolCallStatus::Completed,
6299 content: vec![acp::ToolCallContent::Diff {
6300 diff: acp::Diff {
6301 path: "/project/test1.txt".into(),
6302 old_text: Some("old content 1".into()),
6303 new_text: "new content 1".into(),
6304 meta: None,
6305 },
6306 }],
6307 locations: vec![],
6308 raw_input: None,
6309 raw_output: None,
6310 meta: None,
6311 })]);
6312
6313 thread
6314 .update(cx, |thread, cx| thread.send_raw("Give me a diff", cx))
6315 .await
6316 .unwrap();
6317 cx.run_until_parked();
6318
6319 thread.read_with(cx, |thread, _| {
6320 assert_eq!(thread.entries().len(), 2);
6321 });
6322
6323 thread_view.read_with(cx, |view, cx| {
6324 view.entry_view_state.read_with(cx, |entry_view_state, _| {
6325 assert!(
6326 entry_view_state
6327 .entry(0)
6328 .unwrap()
6329 .message_editor()
6330 .is_some()
6331 );
6332 assert!(entry_view_state.entry(1).unwrap().has_content());
6333 });
6334 });
6335
6336 // Second user message
6337 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(acp::ToolCall {
6338 id: acp::ToolCallId("tool2".into()),
6339 title: "Edit file 2".into(),
6340 kind: acp::ToolKind::Edit,
6341 status: acp::ToolCallStatus::Completed,
6342 content: vec![acp::ToolCallContent::Diff {
6343 diff: acp::Diff {
6344 path: "/project/test2.txt".into(),
6345 old_text: Some("old content 2".into()),
6346 new_text: "new content 2".into(),
6347 meta: None,
6348 },
6349 }],
6350 locations: vec![],
6351 raw_input: None,
6352 raw_output: None,
6353 meta: None,
6354 })]);
6355
6356 thread
6357 .update(cx, |thread, cx| thread.send_raw("Another one", cx))
6358 .await
6359 .unwrap();
6360 cx.run_until_parked();
6361
6362 let second_user_message_id = thread.read_with(cx, |thread, _| {
6363 assert_eq!(thread.entries().len(), 4);
6364 let AgentThreadEntry::UserMessage(user_message) = &thread.entries()[2] else {
6365 panic!();
6366 };
6367 user_message.id.clone().unwrap()
6368 });
6369
6370 thread_view.read_with(cx, |view, cx| {
6371 view.entry_view_state.read_with(cx, |entry_view_state, _| {
6372 assert!(
6373 entry_view_state
6374 .entry(0)
6375 .unwrap()
6376 .message_editor()
6377 .is_some()
6378 );
6379 assert!(entry_view_state.entry(1).unwrap().has_content());
6380 assert!(
6381 entry_view_state
6382 .entry(2)
6383 .unwrap()
6384 .message_editor()
6385 .is_some()
6386 );
6387 assert!(entry_view_state.entry(3).unwrap().has_content());
6388 });
6389 });
6390
6391 // Rewind to first message
6392 thread
6393 .update(cx, |thread, cx| thread.rewind(second_user_message_id, cx))
6394 .await
6395 .unwrap();
6396
6397 cx.run_until_parked();
6398
6399 thread.read_with(cx, |thread, _| {
6400 assert_eq!(thread.entries().len(), 2);
6401 });
6402
6403 thread_view.read_with(cx, |view, cx| {
6404 view.entry_view_state.read_with(cx, |entry_view_state, _| {
6405 assert!(
6406 entry_view_state
6407 .entry(0)
6408 .unwrap()
6409 .message_editor()
6410 .is_some()
6411 );
6412 assert!(entry_view_state.entry(1).unwrap().has_content());
6413
6414 // Old views should be dropped
6415 assert!(entry_view_state.entry(2).is_none());
6416 assert!(entry_view_state.entry(3).is_none());
6417 });
6418 });
6419 }
6420
6421 #[gpui::test]
6422 async fn test_message_editing_cancel(cx: &mut TestAppContext) {
6423 init_test(cx);
6424
6425 let connection = StubAgentConnection::new();
6426
6427 connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk {
6428 content: acp::ContentBlock::Text(acp::TextContent {
6429 text: "Response".into(),
6430 annotations: None,
6431 meta: None,
6432 }),
6433 }]);
6434
6435 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
6436 add_to_workspace(thread_view.clone(), cx);
6437
6438 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
6439 message_editor.update_in(cx, |editor, window, cx| {
6440 editor.set_text("Original message to edit", window, cx);
6441 });
6442 thread_view.update_in(cx, |thread_view, window, cx| {
6443 thread_view.send(window, cx);
6444 });
6445
6446 cx.run_until_parked();
6447
6448 let user_message_editor = thread_view.read_with(cx, |view, cx| {
6449 assert_eq!(view.editing_message, None);
6450
6451 view.entry_view_state
6452 .read(cx)
6453 .entry(0)
6454 .unwrap()
6455 .message_editor()
6456 .unwrap()
6457 .clone()
6458 });
6459
6460 // Focus
6461 cx.focus(&user_message_editor);
6462 thread_view.read_with(cx, |view, _cx| {
6463 assert_eq!(view.editing_message, Some(0));
6464 });
6465
6466 // Edit
6467 user_message_editor.update_in(cx, |editor, window, cx| {
6468 editor.set_text("Edited message content", window, cx);
6469 });
6470
6471 // Cancel
6472 user_message_editor.update_in(cx, |_editor, window, cx| {
6473 window.dispatch_action(Box::new(editor::actions::Cancel), cx);
6474 });
6475
6476 thread_view.read_with(cx, |view, _cx| {
6477 assert_eq!(view.editing_message, None);
6478 });
6479
6480 user_message_editor.read_with(cx, |editor, cx| {
6481 assert_eq!(editor.text(cx), "Original message to edit");
6482 });
6483 }
6484
6485 #[gpui::test]
6486 async fn test_message_doesnt_send_if_empty(cx: &mut TestAppContext) {
6487 init_test(cx);
6488
6489 let connection = StubAgentConnection::new();
6490
6491 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
6492 add_to_workspace(thread_view.clone(), cx);
6493
6494 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
6495 let mut events = cx.events(&message_editor);
6496 message_editor.update_in(cx, |editor, window, cx| {
6497 editor.set_text("", window, cx);
6498 });
6499
6500 message_editor.update_in(cx, |_editor, window, cx| {
6501 window.dispatch_action(Box::new(Chat), cx);
6502 });
6503 cx.run_until_parked();
6504 // We shouldn't have received any messages
6505 assert!(matches!(
6506 events.try_next(),
6507 Err(futures::channel::mpsc::TryRecvError { .. })
6508 ));
6509 }
6510
6511 #[gpui::test]
6512 async fn test_message_editing_regenerate(cx: &mut TestAppContext) {
6513 init_test(cx);
6514
6515 let connection = StubAgentConnection::new();
6516
6517 connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk {
6518 content: acp::ContentBlock::Text(acp::TextContent {
6519 text: "Response".into(),
6520 annotations: None,
6521 meta: None,
6522 }),
6523 }]);
6524
6525 let (thread_view, cx) =
6526 setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
6527 add_to_workspace(thread_view.clone(), cx);
6528
6529 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
6530 message_editor.update_in(cx, |editor, window, cx| {
6531 editor.set_text("Original message to edit", window, cx);
6532 });
6533 thread_view.update_in(cx, |thread_view, window, cx| {
6534 thread_view.send(window, cx);
6535 });
6536
6537 cx.run_until_parked();
6538
6539 let user_message_editor = thread_view.read_with(cx, |view, cx| {
6540 assert_eq!(view.editing_message, None);
6541 assert_eq!(view.thread().unwrap().read(cx).entries().len(), 2);
6542
6543 view.entry_view_state
6544 .read(cx)
6545 .entry(0)
6546 .unwrap()
6547 .message_editor()
6548 .unwrap()
6549 .clone()
6550 });
6551
6552 // Focus
6553 cx.focus(&user_message_editor);
6554
6555 // Edit
6556 user_message_editor.update_in(cx, |editor, window, cx| {
6557 editor.set_text("Edited message content", window, cx);
6558 });
6559
6560 // Send
6561 connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk {
6562 content: acp::ContentBlock::Text(acp::TextContent {
6563 text: "New Response".into(),
6564 annotations: None,
6565 meta: None,
6566 }),
6567 }]);
6568
6569 user_message_editor.update_in(cx, |_editor, window, cx| {
6570 window.dispatch_action(Box::new(Chat), cx);
6571 });
6572
6573 cx.run_until_parked();
6574
6575 thread_view.read_with(cx, |view, cx| {
6576 assert_eq!(view.editing_message, None);
6577
6578 let entries = view.thread().unwrap().read(cx).entries();
6579 assert_eq!(entries.len(), 2);
6580 assert_eq!(
6581 entries[0].to_markdown(cx),
6582 "## User\n\nEdited message content\n\n"
6583 );
6584 assert_eq!(
6585 entries[1].to_markdown(cx),
6586 "## Assistant\n\nNew Response\n\n"
6587 );
6588
6589 let new_editor = view.entry_view_state.read_with(cx, |state, _cx| {
6590 assert!(!state.entry(1).unwrap().has_content());
6591 state.entry(0).unwrap().message_editor().unwrap().clone()
6592 });
6593
6594 assert_eq!(new_editor.read(cx).text(cx), "Edited message content");
6595 })
6596 }
6597
6598 #[gpui::test]
6599 async fn test_message_editing_while_generating(cx: &mut TestAppContext) {
6600 init_test(cx);
6601
6602 let connection = StubAgentConnection::new();
6603
6604 let (thread_view, cx) =
6605 setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
6606 add_to_workspace(thread_view.clone(), cx);
6607
6608 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
6609 message_editor.update_in(cx, |editor, window, cx| {
6610 editor.set_text("Original message to edit", window, cx);
6611 });
6612 thread_view.update_in(cx, |thread_view, window, cx| {
6613 thread_view.send(window, cx);
6614 });
6615
6616 cx.run_until_parked();
6617
6618 let (user_message_editor, session_id) = thread_view.read_with(cx, |view, cx| {
6619 let thread = view.thread().unwrap().read(cx);
6620 assert_eq!(thread.entries().len(), 1);
6621
6622 let editor = view
6623 .entry_view_state
6624 .read(cx)
6625 .entry(0)
6626 .unwrap()
6627 .message_editor()
6628 .unwrap()
6629 .clone();
6630
6631 (editor, thread.session_id().clone())
6632 });
6633
6634 // Focus
6635 cx.focus(&user_message_editor);
6636
6637 thread_view.read_with(cx, |view, _cx| {
6638 assert_eq!(view.editing_message, Some(0));
6639 });
6640
6641 // Edit
6642 user_message_editor.update_in(cx, |editor, window, cx| {
6643 editor.set_text("Edited message content", window, cx);
6644 });
6645
6646 thread_view.read_with(cx, |view, _cx| {
6647 assert_eq!(view.editing_message, Some(0));
6648 });
6649
6650 // Finish streaming response
6651 cx.update(|_, cx| {
6652 connection.send_update(
6653 session_id.clone(),
6654 acp::SessionUpdate::AgentMessageChunk {
6655 content: acp::ContentBlock::Text(acp::TextContent {
6656 text: "Response".into(),
6657 annotations: None,
6658 meta: None,
6659 }),
6660 },
6661 cx,
6662 );
6663 connection.end_turn(session_id, acp::StopReason::EndTurn);
6664 });
6665
6666 thread_view.read_with(cx, |view, _cx| {
6667 assert_eq!(view.editing_message, Some(0));
6668 });
6669
6670 cx.run_until_parked();
6671
6672 // Should still be editing
6673 cx.update(|window, cx| {
6674 assert!(user_message_editor.focus_handle(cx).is_focused(window));
6675 assert_eq!(thread_view.read(cx).editing_message, Some(0));
6676 assert_eq!(
6677 user_message_editor.read(cx).text(cx),
6678 "Edited message content"
6679 );
6680 });
6681 }
6682
6683 #[gpui::test]
6684 async fn test_interrupt(cx: &mut TestAppContext) {
6685 init_test(cx);
6686
6687 let connection = StubAgentConnection::new();
6688
6689 let (thread_view, cx) =
6690 setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
6691 add_to_workspace(thread_view.clone(), cx);
6692
6693 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
6694 message_editor.update_in(cx, |editor, window, cx| {
6695 editor.set_text("Message 1", window, cx);
6696 });
6697 thread_view.update_in(cx, |thread_view, window, cx| {
6698 thread_view.send(window, cx);
6699 });
6700
6701 let (thread, session_id) = thread_view.read_with(cx, |view, cx| {
6702 let thread = view.thread().unwrap();
6703
6704 (thread.clone(), thread.read(cx).session_id().clone())
6705 });
6706
6707 cx.run_until_parked();
6708
6709 cx.update(|_, cx| {
6710 connection.send_update(
6711 session_id.clone(),
6712 acp::SessionUpdate::AgentMessageChunk {
6713 content: "Message 1 resp".into(),
6714 },
6715 cx,
6716 );
6717 });
6718
6719 cx.run_until_parked();
6720
6721 thread.read_with(cx, |thread, cx| {
6722 assert_eq!(
6723 thread.to_markdown(cx),
6724 indoc::indoc! {"
6725 ## User
6726
6727 Message 1
6728
6729 ## Assistant
6730
6731 Message 1 resp
6732
6733 "}
6734 )
6735 });
6736
6737 message_editor.update_in(cx, |editor, window, cx| {
6738 editor.set_text("Message 2", window, cx);
6739 });
6740 thread_view.update_in(cx, |thread_view, window, cx| {
6741 thread_view.send(window, cx);
6742 });
6743
6744 cx.update(|_, cx| {
6745 // Simulate a response sent after beginning to cancel
6746 connection.send_update(
6747 session_id.clone(),
6748 acp::SessionUpdate::AgentMessageChunk {
6749 content: "onse".into(),
6750 },
6751 cx,
6752 );
6753 });
6754
6755 cx.run_until_parked();
6756
6757 // Last Message 1 response should appear before Message 2
6758 thread.read_with(cx, |thread, cx| {
6759 assert_eq!(
6760 thread.to_markdown(cx),
6761 indoc::indoc! {"
6762 ## User
6763
6764 Message 1
6765
6766 ## Assistant
6767
6768 Message 1 response
6769
6770 ## User
6771
6772 Message 2
6773
6774 "}
6775 )
6776 });
6777
6778 cx.update(|_, cx| {
6779 connection.send_update(
6780 session_id.clone(),
6781 acp::SessionUpdate::AgentMessageChunk {
6782 content: "Message 2 response".into(),
6783 },
6784 cx,
6785 );
6786 connection.end_turn(session_id.clone(), acp::StopReason::EndTurn);
6787 });
6788
6789 cx.run_until_parked();
6790
6791 thread.read_with(cx, |thread, cx| {
6792 assert_eq!(
6793 thread.to_markdown(cx),
6794 indoc::indoc! {"
6795 ## User
6796
6797 Message 1
6798
6799 ## Assistant
6800
6801 Message 1 response
6802
6803 ## User
6804
6805 Message 2
6806
6807 ## Assistant
6808
6809 Message 2 response
6810
6811 "}
6812 )
6813 });
6814 }
6815
6816 #[gpui::test]
6817 async fn test_message_editing_insert_selections(cx: &mut TestAppContext) {
6818 init_test(cx);
6819
6820 let connection = StubAgentConnection::new();
6821 connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk {
6822 content: acp::ContentBlock::Text(acp::TextContent {
6823 text: "Response".into(),
6824 annotations: None,
6825 meta: None,
6826 }),
6827 }]);
6828
6829 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
6830 add_to_workspace(thread_view.clone(), cx);
6831
6832 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
6833 message_editor.update_in(cx, |editor, window, cx| {
6834 editor.set_text("Original message to edit", window, cx)
6835 });
6836 thread_view.update_in(cx, |thread_view, window, cx| thread_view.send(window, cx));
6837 cx.run_until_parked();
6838
6839 let user_message_editor = thread_view.read_with(cx, |thread_view, cx| {
6840 thread_view
6841 .entry_view_state
6842 .read(cx)
6843 .entry(0)
6844 .expect("Should have at least one entry")
6845 .message_editor()
6846 .expect("Should have message editor")
6847 .clone()
6848 });
6849
6850 cx.focus(&user_message_editor);
6851 thread_view.read_with(cx, |thread_view, _cx| {
6852 assert_eq!(thread_view.editing_message, Some(0));
6853 });
6854
6855 // Ensure to edit the focused message before proceeding otherwise, since
6856 // its content is not different from what was sent, focus will be lost.
6857 user_message_editor.update_in(cx, |editor, window, cx| {
6858 editor.set_text("Original message to edit with ", window, cx)
6859 });
6860
6861 // Create a simple buffer with some text so we can create a selection
6862 // that will then be added to the message being edited.
6863 let (workspace, project) = thread_view.read_with(cx, |thread_view, _cx| {
6864 (thread_view.workspace.clone(), thread_view.project.clone())
6865 });
6866 let buffer = project.update(cx, |project, cx| {
6867 project.create_local_buffer("let a = 10 + 10;", None, false, cx)
6868 });
6869
6870 workspace
6871 .update_in(cx, |workspace, window, cx| {
6872 let editor = cx.new(|cx| {
6873 let mut editor =
6874 Editor::for_buffer(buffer.clone(), Some(project.clone()), window, cx);
6875
6876 editor.change_selections(Default::default(), window, cx, |selections| {
6877 selections.select_ranges([8..15]);
6878 });
6879
6880 editor
6881 });
6882 workspace.add_item_to_active_pane(Box::new(editor), None, false, window, cx);
6883 })
6884 .unwrap();
6885
6886 thread_view.update_in(cx, |thread_view, window, cx| {
6887 assert_eq!(thread_view.editing_message, Some(0));
6888 thread_view.insert_selections(window, cx);
6889 });
6890
6891 user_message_editor.read_with(cx, |editor, cx| {
6892 let text = editor.editor().read(cx).text(cx);
6893 let expected_text = String::from("Original message to edit with selection ");
6894
6895 assert_eq!(text, expected_text);
6896 });
6897 }
6898
6899 #[gpui::test]
6900 async fn test_insert_selections(cx: &mut TestAppContext) {
6901 init_test(cx);
6902
6903 let connection = StubAgentConnection::new();
6904 connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk {
6905 content: acp::ContentBlock::Text(acp::TextContent {
6906 text: "Response".into(),
6907 annotations: None,
6908 meta: None,
6909 }),
6910 }]);
6911
6912 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
6913 add_to_workspace(thread_view.clone(), cx);
6914
6915 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
6916 message_editor.update_in(cx, |editor, window, cx| {
6917 editor.set_text("Can you review this snippet ", window, cx)
6918 });
6919
6920 // Create a simple buffer with some text so we can create a selection
6921 // that will then be added to the message being edited.
6922 let (workspace, project) = thread_view.read_with(cx, |thread_view, _cx| {
6923 (thread_view.workspace.clone(), thread_view.project.clone())
6924 });
6925 let buffer = project.update(cx, |project, cx| {
6926 project.create_local_buffer("let a = 10 + 10;", None, false, cx)
6927 });
6928
6929 workspace
6930 .update_in(cx, |workspace, window, cx| {
6931 let editor = cx.new(|cx| {
6932 let mut editor =
6933 Editor::for_buffer(buffer.clone(), Some(project.clone()), window, cx);
6934
6935 editor.change_selections(Default::default(), window, cx, |selections| {
6936 selections.select_ranges([8..15]);
6937 });
6938
6939 editor
6940 });
6941 workspace.add_item_to_active_pane(Box::new(editor), None, false, window, cx);
6942 })
6943 .unwrap();
6944
6945 thread_view.update_in(cx, |thread_view, window, cx| {
6946 assert_eq!(thread_view.editing_message, None);
6947 thread_view.insert_selections(window, cx);
6948 });
6949
6950 thread_view.read_with(cx, |thread_view, cx| {
6951 let text = thread_view.message_editor.read(cx).text(cx);
6952 let expected_txt = String::from("Can you review this snippet selection ");
6953
6954 assert_eq!(text, expected_txt);
6955 })
6956 }
6957}