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