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 .p_2()
4292 .gap_2()
4293 .border_t_1()
4294 .border_color(cx.theme().colors().border)
4295 .bg(editor_bg_color)
4296 .when(self.editor_expanded, |this| {
4297 this.h(vh(0.8, window)).size_full().justify_between()
4298 })
4299 .child(
4300 v_flex()
4301 .relative()
4302 .size_full()
4303 .pt_1()
4304 .pr_2p5()
4305 .child(self.message_editor.clone())
4306 .child(
4307 h_flex()
4308 .absolute()
4309 .top_0()
4310 .right_0()
4311 .opacity(0.5)
4312 .hover(|this| this.opacity(1.0))
4313 .child(
4314 IconButton::new("toggle-height", expand_icon)
4315 .icon_size(IconSize::Small)
4316 .icon_color(Color::Muted)
4317 .tooltip({
4318 move |_window, cx| {
4319 Tooltip::for_action_in(
4320 expand_tooltip,
4321 &ExpandMessageEditor,
4322 &focus_handle,
4323 cx,
4324 )
4325 }
4326 })
4327 .on_click(cx.listener(|this, _, window, cx| {
4328 this.expand_message_editor(
4329 &ExpandMessageEditor,
4330 window,
4331 cx,
4332 );
4333 })),
4334 ),
4335 ),
4336 )
4337 .child(
4338 h_flex()
4339 .flex_none()
4340 .flex_wrap()
4341 .justify_between()
4342 .child(
4343 h_flex()
4344 .gap_0p5()
4345 .child(self.render_add_context_button(cx))
4346 .child(self.render_follow_toggle(cx))
4347 .children(self.render_burn_mode_toggle(cx)),
4348 )
4349 .child(
4350 h_flex()
4351 .gap_1()
4352 .children(self.render_token_usage(cx))
4353 .children(self.profile_selector.clone())
4354 .children(self.mode_selector().cloned())
4355 .children(self.model_selector.clone())
4356 .child(self.render_send_button(cx)),
4357 ),
4358 )
4359 .when(!enable_editor, |this| this.child(backdrop))
4360 .into_any()
4361 }
4362
4363 pub(crate) fn as_native_connection(
4364 &self,
4365 cx: &App,
4366 ) -> Option<Rc<agent::NativeAgentConnection>> {
4367 let acp_thread = self.thread()?.read(cx);
4368 acp_thread.connection().clone().downcast()
4369 }
4370
4371 pub(crate) fn as_native_thread(&self, cx: &App) -> Option<Entity<agent::Thread>> {
4372 let acp_thread = self.thread()?.read(cx);
4373 self.as_native_connection(cx)?
4374 .thread(acp_thread.session_id(), cx)
4375 }
4376
4377 fn is_using_zed_ai_models(&self, cx: &App) -> bool {
4378 self.as_native_thread(cx)
4379 .and_then(|thread| thread.read(cx).model())
4380 .is_some_and(|model| model.provider_id() == language_model::ZED_CLOUD_PROVIDER_ID)
4381 }
4382
4383 fn render_token_usage(&self, cx: &mut Context<Self>) -> Option<Div> {
4384 let thread = self.thread()?.read(cx);
4385 let usage = thread.token_usage()?;
4386 let is_generating = thread.status() != ThreadStatus::Idle;
4387
4388 let used = crate::text_thread_editor::humanize_token_count(usage.used_tokens);
4389 let max = crate::text_thread_editor::humanize_token_count(usage.max_tokens);
4390
4391 Some(
4392 h_flex()
4393 .flex_shrink_0()
4394 .gap_0p5()
4395 .mr_1p5()
4396 .child(
4397 Label::new(used)
4398 .size(LabelSize::Small)
4399 .color(Color::Muted)
4400 .map(|label| {
4401 if is_generating {
4402 label
4403 .with_animation(
4404 "used-tokens-label",
4405 Animation::new(Duration::from_secs(2))
4406 .repeat()
4407 .with_easing(pulsating_between(0.3, 0.8)),
4408 |label, delta| label.alpha(delta),
4409 )
4410 .into_any()
4411 } else {
4412 label.into_any_element()
4413 }
4414 }),
4415 )
4416 .child(
4417 Label::new("/")
4418 .size(LabelSize::Small)
4419 .color(Color::Custom(cx.theme().colors().text_muted.opacity(0.5))),
4420 )
4421 .child(Label::new(max).size(LabelSize::Small).color(Color::Muted)),
4422 )
4423 }
4424
4425 fn toggle_burn_mode(
4426 &mut self,
4427 _: &ToggleBurnMode,
4428 _window: &mut Window,
4429 cx: &mut Context<Self>,
4430 ) {
4431 let Some(thread) = self.as_native_thread(cx) else {
4432 return;
4433 };
4434
4435 thread.update(cx, |thread, cx| {
4436 let current_mode = thread.completion_mode();
4437 thread.set_completion_mode(
4438 match current_mode {
4439 CompletionMode::Burn => CompletionMode::Normal,
4440 CompletionMode::Normal => CompletionMode::Burn,
4441 },
4442 cx,
4443 );
4444 });
4445 }
4446
4447 fn keep_all(&mut self, _: &KeepAll, _window: &mut Window, cx: &mut Context<Self>) {
4448 let Some(thread) = self.thread() else {
4449 return;
4450 };
4451 let telemetry = ActionLogTelemetry::from(thread.read(cx));
4452 let action_log = thread.read(cx).action_log().clone();
4453 action_log.update(cx, |action_log, cx| {
4454 action_log.keep_all_edits(Some(telemetry), cx)
4455 });
4456 }
4457
4458 fn reject_all(&mut self, _: &RejectAll, _window: &mut Window, cx: &mut Context<Self>) {
4459 let Some(thread) = self.thread() else {
4460 return;
4461 };
4462 let telemetry = ActionLogTelemetry::from(thread.read(cx));
4463 let action_log = thread.read(cx).action_log().clone();
4464 action_log
4465 .update(cx, |action_log, cx| {
4466 action_log.reject_all_edits(Some(telemetry), cx)
4467 })
4468 .detach();
4469 }
4470
4471 fn allow_always(&mut self, _: &AllowAlways, window: &mut Window, cx: &mut Context<Self>) {
4472 self.authorize_pending_tool_call(acp::PermissionOptionKind::AllowAlways, window, cx);
4473 }
4474
4475 fn allow_once(&mut self, _: &AllowOnce, window: &mut Window, cx: &mut Context<Self>) {
4476 self.authorize_pending_tool_call(acp::PermissionOptionKind::AllowOnce, window, cx);
4477 }
4478
4479 fn reject_once(&mut self, _: &RejectOnce, window: &mut Window, cx: &mut Context<Self>) {
4480 self.authorize_pending_tool_call(acp::PermissionOptionKind::RejectOnce, window, cx);
4481 }
4482
4483 fn authorize_pending_tool_call(
4484 &mut self,
4485 kind: acp::PermissionOptionKind,
4486 window: &mut Window,
4487 cx: &mut Context<Self>,
4488 ) -> Option<()> {
4489 let thread = self.thread()?.read(cx);
4490 let tool_call = thread.first_tool_awaiting_confirmation()?;
4491 let ToolCallStatus::WaitingForConfirmation { options, .. } = &tool_call.status else {
4492 return None;
4493 };
4494 let option = options.iter().find(|o| o.kind == kind)?;
4495
4496 self.authorize_tool_call(
4497 tool_call.id.clone(),
4498 option.option_id.clone(),
4499 option.kind,
4500 window,
4501 cx,
4502 );
4503
4504 Some(())
4505 }
4506
4507 fn render_burn_mode_toggle(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
4508 let thread = self.as_native_thread(cx)?.read(cx);
4509
4510 if thread
4511 .model()
4512 .is_none_or(|model| !model.supports_burn_mode())
4513 {
4514 return None;
4515 }
4516
4517 let active_completion_mode = thread.completion_mode();
4518 let burn_mode_enabled = active_completion_mode == CompletionMode::Burn;
4519 let icon = if burn_mode_enabled {
4520 IconName::ZedBurnModeOn
4521 } else {
4522 IconName::ZedBurnMode
4523 };
4524
4525 Some(
4526 IconButton::new("burn-mode", icon)
4527 .icon_size(IconSize::Small)
4528 .icon_color(Color::Muted)
4529 .toggle_state(burn_mode_enabled)
4530 .selected_icon_color(Color::Error)
4531 .on_click(cx.listener(|this, _event, window, cx| {
4532 this.toggle_burn_mode(&ToggleBurnMode, window, cx);
4533 }))
4534 .tooltip(move |_window, cx| {
4535 cx.new(|_| BurnModeTooltip::new().selected(burn_mode_enabled))
4536 .into()
4537 })
4538 .into_any_element(),
4539 )
4540 }
4541
4542 fn render_send_button(&self, cx: &mut Context<Self>) -> AnyElement {
4543 let is_editor_empty = self.message_editor.read(cx).is_empty(cx);
4544 let is_generating = self
4545 .thread()
4546 .is_some_and(|thread| thread.read(cx).status() != ThreadStatus::Idle);
4547
4548 if self.is_loading_contents {
4549 div()
4550 .id("loading-message-content")
4551 .px_1()
4552 .tooltip(Tooltip::text("Loading Added Context…"))
4553 .child(loading_contents_spinner(IconSize::default()))
4554 .into_any_element()
4555 } else if is_generating && is_editor_empty {
4556 IconButton::new("stop-generation", IconName::Stop)
4557 .icon_color(Color::Error)
4558 .style(ButtonStyle::Tinted(ui::TintColor::Error))
4559 .tooltip(move |_window, cx| {
4560 Tooltip::for_action("Stop Generation", &editor::actions::Cancel, cx)
4561 })
4562 .on_click(cx.listener(|this, _event, _, cx| this.cancel_generation(cx)))
4563 .into_any_element()
4564 } else {
4565 let send_btn_tooltip = if is_editor_empty && !is_generating {
4566 "Type to Send"
4567 } else if is_generating {
4568 "Stop and Send Message"
4569 } else {
4570 "Send"
4571 };
4572
4573 IconButton::new("send-message", IconName::Send)
4574 .style(ButtonStyle::Filled)
4575 .map(|this| {
4576 if is_editor_empty && !is_generating {
4577 this.disabled(true).icon_color(Color::Muted)
4578 } else {
4579 this.icon_color(Color::Accent)
4580 }
4581 })
4582 .tooltip(move |_window, cx| Tooltip::for_action(send_btn_tooltip, &Chat, cx))
4583 .on_click(cx.listener(|this, _, window, cx| {
4584 this.send(window, cx);
4585 }))
4586 .into_any_element()
4587 }
4588 }
4589
4590 fn is_following(&self, cx: &App) -> bool {
4591 match self.thread().map(|thread| thread.read(cx).status()) {
4592 Some(ThreadStatus::Generating) => self
4593 .workspace
4594 .read_with(cx, |workspace, _| {
4595 workspace.is_being_followed(CollaboratorId::Agent)
4596 })
4597 .unwrap_or(false),
4598 _ => self.should_be_following,
4599 }
4600 }
4601
4602 fn toggle_following(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4603 let following = self.is_following(cx);
4604
4605 self.should_be_following = !following;
4606 if self.thread().map(|thread| thread.read(cx).status()) == Some(ThreadStatus::Generating) {
4607 self.workspace
4608 .update(cx, |workspace, cx| {
4609 if following {
4610 workspace.unfollow(CollaboratorId::Agent, window, cx);
4611 } else {
4612 workspace.follow(CollaboratorId::Agent, window, cx);
4613 }
4614 })
4615 .ok();
4616 }
4617
4618 telemetry::event!("Follow Agent Selected", following = !following);
4619 }
4620
4621 fn render_follow_toggle(&self, cx: &mut Context<Self>) -> impl IntoElement {
4622 let following = self.is_following(cx);
4623
4624 let tooltip_label = if following {
4625 if self.agent.name() == "Zed Agent" {
4626 format!("Stop Following the {}", self.agent.name())
4627 } else {
4628 format!("Stop Following {}", self.agent.name())
4629 }
4630 } else {
4631 if self.agent.name() == "Zed Agent" {
4632 format!("Follow the {}", self.agent.name())
4633 } else {
4634 format!("Follow {}", self.agent.name())
4635 }
4636 };
4637
4638 IconButton::new("follow-agent", IconName::Crosshair)
4639 .icon_size(IconSize::Small)
4640 .icon_color(Color::Muted)
4641 .toggle_state(following)
4642 .selected_icon_color(Some(Color::Custom(cx.theme().players().agent().cursor)))
4643 .tooltip(move |_window, cx| {
4644 if following {
4645 Tooltip::for_action(tooltip_label.clone(), &Follow, cx)
4646 } else {
4647 Tooltip::with_meta(
4648 tooltip_label.clone(),
4649 Some(&Follow),
4650 "Track the agent's location as it reads and edits files.",
4651 cx,
4652 )
4653 }
4654 })
4655 .on_click(cx.listener(move |this, _, window, cx| {
4656 this.toggle_following(window, cx);
4657 }))
4658 }
4659
4660 fn render_add_context_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
4661 let message_editor = self.message_editor.clone();
4662 let menu_visible = message_editor.read(cx).is_completions_menu_visible(cx);
4663
4664 IconButton::new("add-context", IconName::AtSign)
4665 .icon_size(IconSize::Small)
4666 .icon_color(Color::Muted)
4667 .when(!menu_visible, |this| {
4668 this.tooltip(move |_window, cx| {
4669 Tooltip::with_meta("Add Context", None, "Or type @ to include context", cx)
4670 })
4671 })
4672 .on_click(cx.listener(move |_this, _, window, cx| {
4673 let message_editor_clone = message_editor.clone();
4674
4675 window.defer(cx, move |window, cx| {
4676 message_editor_clone.update(cx, |message_editor, cx| {
4677 message_editor.trigger_completion_menu(window, cx);
4678 });
4679 });
4680 }))
4681 }
4682
4683 fn render_markdown(&self, markdown: Entity<Markdown>, style: MarkdownStyle) -> MarkdownElement {
4684 let workspace = self.workspace.clone();
4685 MarkdownElement::new(markdown, style).on_url_click(move |text, window, cx| {
4686 Self::open_link(text, &workspace, window, cx);
4687 })
4688 }
4689
4690 fn open_link(
4691 url: SharedString,
4692 workspace: &WeakEntity<Workspace>,
4693 window: &mut Window,
4694 cx: &mut App,
4695 ) {
4696 let Some(workspace) = workspace.upgrade() else {
4697 cx.open_url(&url);
4698 return;
4699 };
4700
4701 if let Some(mention) = MentionUri::parse(&url, workspace.read(cx).path_style(cx)).log_err()
4702 {
4703 workspace.update(cx, |workspace, cx| match mention {
4704 MentionUri::File { abs_path } => {
4705 let project = workspace.project();
4706 let Some(path) =
4707 project.update(cx, |project, cx| project.find_project_path(abs_path, cx))
4708 else {
4709 return;
4710 };
4711
4712 workspace
4713 .open_path(path, None, true, window, cx)
4714 .detach_and_log_err(cx);
4715 }
4716 MentionUri::PastedImage => {}
4717 MentionUri::Directory { abs_path } => {
4718 let project = workspace.project();
4719 let Some(entry_id) = project.update(cx, |project, cx| {
4720 let path = project.find_project_path(abs_path, cx)?;
4721 project.entry_for_path(&path, cx).map(|entry| entry.id)
4722 }) else {
4723 return;
4724 };
4725
4726 project.update(cx, |_, cx| {
4727 cx.emit(project::Event::RevealInProjectPanel(entry_id));
4728 });
4729 }
4730 MentionUri::Symbol {
4731 abs_path: path,
4732 line_range,
4733 ..
4734 }
4735 | MentionUri::Selection {
4736 abs_path: Some(path),
4737 line_range,
4738 } => {
4739 let project = workspace.project();
4740 let Some(path) =
4741 project.update(cx, |project, cx| project.find_project_path(path, cx))
4742 else {
4743 return;
4744 };
4745
4746 let item = workspace.open_path(path, None, true, window, cx);
4747 window
4748 .spawn(cx, async move |cx| {
4749 let Some(editor) = item.await?.downcast::<Editor>() else {
4750 return Ok(());
4751 };
4752 let range = Point::new(*line_range.start(), 0)
4753 ..Point::new(*line_range.start(), 0);
4754 editor
4755 .update_in(cx, |editor, window, cx| {
4756 editor.change_selections(
4757 SelectionEffects::scroll(Autoscroll::center()),
4758 window,
4759 cx,
4760 |s| s.select_ranges(vec![range]),
4761 );
4762 })
4763 .ok();
4764 anyhow::Ok(())
4765 })
4766 .detach_and_log_err(cx);
4767 }
4768 MentionUri::Selection { abs_path: None, .. } => {}
4769 MentionUri::Thread { id, name } => {
4770 if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
4771 panel.update(cx, |panel, cx| {
4772 panel.load_agent_thread(
4773 DbThreadMetadata {
4774 id,
4775 title: name.into(),
4776 updated_at: Default::default(),
4777 },
4778 window,
4779 cx,
4780 )
4781 });
4782 }
4783 }
4784 MentionUri::TextThread { path, .. } => {
4785 if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
4786 panel.update(cx, |panel, cx| {
4787 panel
4788 .open_saved_text_thread(path.as_path().into(), window, cx)
4789 .detach_and_log_err(cx);
4790 });
4791 }
4792 }
4793 MentionUri::Rule { id, .. } => {
4794 let PromptId::User { uuid } = id else {
4795 return;
4796 };
4797 window.dispatch_action(
4798 Box::new(OpenRulesLibrary {
4799 prompt_to_select: Some(uuid.0),
4800 }),
4801 cx,
4802 )
4803 }
4804 MentionUri::Fetch { url } => {
4805 cx.open_url(url.as_str());
4806 }
4807 })
4808 } else {
4809 cx.open_url(&url);
4810 }
4811 }
4812
4813 fn open_tool_call_location(
4814 &self,
4815 entry_ix: usize,
4816 location_ix: usize,
4817 window: &mut Window,
4818 cx: &mut Context<Self>,
4819 ) -> Option<()> {
4820 let (tool_call_location, agent_location) = self
4821 .thread()?
4822 .read(cx)
4823 .entries()
4824 .get(entry_ix)?
4825 .location(location_ix)?;
4826
4827 let project_path = self
4828 .project
4829 .read(cx)
4830 .find_project_path(&tool_call_location.path, cx)?;
4831
4832 let open_task = self
4833 .workspace
4834 .update(cx, |workspace, cx| {
4835 workspace.open_path(project_path, None, true, window, cx)
4836 })
4837 .log_err()?;
4838 window
4839 .spawn(cx, async move |cx| {
4840 let item = open_task.await?;
4841
4842 let Some(active_editor) = item.downcast::<Editor>() else {
4843 return anyhow::Ok(());
4844 };
4845
4846 active_editor.update_in(cx, |editor, window, cx| {
4847 let multibuffer = editor.buffer().read(cx);
4848 let buffer = multibuffer.as_singleton();
4849 if agent_location.buffer.upgrade() == buffer {
4850 let excerpt_id = multibuffer.excerpt_ids().first().cloned();
4851 let anchor =
4852 editor::Anchor::in_buffer(excerpt_id.unwrap(), agent_location.position);
4853 editor.change_selections(Default::default(), window, cx, |selections| {
4854 selections.select_anchor_ranges([anchor..anchor]);
4855 })
4856 } else {
4857 let row = tool_call_location.line.unwrap_or_default();
4858 editor.change_selections(Default::default(), window, cx, |selections| {
4859 selections.select_ranges([Point::new(row, 0)..Point::new(row, 0)]);
4860 })
4861 }
4862 })?;
4863
4864 anyhow::Ok(())
4865 })
4866 .detach_and_log_err(cx);
4867
4868 None
4869 }
4870
4871 pub fn open_thread_as_markdown(
4872 &self,
4873 workspace: Entity<Workspace>,
4874 window: &mut Window,
4875 cx: &mut App,
4876 ) -> Task<Result<()>> {
4877 let markdown_language_task = workspace
4878 .read(cx)
4879 .app_state()
4880 .languages
4881 .language_for_name("Markdown");
4882
4883 let (thread_title, markdown) = if let Some(thread) = self.thread() {
4884 let thread = thread.read(cx);
4885 (thread.title().to_string(), thread.to_markdown(cx))
4886 } else {
4887 return Task::ready(Ok(()));
4888 };
4889
4890 let project = workspace.read(cx).project().clone();
4891 window.spawn(cx, async move |cx| {
4892 let markdown_language = markdown_language_task.await?;
4893
4894 let buffer = project
4895 .update(cx, |project, cx| project.create_buffer(false, cx))?
4896 .await?;
4897
4898 buffer.update(cx, |buffer, cx| {
4899 buffer.set_text(markdown, cx);
4900 buffer.set_language(Some(markdown_language), cx);
4901 buffer.set_capability(language::Capability::ReadWrite, cx);
4902 })?;
4903
4904 workspace.update_in(cx, |workspace, window, cx| {
4905 let buffer = cx
4906 .new(|cx| MultiBuffer::singleton(buffer, cx).with_title(thread_title.clone()));
4907
4908 workspace.add_item_to_active_pane(
4909 Box::new(cx.new(|cx| {
4910 let mut editor =
4911 Editor::for_multibuffer(buffer, Some(project.clone()), window, cx);
4912 editor.set_breadcrumb_header(thread_title);
4913 editor
4914 })),
4915 None,
4916 true,
4917 window,
4918 cx,
4919 );
4920 })?;
4921 anyhow::Ok(())
4922 })
4923 }
4924
4925 fn scroll_to_top(&mut self, cx: &mut Context<Self>) {
4926 self.list_state.scroll_to(ListOffset::default());
4927 cx.notify();
4928 }
4929
4930 fn scroll_to_most_recent_user_prompt(&mut self, cx: &mut Context<Self>) {
4931 let Some(thread) = self.thread() else {
4932 return;
4933 };
4934
4935 let entries = thread.read(cx).entries();
4936 if entries.is_empty() {
4937 return;
4938 }
4939
4940 // Find the most recent user message and scroll it to the top of the viewport.
4941 // (Fallback: if no user message exists, scroll to the bottom.)
4942 if let Some(ix) = entries
4943 .iter()
4944 .rposition(|entry| matches!(entry, AgentThreadEntry::UserMessage(_)))
4945 {
4946 self.list_state.scroll_to(ListOffset {
4947 item_ix: ix,
4948 offset_in_item: px(0.0),
4949 });
4950 cx.notify();
4951 } else {
4952 self.scroll_to_bottom(cx);
4953 }
4954 }
4955
4956 pub fn scroll_to_bottom(&mut self, cx: &mut Context<Self>) {
4957 if let Some(thread) = self.thread() {
4958 let entry_count = thread.read(cx).entries().len();
4959 self.list_state.reset(entry_count);
4960 cx.notify();
4961 }
4962 }
4963
4964 fn notify_with_sound(
4965 &mut self,
4966 caption: impl Into<SharedString>,
4967 icon: IconName,
4968 window: &mut Window,
4969 cx: &mut Context<Self>,
4970 ) {
4971 self.play_notification_sound(window, cx);
4972 self.show_notification(caption, icon, window, cx);
4973 }
4974
4975 fn play_notification_sound(&self, window: &Window, cx: &mut App) {
4976 let settings = AgentSettings::get_global(cx);
4977 if settings.play_sound_when_agent_done && !window.is_window_active() {
4978 Audio::play_sound(Sound::AgentDone, cx);
4979 }
4980 }
4981
4982 fn show_notification(
4983 &mut self,
4984 caption: impl Into<SharedString>,
4985 icon: IconName,
4986 window: &mut Window,
4987 cx: &mut Context<Self>,
4988 ) {
4989 if !self.notifications.is_empty() {
4990 return;
4991 }
4992
4993 let settings = AgentSettings::get_global(cx);
4994
4995 let window_is_inactive = !window.is_window_active();
4996 let panel_is_hidden = self
4997 .workspace
4998 .upgrade()
4999 .map(|workspace| AgentPanel::is_hidden(&workspace, cx))
5000 .unwrap_or(true);
5001
5002 let should_notify = window_is_inactive || panel_is_hidden;
5003
5004 if !should_notify {
5005 return;
5006 }
5007
5008 // TODO: Change this once we have title summarization for external agents.
5009 let title = self.agent.name();
5010
5011 match settings.notify_when_agent_waiting {
5012 NotifyWhenAgentWaiting::PrimaryScreen => {
5013 if let Some(primary) = cx.primary_display() {
5014 self.pop_up(icon, caption.into(), title, window, primary, cx);
5015 }
5016 }
5017 NotifyWhenAgentWaiting::AllScreens => {
5018 let caption = caption.into();
5019 for screen in cx.displays() {
5020 self.pop_up(icon, caption.clone(), title.clone(), window, screen, cx);
5021 }
5022 }
5023 NotifyWhenAgentWaiting::Never => {
5024 // Don't show anything
5025 }
5026 }
5027 }
5028
5029 fn pop_up(
5030 &mut self,
5031 icon: IconName,
5032 caption: SharedString,
5033 title: SharedString,
5034 window: &mut Window,
5035 screen: Rc<dyn PlatformDisplay>,
5036 cx: &mut Context<Self>,
5037 ) {
5038 let options = AgentNotification::window_options(screen, cx);
5039
5040 let project_name = self.workspace.upgrade().and_then(|workspace| {
5041 workspace
5042 .read(cx)
5043 .project()
5044 .read(cx)
5045 .visible_worktrees(cx)
5046 .next()
5047 .map(|worktree| worktree.read(cx).root_name_str().to_string())
5048 });
5049
5050 if let Some(screen_window) = cx
5051 .open_window(options, |_window, cx| {
5052 cx.new(|_cx| {
5053 AgentNotification::new(title.clone(), caption.clone(), icon, project_name)
5054 })
5055 })
5056 .log_err()
5057 && let Some(pop_up) = screen_window.entity(cx).log_err()
5058 {
5059 self.notification_subscriptions
5060 .entry(screen_window)
5061 .or_insert_with(Vec::new)
5062 .push(cx.subscribe_in(&pop_up, window, {
5063 |this, _, event, window, cx| match event {
5064 AgentNotificationEvent::Accepted => {
5065 let handle = window.window_handle();
5066 cx.activate(true);
5067
5068 let workspace_handle = this.workspace.clone();
5069
5070 // If there are multiple Zed windows, activate the correct one.
5071 cx.defer(move |cx| {
5072 handle
5073 .update(cx, |_view, window, _cx| {
5074 window.activate_window();
5075
5076 if let Some(workspace) = workspace_handle.upgrade() {
5077 workspace.update(_cx, |workspace, cx| {
5078 workspace.focus_panel::<AgentPanel>(window, cx);
5079 });
5080 }
5081 })
5082 .log_err();
5083 });
5084
5085 this.dismiss_notifications(cx);
5086 }
5087 AgentNotificationEvent::Dismissed => {
5088 this.dismiss_notifications(cx);
5089 }
5090 }
5091 }));
5092
5093 self.notifications.push(screen_window);
5094
5095 // If the user manually refocuses the original window, dismiss the popup.
5096 self.notification_subscriptions
5097 .entry(screen_window)
5098 .or_insert_with(Vec::new)
5099 .push({
5100 let pop_up_weak = pop_up.downgrade();
5101
5102 cx.observe_window_activation(window, move |_, window, cx| {
5103 if window.is_window_active()
5104 && let Some(pop_up) = pop_up_weak.upgrade()
5105 {
5106 pop_up.update(cx, |_, cx| {
5107 cx.emit(AgentNotificationEvent::Dismissed);
5108 });
5109 }
5110 })
5111 });
5112 }
5113 }
5114
5115 fn dismiss_notifications(&mut self, cx: &mut Context<Self>) {
5116 for window in self.notifications.drain(..) {
5117 window
5118 .update(cx, |_, window, _| {
5119 window.remove_window();
5120 })
5121 .ok();
5122
5123 self.notification_subscriptions.remove(&window);
5124 }
5125 }
5126
5127 fn render_generating(&self, confirmation: bool) -> impl IntoElement {
5128 h_flex()
5129 .id("generating-spinner")
5130 .py_2()
5131 .px(rems_from_px(22.))
5132 .map(|this| {
5133 if confirmation {
5134 this.gap_2()
5135 .child(
5136 h_flex()
5137 .w_2()
5138 .child(SpinnerLabel::sand().size(LabelSize::Small)),
5139 )
5140 .child(
5141 LoadingLabel::new("Waiting Confirmation")
5142 .size(LabelSize::Small)
5143 .color(Color::Muted),
5144 )
5145 } else {
5146 this.child(SpinnerLabel::new().size(LabelSize::Small))
5147 }
5148 })
5149 .into_any_element()
5150 }
5151
5152 fn render_thread_controls(
5153 &self,
5154 thread: &Entity<AcpThread>,
5155 cx: &Context<Self>,
5156 ) -> impl IntoElement {
5157 let is_generating = matches!(thread.read(cx).status(), ThreadStatus::Generating);
5158 if is_generating {
5159 return self.render_generating(false).into_any_element();
5160 }
5161
5162 let open_as_markdown = IconButton::new("open-as-markdown", IconName::FileMarkdown)
5163 .shape(ui::IconButtonShape::Square)
5164 .icon_size(IconSize::Small)
5165 .icon_color(Color::Ignored)
5166 .tooltip(Tooltip::text("Open Thread as Markdown"))
5167 .on_click(cx.listener(move |this, _, window, cx| {
5168 if let Some(workspace) = this.workspace.upgrade() {
5169 this.open_thread_as_markdown(workspace, window, cx)
5170 .detach_and_log_err(cx);
5171 }
5172 }));
5173
5174 let scroll_to_recent_user_prompt =
5175 IconButton::new("scroll_to_recent_user_prompt", IconName::ForwardArrow)
5176 .shape(ui::IconButtonShape::Square)
5177 .icon_size(IconSize::Small)
5178 .icon_color(Color::Ignored)
5179 .tooltip(Tooltip::text("Scroll To Most Recent User Prompt"))
5180 .on_click(cx.listener(move |this, _, _, cx| {
5181 this.scroll_to_most_recent_user_prompt(cx);
5182 }));
5183
5184 let scroll_to_top = IconButton::new("scroll_to_top", IconName::ArrowUp)
5185 .shape(ui::IconButtonShape::Square)
5186 .icon_size(IconSize::Small)
5187 .icon_color(Color::Ignored)
5188 .tooltip(Tooltip::text("Scroll To Top"))
5189 .on_click(cx.listener(move |this, _, _, cx| {
5190 this.scroll_to_top(cx);
5191 }));
5192
5193 let mut container = h_flex()
5194 .w_full()
5195 .py_2()
5196 .px_5()
5197 .gap_px()
5198 .opacity(0.6)
5199 .hover(|s| s.opacity(1.))
5200 .justify_end();
5201
5202 if AgentSettings::get_global(cx).enable_feedback
5203 && self
5204 .thread()
5205 .is_some_and(|thread| thread.read(cx).connection().telemetry().is_some())
5206 {
5207 let feedback = self.thread_feedback.feedback;
5208
5209 let tooltip_meta = || {
5210 SharedString::new(
5211 "Rating the thread sends all of your current conversation to the Zed team.",
5212 )
5213 };
5214
5215 container = container
5216 .child(
5217 IconButton::new("feedback-thumbs-up", IconName::ThumbsUp)
5218 .shape(ui::IconButtonShape::Square)
5219 .icon_size(IconSize::Small)
5220 .icon_color(match feedback {
5221 Some(ThreadFeedback::Positive) => Color::Accent,
5222 _ => Color::Ignored,
5223 })
5224 .tooltip(move |window, cx| match feedback {
5225 Some(ThreadFeedback::Positive) => {
5226 Tooltip::text("Thanks for your feedback!")(window, cx)
5227 }
5228 _ => Tooltip::with_meta("Helpful Response", None, tooltip_meta(), cx),
5229 })
5230 .on_click(cx.listener(move |this, _, window, cx| {
5231 this.handle_feedback_click(ThreadFeedback::Positive, window, cx);
5232 })),
5233 )
5234 .child(
5235 IconButton::new("feedback-thumbs-down", IconName::ThumbsDown)
5236 .shape(ui::IconButtonShape::Square)
5237 .icon_size(IconSize::Small)
5238 .icon_color(match feedback {
5239 Some(ThreadFeedback::Negative) => Color::Accent,
5240 _ => Color::Ignored,
5241 })
5242 .tooltip(move |window, cx| match feedback {
5243 Some(ThreadFeedback::Negative) => {
5244 Tooltip::text(
5245 "We appreciate your feedback and will use it to improve in the future.",
5246 )(window, cx)
5247 }
5248 _ => {
5249 Tooltip::with_meta("Not Helpful Response", None, tooltip_meta(), cx)
5250 }
5251 })
5252 .on_click(cx.listener(move |this, _, window, cx| {
5253 this.handle_feedback_click(ThreadFeedback::Negative, window, cx);
5254 })),
5255 );
5256 }
5257
5258 container
5259 .child(open_as_markdown)
5260 .child(scroll_to_recent_user_prompt)
5261 .child(scroll_to_top)
5262 .into_any_element()
5263 }
5264
5265 fn render_feedback_feedback_editor(editor: Entity<Editor>, cx: &Context<Self>) -> Div {
5266 h_flex()
5267 .key_context("AgentFeedbackMessageEditor")
5268 .on_action(cx.listener(move |this, _: &menu::Cancel, _, cx| {
5269 this.thread_feedback.dismiss_comments();
5270 cx.notify();
5271 }))
5272 .on_action(cx.listener(move |this, _: &menu::Confirm, _window, cx| {
5273 this.submit_feedback_message(cx);
5274 }))
5275 .p_2()
5276 .mb_2()
5277 .mx_5()
5278 .gap_1()
5279 .rounded_md()
5280 .border_1()
5281 .border_color(cx.theme().colors().border)
5282 .bg(cx.theme().colors().editor_background)
5283 .child(div().w_full().child(editor))
5284 .child(
5285 h_flex()
5286 .child(
5287 IconButton::new("dismiss-feedback-message", IconName::Close)
5288 .icon_color(Color::Error)
5289 .icon_size(IconSize::XSmall)
5290 .shape(ui::IconButtonShape::Square)
5291 .on_click(cx.listener(move |this, _, _window, cx| {
5292 this.thread_feedback.dismiss_comments();
5293 cx.notify();
5294 })),
5295 )
5296 .child(
5297 IconButton::new("submit-feedback-message", IconName::Return)
5298 .icon_size(IconSize::XSmall)
5299 .shape(ui::IconButtonShape::Square)
5300 .on_click(cx.listener(move |this, _, _window, cx| {
5301 this.submit_feedback_message(cx);
5302 })),
5303 ),
5304 )
5305 }
5306
5307 fn handle_feedback_click(
5308 &mut self,
5309 feedback: ThreadFeedback,
5310 window: &mut Window,
5311 cx: &mut Context<Self>,
5312 ) {
5313 let Some(thread) = self.thread().cloned() else {
5314 return;
5315 };
5316
5317 self.thread_feedback.submit(thread, feedback, window, cx);
5318 cx.notify();
5319 }
5320
5321 fn submit_feedback_message(&mut self, cx: &mut Context<Self>) {
5322 let Some(thread) = self.thread().cloned() else {
5323 return;
5324 };
5325
5326 self.thread_feedback.submit_comments(thread, cx);
5327 cx.notify();
5328 }
5329
5330 fn render_token_limit_callout(
5331 &self,
5332 line_height: Pixels,
5333 cx: &mut Context<Self>,
5334 ) -> Option<Callout> {
5335 let token_usage = self.thread()?.read(cx).token_usage()?;
5336 let ratio = token_usage.ratio();
5337
5338 let (severity, title) = match ratio {
5339 acp_thread::TokenUsageRatio::Normal => return None,
5340 acp_thread::TokenUsageRatio::Warning => {
5341 (Severity::Warning, "Thread reaching the token limit soon")
5342 }
5343 acp_thread::TokenUsageRatio::Exceeded => {
5344 (Severity::Error, "Thread reached the token limit")
5345 }
5346 };
5347
5348 let burn_mode_available = self.as_native_thread(cx).is_some_and(|thread| {
5349 thread.read(cx).completion_mode() == CompletionMode::Normal
5350 && thread
5351 .read(cx)
5352 .model()
5353 .is_some_and(|model| model.supports_burn_mode())
5354 });
5355
5356 let description = if burn_mode_available {
5357 "To continue, start a new thread from a summary or turn Burn Mode on."
5358 } else {
5359 "To continue, start a new thread from a summary."
5360 };
5361
5362 Some(
5363 Callout::new()
5364 .severity(severity)
5365 .line_height(line_height)
5366 .title(title)
5367 .description(description)
5368 .actions_slot(
5369 h_flex()
5370 .gap_0p5()
5371 .child(
5372 Button::new("start-new-thread", "Start New Thread")
5373 .label_size(LabelSize::Small)
5374 .on_click(cx.listener(|this, _, window, cx| {
5375 let Some(thread) = this.thread() else {
5376 return;
5377 };
5378 let session_id = thread.read(cx).session_id().clone();
5379 window.dispatch_action(
5380 crate::NewNativeAgentThreadFromSummary {
5381 from_session_id: session_id,
5382 }
5383 .boxed_clone(),
5384 cx,
5385 );
5386 })),
5387 )
5388 .when(burn_mode_available, |this| {
5389 this.child(
5390 IconButton::new("burn-mode-callout", IconName::ZedBurnMode)
5391 .icon_size(IconSize::XSmall)
5392 .on_click(cx.listener(|this, _event, window, cx| {
5393 this.toggle_burn_mode(&ToggleBurnMode, window, cx);
5394 })),
5395 )
5396 }),
5397 ),
5398 )
5399 }
5400
5401 fn render_usage_callout(&self, line_height: Pixels, cx: &mut Context<Self>) -> Option<Div> {
5402 if !self.is_using_zed_ai_models(cx) {
5403 return None;
5404 }
5405
5406 let user_store = self.project.read(cx).user_store().read(cx);
5407 if user_store.is_usage_based_billing_enabled() {
5408 return None;
5409 }
5410
5411 let plan = user_store
5412 .plan()
5413 .unwrap_or(cloud_llm_client::Plan::V1(PlanV1::ZedFree));
5414
5415 let usage = user_store.model_request_usage()?;
5416
5417 Some(
5418 div()
5419 .child(UsageCallout::new(plan, usage))
5420 .line_height(line_height),
5421 )
5422 }
5423
5424 fn agent_ui_font_size_changed(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
5425 self.entry_view_state.update(cx, |entry_view_state, cx| {
5426 entry_view_state.agent_ui_font_size_changed(cx);
5427 });
5428 }
5429
5430 pub(crate) fn insert_dragged_files(
5431 &self,
5432 paths: Vec<project::ProjectPath>,
5433 added_worktrees: Vec<Entity<project::Worktree>>,
5434 window: &mut Window,
5435 cx: &mut Context<Self>,
5436 ) {
5437 self.message_editor.update(cx, |message_editor, cx| {
5438 message_editor.insert_dragged_files(paths, added_worktrees, window, cx);
5439 })
5440 }
5441
5442 /// Inserts the selected text into the message editor or the message being
5443 /// edited, if any.
5444 pub(crate) fn insert_selections(&self, window: &mut Window, cx: &mut Context<Self>) {
5445 self.active_editor(cx).update(cx, |editor, cx| {
5446 editor.insert_selections(window, cx);
5447 });
5448 }
5449
5450 fn render_thread_retry_status_callout(
5451 &self,
5452 _window: &mut Window,
5453 _cx: &mut Context<Self>,
5454 ) -> Option<Callout> {
5455 let state = self.thread_retry_status.as_ref()?;
5456
5457 let next_attempt_in = state
5458 .duration
5459 .saturating_sub(Instant::now().saturating_duration_since(state.started_at));
5460 if next_attempt_in.is_zero() {
5461 return None;
5462 }
5463
5464 let next_attempt_in_secs = next_attempt_in.as_secs() + 1;
5465
5466 let retry_message = if state.max_attempts == 1 {
5467 if next_attempt_in_secs == 1 {
5468 "Retrying. Next attempt in 1 second.".to_string()
5469 } else {
5470 format!("Retrying. Next attempt in {next_attempt_in_secs} seconds.")
5471 }
5472 } else if next_attempt_in_secs == 1 {
5473 format!(
5474 "Retrying. Next attempt in 1 second (Attempt {} of {}).",
5475 state.attempt, state.max_attempts,
5476 )
5477 } else {
5478 format!(
5479 "Retrying. Next attempt in {next_attempt_in_secs} seconds (Attempt {} of {}).",
5480 state.attempt, state.max_attempts,
5481 )
5482 };
5483
5484 Some(
5485 Callout::new()
5486 .severity(Severity::Warning)
5487 .title(state.last_error.clone())
5488 .description(retry_message),
5489 )
5490 }
5491
5492 fn render_codex_windows_warning(&self, cx: &mut Context<Self>) -> Callout {
5493 Callout::new()
5494 .icon(IconName::Warning)
5495 .severity(Severity::Warning)
5496 .title("Codex on Windows")
5497 .description("For best performance, run Codex in Windows Subsystem for Linux (WSL2)")
5498 .actions_slot(
5499 Button::new("open-wsl-modal", "Open in WSL")
5500 .icon_size(IconSize::Small)
5501 .icon_color(Color::Muted)
5502 .on_click(cx.listener({
5503 move |_, _, _window, cx| {
5504 #[cfg(windows)]
5505 _window.dispatch_action(
5506 zed_actions::wsl_actions::OpenWsl::default().boxed_clone(),
5507 cx,
5508 );
5509 cx.notify();
5510 }
5511 })),
5512 )
5513 .dismiss_action(
5514 IconButton::new("dismiss", IconName::Close)
5515 .icon_size(IconSize::Small)
5516 .icon_color(Color::Muted)
5517 .tooltip(Tooltip::text("Dismiss Warning"))
5518 .on_click(cx.listener({
5519 move |this, _, _, cx| {
5520 this.show_codex_windows_warning = false;
5521 cx.notify();
5522 }
5523 })),
5524 )
5525 }
5526
5527 fn render_thread_error(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<Div> {
5528 let content = match self.thread_error.as_ref()? {
5529 ThreadError::Other(error) => self.render_any_thread_error(error.clone(), window, cx),
5530 ThreadError::Refusal => self.render_refusal_error(cx),
5531 ThreadError::AuthenticationRequired(error) => {
5532 self.render_authentication_required_error(error.clone(), cx)
5533 }
5534 ThreadError::PaymentRequired => self.render_payment_required_error(cx),
5535 ThreadError::ModelRequestLimitReached(plan) => {
5536 self.render_model_request_limit_reached_error(*plan, cx)
5537 }
5538 ThreadError::ToolUseLimitReached => self.render_tool_use_limit_reached_error(cx)?,
5539 };
5540
5541 Some(div().child(content))
5542 }
5543
5544 fn render_new_version_callout(&self, version: &SharedString, cx: &mut Context<Self>) -> Div {
5545 v_flex().w_full().justify_end().child(
5546 h_flex()
5547 .p_2()
5548 .pr_3()
5549 .w_full()
5550 .gap_1p5()
5551 .border_t_1()
5552 .border_color(cx.theme().colors().border)
5553 .bg(cx.theme().colors().element_background)
5554 .child(
5555 h_flex()
5556 .flex_1()
5557 .gap_1p5()
5558 .child(
5559 Icon::new(IconName::Download)
5560 .color(Color::Accent)
5561 .size(IconSize::Small),
5562 )
5563 .child(Label::new("New version available").size(LabelSize::Small)),
5564 )
5565 .child(
5566 Button::new("update-button", format!("Update to v{}", version))
5567 .label_size(LabelSize::Small)
5568 .style(ButtonStyle::Tinted(TintColor::Accent))
5569 .on_click(cx.listener(|this, _, window, cx| {
5570 this.reset(window, cx);
5571 })),
5572 ),
5573 )
5574 }
5575
5576 fn current_mode_id(&self, cx: &App) -> Option<Arc<str>> {
5577 if let Some(thread) = self.as_native_thread(cx) {
5578 Some(thread.read(cx).profile().0.clone())
5579 } else if let Some(mode_selector) = self.mode_selector() {
5580 Some(mode_selector.read(cx).mode().0)
5581 } else {
5582 None
5583 }
5584 }
5585
5586 fn current_model_id(&self, cx: &App) -> Option<String> {
5587 self.model_selector
5588 .as_ref()
5589 .and_then(|selector| selector.read(cx).active_model(cx).map(|m| m.id.to_string()))
5590 }
5591
5592 fn current_model_name(&self, cx: &App) -> SharedString {
5593 // For native agent (Zed Agent), use the specific model name (e.g., "Claude 3.5 Sonnet")
5594 // For ACP agents, use the agent name (e.g., "Claude Code", "Gemini CLI")
5595 // This provides better clarity about what refused the request
5596 if self.as_native_connection(cx).is_some() {
5597 self.model_selector
5598 .as_ref()
5599 .and_then(|selector| selector.read(cx).active_model(cx))
5600 .map(|model| model.name.clone())
5601 .unwrap_or_else(|| SharedString::from("The model"))
5602 } else {
5603 // ACP agent - use the agent name (e.g., "Claude Code", "Gemini CLI")
5604 self.agent.name()
5605 }
5606 }
5607
5608 fn render_refusal_error(&self, cx: &mut Context<'_, Self>) -> Callout {
5609 let model_or_agent_name = self.current_model_name(cx);
5610 let refusal_message = format!(
5611 "{} 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.",
5612 model_or_agent_name
5613 );
5614
5615 Callout::new()
5616 .severity(Severity::Error)
5617 .title("Request Refused")
5618 .icon(IconName::XCircle)
5619 .description(refusal_message.clone())
5620 .actions_slot(self.create_copy_button(&refusal_message))
5621 .dismiss_action(self.dismiss_error_button(cx))
5622 }
5623
5624 fn render_any_thread_error(
5625 &mut self,
5626 error: SharedString,
5627 window: &mut Window,
5628 cx: &mut Context<'_, Self>,
5629 ) -> Callout {
5630 let can_resume = self
5631 .thread()
5632 .map_or(false, |thread| thread.read(cx).can_resume(cx));
5633
5634 let can_enable_burn_mode = self.as_native_thread(cx).map_or(false, |thread| {
5635 let thread = thread.read(cx);
5636 let supports_burn_mode = thread
5637 .model()
5638 .map_or(false, |model| model.supports_burn_mode());
5639 supports_burn_mode && thread.completion_mode() == CompletionMode::Normal
5640 });
5641
5642 let markdown = if let Some(markdown) = &self.thread_error_markdown {
5643 markdown.clone()
5644 } else {
5645 let markdown = cx.new(|cx| Markdown::new(error.clone(), None, None, cx));
5646 self.thread_error_markdown = Some(markdown.clone());
5647 markdown
5648 };
5649
5650 let markdown_style = default_markdown_style(false, true, window, cx);
5651 let description = self
5652 .render_markdown(markdown, markdown_style)
5653 .into_any_element();
5654
5655 Callout::new()
5656 .severity(Severity::Error)
5657 .icon(IconName::XCircle)
5658 .title("An Error Happened")
5659 .description_slot(description)
5660 .actions_slot(
5661 h_flex()
5662 .gap_0p5()
5663 .when(can_resume && can_enable_burn_mode, |this| {
5664 this.child(
5665 Button::new("enable-burn-mode-and-retry", "Enable Burn Mode and Retry")
5666 .icon(IconName::ZedBurnMode)
5667 .icon_position(IconPosition::Start)
5668 .icon_size(IconSize::Small)
5669 .label_size(LabelSize::Small)
5670 .on_click(cx.listener(|this, _, window, cx| {
5671 this.toggle_burn_mode(&ToggleBurnMode, window, cx);
5672 this.resume_chat(cx);
5673 })),
5674 )
5675 })
5676 .when(can_resume, |this| {
5677 this.child(
5678 IconButton::new("retry", IconName::RotateCw)
5679 .icon_size(IconSize::Small)
5680 .tooltip(Tooltip::text("Retry Generation"))
5681 .on_click(cx.listener(|this, _, _window, cx| {
5682 this.resume_chat(cx);
5683 })),
5684 )
5685 })
5686 .child(self.create_copy_button(error.to_string())),
5687 )
5688 .dismiss_action(self.dismiss_error_button(cx))
5689 }
5690
5691 fn render_payment_required_error(&self, cx: &mut Context<Self>) -> Callout {
5692 const ERROR_MESSAGE: &str =
5693 "You reached your free usage limit. Upgrade to Zed Pro for more prompts.";
5694
5695 Callout::new()
5696 .severity(Severity::Error)
5697 .icon(IconName::XCircle)
5698 .title("Free Usage Exceeded")
5699 .description(ERROR_MESSAGE)
5700 .actions_slot(
5701 h_flex()
5702 .gap_0p5()
5703 .child(self.upgrade_button(cx))
5704 .child(self.create_copy_button(ERROR_MESSAGE)),
5705 )
5706 .dismiss_action(self.dismiss_error_button(cx))
5707 }
5708
5709 fn render_authentication_required_error(
5710 &self,
5711 error: SharedString,
5712 cx: &mut Context<Self>,
5713 ) -> Callout {
5714 Callout::new()
5715 .severity(Severity::Error)
5716 .title("Authentication Required")
5717 .icon(IconName::XCircle)
5718 .description(error.clone())
5719 .actions_slot(
5720 h_flex()
5721 .gap_0p5()
5722 .child(self.authenticate_button(cx))
5723 .child(self.create_copy_button(error)),
5724 )
5725 .dismiss_action(self.dismiss_error_button(cx))
5726 }
5727
5728 fn render_model_request_limit_reached_error(
5729 &self,
5730 plan: cloud_llm_client::Plan,
5731 cx: &mut Context<Self>,
5732 ) -> Callout {
5733 let error_message = match plan {
5734 cloud_llm_client::Plan::V1(PlanV1::ZedPro) => {
5735 "Upgrade to usage-based billing for more prompts."
5736 }
5737 cloud_llm_client::Plan::V1(PlanV1::ZedProTrial)
5738 | cloud_llm_client::Plan::V1(PlanV1::ZedFree) => "Upgrade to Zed Pro for more prompts.",
5739 cloud_llm_client::Plan::V2(_) => "",
5740 };
5741
5742 Callout::new()
5743 .severity(Severity::Error)
5744 .title("Model Prompt Limit Reached")
5745 .icon(IconName::XCircle)
5746 .description(error_message)
5747 .actions_slot(
5748 h_flex()
5749 .gap_0p5()
5750 .child(self.upgrade_button(cx))
5751 .child(self.create_copy_button(error_message)),
5752 )
5753 .dismiss_action(self.dismiss_error_button(cx))
5754 }
5755
5756 fn render_tool_use_limit_reached_error(&self, cx: &mut Context<Self>) -> Option<Callout> {
5757 let thread = self.as_native_thread(cx)?;
5758 let supports_burn_mode = thread
5759 .read(cx)
5760 .model()
5761 .is_some_and(|model| model.supports_burn_mode());
5762
5763 let focus_handle = self.focus_handle(cx);
5764
5765 Some(
5766 Callout::new()
5767 .icon(IconName::Info)
5768 .title("Consecutive tool use limit reached.")
5769 .actions_slot(
5770 h_flex()
5771 .gap_0p5()
5772 .when(supports_burn_mode, |this| {
5773 this.child(
5774 Button::new("continue-burn-mode", "Continue with Burn Mode")
5775 .style(ButtonStyle::Filled)
5776 .style(ButtonStyle::Tinted(ui::TintColor::Accent))
5777 .layer(ElevationIndex::ModalSurface)
5778 .label_size(LabelSize::Small)
5779 .key_binding(
5780 KeyBinding::for_action_in(
5781 &ContinueWithBurnMode,
5782 &focus_handle,
5783 cx,
5784 )
5785 .map(|kb| kb.size(rems_from_px(10.))),
5786 )
5787 .tooltip(Tooltip::text(
5788 "Enable Burn Mode for unlimited tool use.",
5789 ))
5790 .on_click({
5791 cx.listener(move |this, _, _window, cx| {
5792 thread.update(cx, |thread, cx| {
5793 thread
5794 .set_completion_mode(CompletionMode::Burn, cx);
5795 });
5796 this.resume_chat(cx);
5797 })
5798 }),
5799 )
5800 })
5801 .child(
5802 Button::new("continue-conversation", "Continue")
5803 .layer(ElevationIndex::ModalSurface)
5804 .label_size(LabelSize::Small)
5805 .key_binding(
5806 KeyBinding::for_action_in(&ContinueThread, &focus_handle, cx)
5807 .map(|kb| kb.size(rems_from_px(10.))),
5808 )
5809 .on_click(cx.listener(|this, _, _window, cx| {
5810 this.resume_chat(cx);
5811 })),
5812 ),
5813 ),
5814 )
5815 }
5816
5817 fn create_copy_button(&self, message: impl Into<String>) -> impl IntoElement {
5818 let message = message.into();
5819
5820 IconButton::new("copy", IconName::Copy)
5821 .icon_size(IconSize::Small)
5822 .tooltip(Tooltip::text("Copy Error Message"))
5823 .on_click(move |_, _, cx| {
5824 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
5825 })
5826 }
5827
5828 fn dismiss_error_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
5829 IconButton::new("dismiss", IconName::Close)
5830 .icon_size(IconSize::Small)
5831 .tooltip(Tooltip::text("Dismiss Error"))
5832 .on_click(cx.listener({
5833 move |this, _, _, cx| {
5834 this.clear_thread_error(cx);
5835 cx.notify();
5836 }
5837 }))
5838 }
5839
5840 fn authenticate_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
5841 Button::new("authenticate", "Authenticate")
5842 .label_size(LabelSize::Small)
5843 .style(ButtonStyle::Filled)
5844 .on_click(cx.listener({
5845 move |this, _, window, cx| {
5846 let agent = this.agent.clone();
5847 let ThreadState::Ready { thread, .. } = &this.thread_state else {
5848 return;
5849 };
5850
5851 let connection = thread.read(cx).connection().clone();
5852 this.clear_thread_error(cx);
5853 if let Some(message) = this.in_flight_prompt.take() {
5854 this.message_editor.update(cx, |editor, cx| {
5855 editor.set_message(message, window, cx);
5856 });
5857 }
5858 let this = cx.weak_entity();
5859 window.defer(cx, |window, cx| {
5860 Self::handle_auth_required(
5861 this,
5862 AuthRequired::new(),
5863 agent,
5864 connection,
5865 window,
5866 cx,
5867 );
5868 })
5869 }
5870 }))
5871 }
5872
5873 pub(crate) fn reauthenticate(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5874 let agent = self.agent.clone();
5875 let ThreadState::Ready { thread, .. } = &self.thread_state else {
5876 return;
5877 };
5878
5879 let connection = thread.read(cx).connection().clone();
5880 self.clear_thread_error(cx);
5881 let this = cx.weak_entity();
5882 window.defer(cx, |window, cx| {
5883 Self::handle_auth_required(this, AuthRequired::new(), agent, connection, window, cx);
5884 })
5885 }
5886
5887 fn upgrade_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
5888 Button::new("upgrade", "Upgrade")
5889 .label_size(LabelSize::Small)
5890 .style(ButtonStyle::Tinted(ui::TintColor::Accent))
5891 .on_click(cx.listener({
5892 move |this, _, _, cx| {
5893 this.clear_thread_error(cx);
5894 cx.open_url(&zed_urls::upgrade_to_zed_pro_url(cx));
5895 }
5896 }))
5897 }
5898
5899 pub fn delete_history_entry(&mut self, entry: HistoryEntry, cx: &mut Context<Self>) {
5900 let task = match entry {
5901 HistoryEntry::AcpThread(thread) => self.history_store.update(cx, |history, cx| {
5902 history.delete_thread(thread.id.clone(), cx)
5903 }),
5904 HistoryEntry::TextThread(text_thread) => {
5905 self.history_store.update(cx, |history, cx| {
5906 history.delete_text_thread(text_thread.path.clone(), cx)
5907 })
5908 }
5909 };
5910 task.detach_and_log_err(cx);
5911 }
5912
5913 /// Returns the currently active editor, either for a message that is being
5914 /// edited or the editor for a new message.
5915 fn active_editor(&self, cx: &App) -> Entity<MessageEditor> {
5916 if let Some(index) = self.editing_message
5917 && let Some(editor) = self
5918 .entry_view_state
5919 .read(cx)
5920 .entry(index)
5921 .and_then(|e| e.message_editor())
5922 .cloned()
5923 {
5924 editor
5925 } else {
5926 self.message_editor.clone()
5927 }
5928 }
5929}
5930
5931fn loading_contents_spinner(size: IconSize) -> AnyElement {
5932 Icon::new(IconName::LoadCircle)
5933 .size(size)
5934 .color(Color::Accent)
5935 .with_rotate_animation(3)
5936 .into_any_element()
5937}
5938
5939fn placeholder_text(agent_name: &str, has_commands: bool) -> String {
5940 if agent_name == "Zed Agent" {
5941 format!("Message the {} — @ to include context", agent_name)
5942 } else if has_commands {
5943 format!(
5944 "Message {} — @ to include context, / for commands",
5945 agent_name
5946 )
5947 } else {
5948 format!("Message {} — @ to include context", agent_name)
5949 }
5950}
5951
5952impl Focusable for AcpThreadView {
5953 fn focus_handle(&self, cx: &App) -> FocusHandle {
5954 match self.thread_state {
5955 ThreadState::Ready { .. } => self.active_editor(cx).focus_handle(cx),
5956 ThreadState::Loading { .. }
5957 | ThreadState::LoadError(_)
5958 | ThreadState::Unauthenticated { .. } => self.focus_handle.clone(),
5959 }
5960 }
5961}
5962
5963impl Render for AcpThreadView {
5964 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
5965 let has_messages = self.list_state.item_count() > 0;
5966 let line_height = TextSize::Small.rems(cx).to_pixels(window.rem_size()) * 1.5;
5967
5968 v_flex()
5969 .size_full()
5970 .key_context("AcpThread")
5971 .on_action(cx.listener(Self::toggle_burn_mode))
5972 .on_action(cx.listener(Self::keep_all))
5973 .on_action(cx.listener(Self::reject_all))
5974 .on_action(cx.listener(Self::allow_always))
5975 .on_action(cx.listener(Self::allow_once))
5976 .on_action(cx.listener(Self::reject_once))
5977 .on_action(cx.listener(|this, _: &ToggleProfileSelector, window, cx| {
5978 if let Some(profile_selector) = this.profile_selector.as_ref() {
5979 profile_selector.read(cx).menu_handle().toggle(window, cx);
5980 } else if let Some(mode_selector) = this.mode_selector() {
5981 mode_selector.read(cx).menu_handle().toggle(window, cx);
5982 }
5983 }))
5984 .on_action(cx.listener(|this, _: &CycleModeSelector, window, cx| {
5985 if let Some(profile_selector) = this.profile_selector.as_ref() {
5986 profile_selector.update(cx, |profile_selector, cx| {
5987 profile_selector.cycle_profile(cx);
5988 });
5989 } else if let Some(mode_selector) = this.mode_selector() {
5990 mode_selector.update(cx, |mode_selector, cx| {
5991 mode_selector.cycle_mode(window, cx);
5992 });
5993 }
5994 }))
5995 .on_action(cx.listener(|this, _: &ToggleModelSelector, window, cx| {
5996 if let Some(model_selector) = this.model_selector.as_ref() {
5997 model_selector
5998 .update(cx, |model_selector, cx| model_selector.toggle(window, cx));
5999 }
6000 }))
6001 .on_action(cx.listener(|this, _: &CycleFavoriteModels, window, cx| {
6002 if let Some(model_selector) = this.model_selector.as_ref() {
6003 model_selector.update(cx, |model_selector, cx| {
6004 model_selector.cycle_favorite_models(window, cx);
6005 });
6006 }
6007 }))
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}