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