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