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