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