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