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