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