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, bail};
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_summary, 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 window.spawn(cx, async move |cx| {
4720 let markdown_language = markdown_language_task.await?;
4721
4722 workspace.update_in(cx, |workspace, window, cx| {
4723 let project = workspace.project().clone();
4724
4725 if !project.read(cx).is_local() {
4726 bail!("failed to open active thread as markdown in remote project");
4727 }
4728
4729 let buffer = project.update(cx, |project, cx| {
4730 project.create_local_buffer(&markdown, Some(markdown_language), true, cx)
4731 });
4732 let buffer = cx.new(|cx| {
4733 MultiBuffer::singleton(buffer, cx).with_title(thread_summary.clone())
4734 });
4735
4736 workspace.add_item_to_active_pane(
4737 Box::new(cx.new(|cx| {
4738 let mut editor =
4739 Editor::for_multibuffer(buffer, Some(project.clone()), window, cx);
4740 editor.set_breadcrumb_header(thread_summary);
4741 editor
4742 })),
4743 None,
4744 true,
4745 window,
4746 cx,
4747 );
4748
4749 anyhow::Ok(())
4750 })??;
4751 anyhow::Ok(())
4752 })
4753 }
4754
4755 fn scroll_to_top(&mut self, cx: &mut Context<Self>) {
4756 self.list_state.scroll_to(ListOffset::default());
4757 cx.notify();
4758 }
4759
4760 pub fn scroll_to_bottom(&mut self, cx: &mut Context<Self>) {
4761 if let Some(thread) = self.thread() {
4762 let entry_count = thread.read(cx).entries().len();
4763 self.list_state.reset(entry_count);
4764 cx.notify();
4765 }
4766 }
4767
4768 fn notify_with_sound(
4769 &mut self,
4770 caption: impl Into<SharedString>,
4771 icon: IconName,
4772 window: &mut Window,
4773 cx: &mut Context<Self>,
4774 ) {
4775 self.play_notification_sound(window, cx);
4776 self.show_notification(caption, icon, window, cx);
4777 }
4778
4779 fn play_notification_sound(&self, window: &Window, cx: &mut App) {
4780 let settings = AgentSettings::get_global(cx);
4781 if settings.play_sound_when_agent_done && !window.is_window_active() {
4782 Audio::play_sound(Sound::AgentDone, cx);
4783 }
4784 }
4785
4786 fn show_notification(
4787 &mut self,
4788 caption: impl Into<SharedString>,
4789 icon: IconName,
4790 window: &mut Window,
4791 cx: &mut Context<Self>,
4792 ) {
4793 if !self.notifications.is_empty() {
4794 return;
4795 }
4796
4797 let settings = AgentSettings::get_global(cx);
4798
4799 let window_is_inactive = !window.is_window_active();
4800 let panel_is_hidden = self
4801 .workspace
4802 .upgrade()
4803 .map(|workspace| AgentPanel::is_hidden(&workspace, cx))
4804 .unwrap_or(true);
4805
4806 let should_notify = window_is_inactive || panel_is_hidden;
4807
4808 if !should_notify {
4809 return;
4810 }
4811
4812 // TODO: Change this once we have title summarization for external agents.
4813 let title = self.agent.name();
4814
4815 match settings.notify_when_agent_waiting {
4816 NotifyWhenAgentWaiting::PrimaryScreen => {
4817 if let Some(primary) = cx.primary_display() {
4818 self.pop_up(icon, caption.into(), title, window, primary, cx);
4819 }
4820 }
4821 NotifyWhenAgentWaiting::AllScreens => {
4822 let caption = caption.into();
4823 for screen in cx.displays() {
4824 self.pop_up(icon, caption.clone(), title.clone(), window, screen, cx);
4825 }
4826 }
4827 NotifyWhenAgentWaiting::Never => {
4828 // Don't show anything
4829 }
4830 }
4831 }
4832
4833 fn pop_up(
4834 &mut self,
4835 icon: IconName,
4836 caption: SharedString,
4837 title: SharedString,
4838 window: &mut Window,
4839 screen: Rc<dyn PlatformDisplay>,
4840 cx: &mut Context<Self>,
4841 ) {
4842 let options = AgentNotification::window_options(screen, cx);
4843
4844 let project_name = self.workspace.upgrade().and_then(|workspace| {
4845 workspace
4846 .read(cx)
4847 .project()
4848 .read(cx)
4849 .visible_worktrees(cx)
4850 .next()
4851 .map(|worktree| worktree.read(cx).root_name_str().to_string())
4852 });
4853
4854 if let Some(screen_window) = cx
4855 .open_window(options, |_, cx| {
4856 cx.new(|_| {
4857 AgentNotification::new(title.clone(), caption.clone(), icon, project_name)
4858 })
4859 })
4860 .log_err()
4861 && let Some(pop_up) = screen_window.entity(cx).log_err()
4862 {
4863 self.notification_subscriptions
4864 .entry(screen_window)
4865 .or_insert_with(Vec::new)
4866 .push(cx.subscribe_in(&pop_up, window, {
4867 |this, _, event, window, cx| match event {
4868 AgentNotificationEvent::Accepted => {
4869 let handle = window.window_handle();
4870 cx.activate(true);
4871
4872 let workspace_handle = this.workspace.clone();
4873
4874 // If there are multiple Zed windows, activate the correct one.
4875 cx.defer(move |cx| {
4876 handle
4877 .update(cx, |_view, window, _cx| {
4878 window.activate_window();
4879
4880 if let Some(workspace) = workspace_handle.upgrade() {
4881 workspace.update(_cx, |workspace, cx| {
4882 workspace.focus_panel::<AgentPanel>(window, cx);
4883 });
4884 }
4885 })
4886 .log_err();
4887 });
4888
4889 this.dismiss_notifications(cx);
4890 }
4891 AgentNotificationEvent::Dismissed => {
4892 this.dismiss_notifications(cx);
4893 }
4894 }
4895 }));
4896
4897 self.notifications.push(screen_window);
4898
4899 // If the user manually refocuses the original window, dismiss the popup.
4900 self.notification_subscriptions
4901 .entry(screen_window)
4902 .or_insert_with(Vec::new)
4903 .push({
4904 let pop_up_weak = pop_up.downgrade();
4905
4906 cx.observe_window_activation(window, move |_, window, cx| {
4907 if window.is_window_active()
4908 && let Some(pop_up) = pop_up_weak.upgrade()
4909 {
4910 pop_up.update(cx, |_, cx| {
4911 cx.emit(AgentNotificationEvent::Dismissed);
4912 });
4913 }
4914 })
4915 });
4916 }
4917 }
4918
4919 fn dismiss_notifications(&mut self, cx: &mut Context<Self>) {
4920 for window in self.notifications.drain(..) {
4921 window
4922 .update(cx, |_, window, _| {
4923 window.remove_window();
4924 })
4925 .ok();
4926
4927 self.notification_subscriptions.remove(&window);
4928 }
4929 }
4930
4931 fn render_generating(&self, confirmation: bool) -> impl IntoElement {
4932 h_flex()
4933 .id("generating-spinner")
4934 .py_2()
4935 .px(rems_from_px(22.))
4936 .map(|this| {
4937 if confirmation {
4938 this.gap_2()
4939 .child(
4940 h_flex()
4941 .w_2()
4942 .child(SpinnerLabel::sand().size(LabelSize::Small)),
4943 )
4944 .child(
4945 LoadingLabel::new("Waiting Confirmation")
4946 .size(LabelSize::Small)
4947 .color(Color::Muted),
4948 )
4949 } else {
4950 this.child(SpinnerLabel::new().size(LabelSize::Small))
4951 }
4952 })
4953 .into_any_element()
4954 }
4955
4956 fn render_thread_controls(
4957 &self,
4958 thread: &Entity<AcpThread>,
4959 cx: &Context<Self>,
4960 ) -> impl IntoElement {
4961 let is_generating = matches!(thread.read(cx).status(), ThreadStatus::Generating);
4962 if is_generating {
4963 return self.render_generating(false).into_any_element();
4964 }
4965
4966 let open_as_markdown = IconButton::new("open-as-markdown", IconName::FileMarkdown)
4967 .shape(ui::IconButtonShape::Square)
4968 .icon_size(IconSize::Small)
4969 .icon_color(Color::Ignored)
4970 .tooltip(Tooltip::text("Open Thread as Markdown"))
4971 .on_click(cx.listener(move |this, _, window, cx| {
4972 if let Some(workspace) = this.workspace.upgrade() {
4973 this.open_thread_as_markdown(workspace, window, cx)
4974 .detach_and_log_err(cx);
4975 }
4976 }));
4977
4978 let scroll_to_top = IconButton::new("scroll_to_top", IconName::ArrowUp)
4979 .shape(ui::IconButtonShape::Square)
4980 .icon_size(IconSize::Small)
4981 .icon_color(Color::Ignored)
4982 .tooltip(Tooltip::text("Scroll To Top"))
4983 .on_click(cx.listener(move |this, _, _, cx| {
4984 this.scroll_to_top(cx);
4985 }));
4986
4987 let mut container = h_flex()
4988 .id("thread-controls-container")
4989 .group("thread-controls-container")
4990 .w_full()
4991 .py_2()
4992 .px_5()
4993 .gap_px()
4994 .opacity(0.6)
4995 .hover(|style| style.opacity(1.))
4996 .flex_wrap()
4997 .justify_end();
4998
4999 if AgentSettings::get_global(cx).enable_feedback
5000 && self
5001 .thread()
5002 .is_some_and(|thread| thread.read(cx).connection().telemetry().is_some())
5003 {
5004 let feedback = self.thread_feedback.feedback;
5005
5006 container = container
5007 .child(
5008 div().visible_on_hover("thread-controls-container").child(
5009 Label::new(match feedback {
5010 Some(ThreadFeedback::Positive) => "Thanks for your feedback!",
5011 Some(ThreadFeedback::Negative) => {
5012 "We appreciate your feedback and will use it to improve."
5013 }
5014 None => {
5015 "Rating the thread sends all of your current conversation to the Zed team."
5016 }
5017 })
5018 .color(Color::Muted)
5019 .size(LabelSize::XSmall)
5020 .truncate(),
5021 ),
5022 )
5023 .child(
5024 IconButton::new("feedback-thumbs-up", IconName::ThumbsUp)
5025 .shape(ui::IconButtonShape::Square)
5026 .icon_size(IconSize::Small)
5027 .icon_color(match feedback {
5028 Some(ThreadFeedback::Positive) => Color::Accent,
5029 _ => Color::Ignored,
5030 })
5031 .tooltip(Tooltip::text("Helpful Response"))
5032 .on_click(cx.listener(move |this, _, window, cx| {
5033 this.handle_feedback_click(ThreadFeedback::Positive, window, cx);
5034 })),
5035 )
5036 .child(
5037 IconButton::new("feedback-thumbs-down", IconName::ThumbsDown)
5038 .shape(ui::IconButtonShape::Square)
5039 .icon_size(IconSize::Small)
5040 .icon_color(match feedback {
5041 Some(ThreadFeedback::Negative) => Color::Accent,
5042 _ => Color::Ignored,
5043 })
5044 .tooltip(Tooltip::text("Not Helpful"))
5045 .on_click(cx.listener(move |this, _, window, cx| {
5046 this.handle_feedback_click(ThreadFeedback::Negative, window, cx);
5047 })),
5048 );
5049 }
5050
5051 container
5052 .child(open_as_markdown)
5053 .child(scroll_to_top)
5054 .into_any_element()
5055 }
5056
5057 fn render_feedback_feedback_editor(editor: Entity<Editor>, cx: &Context<Self>) -> Div {
5058 h_flex()
5059 .key_context("AgentFeedbackMessageEditor")
5060 .on_action(cx.listener(move |this, _: &menu::Cancel, _, cx| {
5061 this.thread_feedback.dismiss_comments();
5062 cx.notify();
5063 }))
5064 .on_action(cx.listener(move |this, _: &menu::Confirm, _window, cx| {
5065 this.submit_feedback_message(cx);
5066 }))
5067 .p_2()
5068 .mb_2()
5069 .mx_5()
5070 .gap_1()
5071 .rounded_md()
5072 .border_1()
5073 .border_color(cx.theme().colors().border)
5074 .bg(cx.theme().colors().editor_background)
5075 .child(div().w_full().child(editor))
5076 .child(
5077 h_flex()
5078 .child(
5079 IconButton::new("dismiss-feedback-message", IconName::Close)
5080 .icon_color(Color::Error)
5081 .icon_size(IconSize::XSmall)
5082 .shape(ui::IconButtonShape::Square)
5083 .on_click(cx.listener(move |this, _, _window, cx| {
5084 this.thread_feedback.dismiss_comments();
5085 cx.notify();
5086 })),
5087 )
5088 .child(
5089 IconButton::new("submit-feedback-message", IconName::Return)
5090 .icon_size(IconSize::XSmall)
5091 .shape(ui::IconButtonShape::Square)
5092 .on_click(cx.listener(move |this, _, _window, cx| {
5093 this.submit_feedback_message(cx);
5094 })),
5095 ),
5096 )
5097 }
5098
5099 fn handle_feedback_click(
5100 &mut self,
5101 feedback: ThreadFeedback,
5102 window: &mut Window,
5103 cx: &mut Context<Self>,
5104 ) {
5105 let Some(thread) = self.thread().cloned() else {
5106 return;
5107 };
5108
5109 self.thread_feedback.submit(thread, feedback, window, cx);
5110 cx.notify();
5111 }
5112
5113 fn submit_feedback_message(&mut self, cx: &mut Context<Self>) {
5114 let Some(thread) = self.thread().cloned() else {
5115 return;
5116 };
5117
5118 self.thread_feedback.submit_comments(thread, cx);
5119 cx.notify();
5120 }
5121
5122 fn render_token_limit_callout(
5123 &self,
5124 line_height: Pixels,
5125 cx: &mut Context<Self>,
5126 ) -> Option<Callout> {
5127 let token_usage = self.thread()?.read(cx).token_usage()?;
5128 let ratio = token_usage.ratio();
5129
5130 let (severity, title) = match ratio {
5131 acp_thread::TokenUsageRatio::Normal => return None,
5132 acp_thread::TokenUsageRatio::Warning => {
5133 (Severity::Warning, "Thread reaching the token limit soon")
5134 }
5135 acp_thread::TokenUsageRatio::Exceeded => {
5136 (Severity::Error, "Thread reached the token limit")
5137 }
5138 };
5139
5140 let burn_mode_available = self.as_native_thread(cx).is_some_and(|thread| {
5141 thread.read(cx).completion_mode() == CompletionMode::Normal
5142 && thread
5143 .read(cx)
5144 .model()
5145 .is_some_and(|model| model.supports_burn_mode())
5146 });
5147
5148 let description = if burn_mode_available {
5149 "To continue, start a new thread from a summary or turn Burn Mode on."
5150 } else {
5151 "To continue, start a new thread from a summary."
5152 };
5153
5154 Some(
5155 Callout::new()
5156 .severity(severity)
5157 .line_height(line_height)
5158 .title(title)
5159 .description(description)
5160 .actions_slot(
5161 h_flex()
5162 .gap_0p5()
5163 .child(
5164 Button::new("start-new-thread", "Start New Thread")
5165 .label_size(LabelSize::Small)
5166 .on_click(cx.listener(|this, _, window, cx| {
5167 let Some(thread) = this.thread() else {
5168 return;
5169 };
5170 let session_id = thread.read(cx).session_id().clone();
5171 window.dispatch_action(
5172 crate::NewNativeAgentThreadFromSummary {
5173 from_session_id: session_id,
5174 }
5175 .boxed_clone(),
5176 cx,
5177 );
5178 })),
5179 )
5180 .when(burn_mode_available, |this| {
5181 this.child(
5182 IconButton::new("burn-mode-callout", IconName::ZedBurnMode)
5183 .icon_size(IconSize::XSmall)
5184 .on_click(cx.listener(|this, _event, window, cx| {
5185 this.toggle_burn_mode(&ToggleBurnMode, window, cx);
5186 })),
5187 )
5188 }),
5189 ),
5190 )
5191 }
5192
5193 fn render_usage_callout(&self, line_height: Pixels, cx: &mut Context<Self>) -> Option<Div> {
5194 if !self.is_using_zed_ai_models(cx) {
5195 return None;
5196 }
5197
5198 let user_store = self.project.read(cx).user_store().read(cx);
5199 if user_store.is_usage_based_billing_enabled() {
5200 return None;
5201 }
5202
5203 let plan = user_store
5204 .plan()
5205 .unwrap_or(cloud_llm_client::Plan::V1(PlanV1::ZedFree));
5206
5207 let usage = user_store.model_request_usage()?;
5208
5209 Some(
5210 div()
5211 .child(UsageCallout::new(plan, usage))
5212 .line_height(line_height),
5213 )
5214 }
5215
5216 fn agent_ui_font_size_changed(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
5217 self.entry_view_state.update(cx, |entry_view_state, cx| {
5218 entry_view_state.agent_ui_font_size_changed(cx);
5219 });
5220 }
5221
5222 pub(crate) fn insert_dragged_files(
5223 &self,
5224 paths: Vec<project::ProjectPath>,
5225 added_worktrees: Vec<Entity<project::Worktree>>,
5226 window: &mut Window,
5227 cx: &mut Context<Self>,
5228 ) {
5229 self.message_editor.update(cx, |message_editor, cx| {
5230 message_editor.insert_dragged_files(paths, added_worktrees, window, cx);
5231 })
5232 }
5233
5234 /// Inserts the selected text into the message editor or the message being
5235 /// edited, if any.
5236 pub(crate) fn insert_selections(&self, window: &mut Window, cx: &mut Context<Self>) {
5237 self.active_editor(cx).update(cx, |editor, cx| {
5238 editor.insert_selections(window, cx);
5239 });
5240 }
5241
5242 fn render_thread_retry_status_callout(
5243 &self,
5244 _window: &mut Window,
5245 _cx: &mut Context<Self>,
5246 ) -> Option<Callout> {
5247 let state = self.thread_retry_status.as_ref()?;
5248
5249 let next_attempt_in = state
5250 .duration
5251 .saturating_sub(Instant::now().saturating_duration_since(state.started_at));
5252 if next_attempt_in.is_zero() {
5253 return None;
5254 }
5255
5256 let next_attempt_in_secs = next_attempt_in.as_secs() + 1;
5257
5258 let retry_message = if state.max_attempts == 1 {
5259 if next_attempt_in_secs == 1 {
5260 "Retrying. Next attempt in 1 second.".to_string()
5261 } else {
5262 format!("Retrying. Next attempt in {next_attempt_in_secs} seconds.")
5263 }
5264 } else if next_attempt_in_secs == 1 {
5265 format!(
5266 "Retrying. Next attempt in 1 second (Attempt {} of {}).",
5267 state.attempt, state.max_attempts,
5268 )
5269 } else {
5270 format!(
5271 "Retrying. Next attempt in {next_attempt_in_secs} seconds (Attempt {} of {}).",
5272 state.attempt, state.max_attempts,
5273 )
5274 };
5275
5276 Some(
5277 Callout::new()
5278 .severity(Severity::Warning)
5279 .title(state.last_error.clone())
5280 .description(retry_message),
5281 )
5282 }
5283
5284 fn render_codex_windows_warning(&self, cx: &mut Context<Self>) -> Option<Callout> {
5285 if self.show_codex_windows_warning {
5286 Some(
5287 Callout::new()
5288 .icon(IconName::Warning)
5289 .severity(Severity::Warning)
5290 .title("Codex on Windows")
5291 .description(
5292 "For best performance, run Codex in Windows Subsystem for Linux (WSL2)",
5293 )
5294 .actions_slot(
5295 Button::new("open-wsl-modal", "Open in WSL")
5296 .icon_size(IconSize::Small)
5297 .icon_color(Color::Muted)
5298 .on_click(cx.listener({
5299 move |_, _, _window, cx| {
5300 #[cfg(windows)]
5301 _window.dispatch_action(
5302 zed_actions::wsl_actions::OpenWsl::default().boxed_clone(),
5303 cx,
5304 );
5305 cx.notify();
5306 }
5307 })),
5308 )
5309 .dismiss_action(
5310 IconButton::new("dismiss", IconName::Close)
5311 .icon_size(IconSize::Small)
5312 .icon_color(Color::Muted)
5313 .tooltip(Tooltip::text("Dismiss Warning"))
5314 .on_click(cx.listener({
5315 move |this, _, _, cx| {
5316 this.show_codex_windows_warning = false;
5317 cx.notify();
5318 }
5319 })),
5320 ),
5321 )
5322 } else {
5323 None
5324 }
5325 }
5326
5327 fn render_thread_error(&self, cx: &mut Context<Self>) -> Option<Div> {
5328 let content = match self.thread_error.as_ref()? {
5329 ThreadError::Other(error) => self.render_any_thread_error(error.clone(), cx),
5330 ThreadError::Refusal => self.render_refusal_error(cx),
5331 ThreadError::AuthenticationRequired(error) => {
5332 self.render_authentication_required_error(error.clone(), cx)
5333 }
5334 ThreadError::PaymentRequired => self.render_payment_required_error(cx),
5335 ThreadError::ModelRequestLimitReached(plan) => {
5336 self.render_model_request_limit_reached_error(*plan, cx)
5337 }
5338 ThreadError::ToolUseLimitReached => self.render_tool_use_limit_reached_error(cx)?,
5339 };
5340
5341 Some(div().child(content))
5342 }
5343
5344 fn render_new_version_callout(&self, version: &SharedString, cx: &mut Context<Self>) -> Div {
5345 v_flex().w_full().justify_end().child(
5346 h_flex()
5347 .p_2()
5348 .pr_3()
5349 .w_full()
5350 .gap_1p5()
5351 .border_t_1()
5352 .border_color(cx.theme().colors().border)
5353 .bg(cx.theme().colors().element_background)
5354 .child(
5355 h_flex()
5356 .flex_1()
5357 .gap_1p5()
5358 .child(
5359 Icon::new(IconName::Download)
5360 .color(Color::Accent)
5361 .size(IconSize::Small),
5362 )
5363 .child(Label::new("New version available").size(LabelSize::Small)),
5364 )
5365 .child(
5366 Button::new("update-button", format!("Update to v{}", version))
5367 .label_size(LabelSize::Small)
5368 .style(ButtonStyle::Tinted(TintColor::Accent))
5369 .on_click(cx.listener(|this, _, window, cx| {
5370 this.reset(window, cx);
5371 })),
5372 ),
5373 )
5374 }
5375
5376 fn current_model_id(&self, cx: &App) -> Option<String> {
5377 self.model_selector
5378 .as_ref()
5379 .and_then(|selector| selector.read(cx).active_model(cx).map(|m| m.id.to_string()))
5380 }
5381
5382 fn current_model_name(&self, cx: &App) -> SharedString {
5383 // For native agent (Zed Agent), use the specific model name (e.g., "Claude 3.5 Sonnet")
5384 // For ACP agents, use the agent name (e.g., "Claude Code", "Gemini CLI")
5385 // This provides better clarity about what refused the request
5386 if self.as_native_connection(cx).is_some() {
5387 self.model_selector
5388 .as_ref()
5389 .and_then(|selector| selector.read(cx).active_model(cx))
5390 .map(|model| model.name.clone())
5391 .unwrap_or_else(|| SharedString::from("The model"))
5392 } else {
5393 // ACP agent - use the agent name (e.g., "Claude Code", "Gemini CLI")
5394 self.agent.name()
5395 }
5396 }
5397
5398 fn render_refusal_error(&self, cx: &mut Context<'_, Self>) -> Callout {
5399 let model_or_agent_name = self.current_model_name(cx);
5400 let refusal_message = format!(
5401 "{} 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.",
5402 model_or_agent_name
5403 );
5404
5405 Callout::new()
5406 .severity(Severity::Error)
5407 .title("Request Refused")
5408 .icon(IconName::XCircle)
5409 .description(refusal_message.clone())
5410 .actions_slot(self.create_copy_button(&refusal_message))
5411 .dismiss_action(self.dismiss_error_button(cx))
5412 }
5413
5414 fn render_any_thread_error(&self, error: SharedString, cx: &mut Context<'_, Self>) -> Callout {
5415 let can_resume = self
5416 .thread()
5417 .map_or(false, |thread| thread.read(cx).can_resume(cx));
5418
5419 let can_enable_burn_mode = self.as_native_thread(cx).map_or(false, |thread| {
5420 let thread = thread.read(cx);
5421 let supports_burn_mode = thread
5422 .model()
5423 .map_or(false, |model| model.supports_burn_mode());
5424 supports_burn_mode && thread.completion_mode() == CompletionMode::Normal
5425 });
5426
5427 Callout::new()
5428 .severity(Severity::Error)
5429 .title("Error")
5430 .icon(IconName::XCircle)
5431 .description(error.clone())
5432 .actions_slot(
5433 h_flex()
5434 .gap_0p5()
5435 .when(can_resume && can_enable_burn_mode, |this| {
5436 this.child(
5437 Button::new("enable-burn-mode-and-retry", "Enable Burn Mode and Retry")
5438 .icon(IconName::ZedBurnMode)
5439 .icon_position(IconPosition::Start)
5440 .icon_size(IconSize::Small)
5441 .label_size(LabelSize::Small)
5442 .on_click(cx.listener(|this, _, window, cx| {
5443 this.toggle_burn_mode(&ToggleBurnMode, window, cx);
5444 this.resume_chat(cx);
5445 })),
5446 )
5447 })
5448 .when(can_resume, |this| {
5449 this.child(
5450 Button::new("retry", "Retry")
5451 .icon(IconName::RotateCw)
5452 .icon_position(IconPosition::Start)
5453 .icon_size(IconSize::Small)
5454 .label_size(LabelSize::Small)
5455 .on_click(cx.listener(|this, _, _window, cx| {
5456 this.resume_chat(cx);
5457 })),
5458 )
5459 })
5460 .child(self.create_copy_button(error.to_string())),
5461 )
5462 .dismiss_action(self.dismiss_error_button(cx))
5463 }
5464
5465 fn render_payment_required_error(&self, cx: &mut Context<Self>) -> Callout {
5466 const ERROR_MESSAGE: &str =
5467 "You reached your free usage limit. Upgrade to Zed Pro for more prompts.";
5468
5469 Callout::new()
5470 .severity(Severity::Error)
5471 .icon(IconName::XCircle)
5472 .title("Free Usage Exceeded")
5473 .description(ERROR_MESSAGE)
5474 .actions_slot(
5475 h_flex()
5476 .gap_0p5()
5477 .child(self.upgrade_button(cx))
5478 .child(self.create_copy_button(ERROR_MESSAGE)),
5479 )
5480 .dismiss_action(self.dismiss_error_button(cx))
5481 }
5482
5483 fn render_authentication_required_error(
5484 &self,
5485 error: SharedString,
5486 cx: &mut Context<Self>,
5487 ) -> Callout {
5488 Callout::new()
5489 .severity(Severity::Error)
5490 .title("Authentication Required")
5491 .icon(IconName::XCircle)
5492 .description(error.clone())
5493 .actions_slot(
5494 h_flex()
5495 .gap_0p5()
5496 .child(self.authenticate_button(cx))
5497 .child(self.create_copy_button(error)),
5498 )
5499 .dismiss_action(self.dismiss_error_button(cx))
5500 }
5501
5502 fn render_model_request_limit_reached_error(
5503 &self,
5504 plan: cloud_llm_client::Plan,
5505 cx: &mut Context<Self>,
5506 ) -> Callout {
5507 let error_message = match plan {
5508 cloud_llm_client::Plan::V1(PlanV1::ZedPro) => {
5509 "Upgrade to usage-based billing for more prompts."
5510 }
5511 cloud_llm_client::Plan::V1(PlanV1::ZedProTrial)
5512 | cloud_llm_client::Plan::V1(PlanV1::ZedFree) => "Upgrade to Zed Pro for more prompts.",
5513 cloud_llm_client::Plan::V2(_) => "",
5514 };
5515
5516 Callout::new()
5517 .severity(Severity::Error)
5518 .title("Model Prompt Limit Reached")
5519 .icon(IconName::XCircle)
5520 .description(error_message)
5521 .actions_slot(
5522 h_flex()
5523 .gap_0p5()
5524 .child(self.upgrade_button(cx))
5525 .child(self.create_copy_button(error_message)),
5526 )
5527 .dismiss_action(self.dismiss_error_button(cx))
5528 }
5529
5530 fn render_tool_use_limit_reached_error(&self, cx: &mut Context<Self>) -> Option<Callout> {
5531 let thread = self.as_native_thread(cx)?;
5532 let supports_burn_mode = thread
5533 .read(cx)
5534 .model()
5535 .is_some_and(|model| model.supports_burn_mode());
5536
5537 let focus_handle = self.focus_handle(cx);
5538
5539 Some(
5540 Callout::new()
5541 .icon(IconName::Info)
5542 .title("Consecutive tool use limit reached.")
5543 .actions_slot(
5544 h_flex()
5545 .gap_0p5()
5546 .when(supports_burn_mode, |this| {
5547 this.child(
5548 Button::new("continue-burn-mode", "Continue with Burn Mode")
5549 .style(ButtonStyle::Filled)
5550 .style(ButtonStyle::Tinted(ui::TintColor::Accent))
5551 .layer(ElevationIndex::ModalSurface)
5552 .label_size(LabelSize::Small)
5553 .key_binding(
5554 KeyBinding::for_action_in(
5555 &ContinueWithBurnMode,
5556 &focus_handle,
5557 cx,
5558 )
5559 .map(|kb| kb.size(rems_from_px(10.))),
5560 )
5561 .tooltip(Tooltip::text(
5562 "Enable Burn Mode for unlimited tool use.",
5563 ))
5564 .on_click({
5565 cx.listener(move |this, _, _window, cx| {
5566 thread.update(cx, |thread, cx| {
5567 thread
5568 .set_completion_mode(CompletionMode::Burn, cx);
5569 });
5570 this.resume_chat(cx);
5571 })
5572 }),
5573 )
5574 })
5575 .child(
5576 Button::new("continue-conversation", "Continue")
5577 .layer(ElevationIndex::ModalSurface)
5578 .label_size(LabelSize::Small)
5579 .key_binding(
5580 KeyBinding::for_action_in(&ContinueThread, &focus_handle, cx)
5581 .map(|kb| kb.size(rems_from_px(10.))),
5582 )
5583 .on_click(cx.listener(|this, _, _window, cx| {
5584 this.resume_chat(cx);
5585 })),
5586 ),
5587 ),
5588 )
5589 }
5590
5591 fn create_copy_button(&self, message: impl Into<String>) -> impl IntoElement {
5592 let message = message.into();
5593
5594 IconButton::new("copy", IconName::Copy)
5595 .icon_size(IconSize::Small)
5596 .icon_color(Color::Muted)
5597 .tooltip(Tooltip::text("Copy Error Message"))
5598 .on_click(move |_, _, cx| {
5599 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
5600 })
5601 }
5602
5603 fn dismiss_error_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
5604 IconButton::new("dismiss", IconName::Close)
5605 .icon_size(IconSize::Small)
5606 .icon_color(Color::Muted)
5607 .tooltip(Tooltip::text("Dismiss Error"))
5608 .on_click(cx.listener({
5609 move |this, _, _, cx| {
5610 this.clear_thread_error(cx);
5611 cx.notify();
5612 }
5613 }))
5614 }
5615
5616 fn authenticate_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
5617 Button::new("authenticate", "Authenticate")
5618 .label_size(LabelSize::Small)
5619 .style(ButtonStyle::Filled)
5620 .on_click(cx.listener({
5621 move |this, _, window, cx| {
5622 let agent = this.agent.clone();
5623 let ThreadState::Ready { thread, .. } = &this.thread_state else {
5624 return;
5625 };
5626
5627 let connection = thread.read(cx).connection().clone();
5628 let err = AuthRequired {
5629 description: None,
5630 provider_id: None,
5631 };
5632 this.clear_thread_error(cx);
5633 let this = cx.weak_entity();
5634 window.defer(cx, |window, cx| {
5635 Self::handle_auth_required(this, err, agent, connection, window, cx);
5636 })
5637 }
5638 }))
5639 }
5640
5641 pub(crate) fn reauthenticate(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5642 let agent = self.agent.clone();
5643 let ThreadState::Ready { thread, .. } = &self.thread_state else {
5644 return;
5645 };
5646
5647 let connection = thread.read(cx).connection().clone();
5648 let err = AuthRequired {
5649 description: None,
5650 provider_id: None,
5651 };
5652 self.clear_thread_error(cx);
5653 let this = cx.weak_entity();
5654 window.defer(cx, |window, cx| {
5655 Self::handle_auth_required(this, err, agent, connection, window, cx);
5656 })
5657 }
5658
5659 fn upgrade_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
5660 Button::new("upgrade", "Upgrade")
5661 .label_size(LabelSize::Small)
5662 .style(ButtonStyle::Tinted(ui::TintColor::Accent))
5663 .on_click(cx.listener({
5664 move |this, _, _, cx| {
5665 this.clear_thread_error(cx);
5666 cx.open_url(&zed_urls::upgrade_to_zed_pro_url(cx));
5667 }
5668 }))
5669 }
5670
5671 pub fn delete_history_entry(&mut self, entry: HistoryEntry, cx: &mut Context<Self>) {
5672 let task = match entry {
5673 HistoryEntry::AcpThread(thread) => self.history_store.update(cx, |history, cx| {
5674 history.delete_thread(thread.id.clone(), cx)
5675 }),
5676 HistoryEntry::TextThread(text_thread) => {
5677 self.history_store.update(cx, |history, cx| {
5678 history.delete_text_thread(text_thread.path.clone(), cx)
5679 })
5680 }
5681 };
5682 task.detach_and_log_err(cx);
5683 }
5684
5685 /// Returns the currently active editor, either for a message that is being
5686 /// edited or the editor for a new message.
5687 fn active_editor(&self, cx: &App) -> Entity<MessageEditor> {
5688 if let Some(index) = self.editing_message
5689 && let Some(editor) = self
5690 .entry_view_state
5691 .read(cx)
5692 .entry(index)
5693 .and_then(|e| e.message_editor())
5694 .cloned()
5695 {
5696 editor
5697 } else {
5698 self.message_editor.clone()
5699 }
5700 }
5701}
5702
5703fn loading_contents_spinner(size: IconSize) -> AnyElement {
5704 Icon::new(IconName::LoadCircle)
5705 .size(size)
5706 .color(Color::Accent)
5707 .with_rotate_animation(3)
5708 .into_any_element()
5709}
5710
5711impl Focusable for AcpThreadView {
5712 fn focus_handle(&self, cx: &App) -> FocusHandle {
5713 match self.thread_state {
5714 ThreadState::Loading { .. } | ThreadState::Ready { .. } => {
5715 self.active_editor(cx).focus_handle(cx)
5716 }
5717 ThreadState::LoadError(_) | ThreadState::Unauthenticated { .. } => {
5718 self.focus_handle.clone()
5719 }
5720 }
5721 }
5722}
5723
5724impl Render for AcpThreadView {
5725 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
5726 let has_messages = self.list_state.item_count() > 0;
5727 let line_height = TextSize::Small.rems(cx).to_pixels(window.rem_size()) * 1.5;
5728
5729 v_flex()
5730 .size_full()
5731 .key_context("AcpThread")
5732 .on_action(cx.listener(Self::toggle_burn_mode))
5733 .on_action(cx.listener(Self::keep_all))
5734 .on_action(cx.listener(Self::reject_all))
5735 .on_action(cx.listener(Self::allow_always))
5736 .on_action(cx.listener(Self::allow_once))
5737 .on_action(cx.listener(Self::reject_once))
5738 .track_focus(&self.focus_handle)
5739 .bg(cx.theme().colors().panel_background)
5740 .child(match &self.thread_state {
5741 ThreadState::Unauthenticated {
5742 connection,
5743 description,
5744 configuration_view,
5745 pending_auth_method,
5746 ..
5747 } => self
5748 .render_auth_required_state(
5749 connection,
5750 description.as_ref(),
5751 configuration_view.as_ref(),
5752 pending_auth_method.as_ref(),
5753 window,
5754 cx,
5755 )
5756 .into_any(),
5757 ThreadState::Loading { .. } => v_flex()
5758 .flex_1()
5759 .child(self.render_recent_history(cx))
5760 .into_any(),
5761 ThreadState::LoadError(e) => v_flex()
5762 .flex_1()
5763 .size_full()
5764 .items_center()
5765 .justify_end()
5766 .child(self.render_load_error(e, window, cx))
5767 .into_any(),
5768 ThreadState::Ready { .. } => v_flex().flex_1().map(|this| {
5769 if has_messages {
5770 this.child(
5771 list(
5772 self.list_state.clone(),
5773 cx.processor(|this, index: usize, window, cx| {
5774 let Some((entry, len)) = this.thread().and_then(|thread| {
5775 let entries = &thread.read(cx).entries();
5776 Some((entries.get(index)?, entries.len()))
5777 }) else {
5778 return Empty.into_any();
5779 };
5780 this.render_entry(index, len, entry, window, cx)
5781 }),
5782 )
5783 .with_sizing_behavior(gpui::ListSizingBehavior::Auto)
5784 .flex_grow()
5785 .into_any(),
5786 )
5787 .vertical_scrollbar_for(self.list_state.clone(), window, cx)
5788 .into_any()
5789 } else {
5790 this.child(self.render_recent_history(cx)).into_any()
5791 }
5792 }),
5793 })
5794 // The activity bar is intentionally rendered outside of the ThreadState::Ready match
5795 // above so that the scrollbar doesn't render behind it. The current setup allows
5796 // the scrollbar to stop exactly at the activity bar start.
5797 .when(has_messages, |this| match &self.thread_state {
5798 ThreadState::Ready { thread, .. } => {
5799 this.children(self.render_activity_bar(thread, window, cx))
5800 }
5801 _ => this,
5802 })
5803 .children(self.render_thread_retry_status_callout(window, cx))
5804 .children({
5805 if cfg!(windows) && self.project.read(cx).is_local() {
5806 self.render_codex_windows_warning(cx)
5807 } else {
5808 None
5809 }
5810 })
5811 .children(self.render_thread_error(cx))
5812 .when_some(
5813 self.new_server_version_available.as_ref().filter(|_| {
5814 !has_messages || !matches!(self.thread_state, ThreadState::Ready { .. })
5815 }),
5816 |this, version| this.child(self.render_new_version_callout(&version, cx)),
5817 )
5818 .children(
5819 if let Some(usage_callout) = self.render_usage_callout(line_height, cx) {
5820 Some(usage_callout.into_any_element())
5821 } else {
5822 self.render_token_limit_callout(line_height, cx)
5823 .map(|token_limit_callout| token_limit_callout.into_any_element())
5824 },
5825 )
5826 .child(self.render_message_editor(window, cx))
5827 }
5828}
5829
5830fn default_markdown_style(
5831 buffer_font: bool,
5832 muted_text: bool,
5833 window: &Window,
5834 cx: &App,
5835) -> MarkdownStyle {
5836 let theme_settings = ThemeSettings::get_global(cx);
5837 let colors = cx.theme().colors();
5838
5839 let buffer_font_size = theme_settings.agent_buffer_font_size(cx);
5840
5841 let mut text_style = window.text_style();
5842 let line_height = buffer_font_size * 1.75;
5843
5844 let font_family = if buffer_font {
5845 theme_settings.buffer_font.family.clone()
5846 } else {
5847 theme_settings.ui_font.family.clone()
5848 };
5849
5850 let font_size = if buffer_font {
5851 theme_settings.agent_buffer_font_size(cx)
5852 } else {
5853 theme_settings.agent_ui_font_size(cx)
5854 };
5855
5856 let text_color = if muted_text {
5857 colors.text_muted
5858 } else {
5859 colors.text
5860 };
5861
5862 text_style.refine(&TextStyleRefinement {
5863 font_family: Some(font_family),
5864 font_fallbacks: theme_settings.ui_font.fallbacks.clone(),
5865 font_features: Some(theme_settings.ui_font.features.clone()),
5866 font_size: Some(font_size.into()),
5867 line_height: Some(line_height.into()),
5868 color: Some(text_color),
5869 ..Default::default()
5870 });
5871
5872 MarkdownStyle {
5873 base_text_style: text_style.clone(),
5874 syntax: cx.theme().syntax().clone(),
5875 selection_background_color: colors.element_selection_background,
5876 code_block_overflow_x_scroll: true,
5877 table_overflow_x_scroll: true,
5878 heading_level_styles: Some(HeadingLevelStyles {
5879 h1: Some(TextStyleRefinement {
5880 font_size: Some(rems(1.15).into()),
5881 ..Default::default()
5882 }),
5883 h2: Some(TextStyleRefinement {
5884 font_size: Some(rems(1.1).into()),
5885 ..Default::default()
5886 }),
5887 h3: Some(TextStyleRefinement {
5888 font_size: Some(rems(1.05).into()),
5889 ..Default::default()
5890 }),
5891 h4: Some(TextStyleRefinement {
5892 font_size: Some(rems(1.).into()),
5893 ..Default::default()
5894 }),
5895 h5: Some(TextStyleRefinement {
5896 font_size: Some(rems(0.95).into()),
5897 ..Default::default()
5898 }),
5899 h6: Some(TextStyleRefinement {
5900 font_size: Some(rems(0.875).into()),
5901 ..Default::default()
5902 }),
5903 }),
5904 code_block: StyleRefinement {
5905 padding: EdgesRefinement {
5906 top: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(px(8.)))),
5907 left: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(px(8.)))),
5908 right: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(px(8.)))),
5909 bottom: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(px(8.)))),
5910 },
5911 margin: EdgesRefinement {
5912 top: Some(Length::Definite(px(8.).into())),
5913 left: Some(Length::Definite(px(0.).into())),
5914 right: Some(Length::Definite(px(0.).into())),
5915 bottom: Some(Length::Definite(px(12.).into())),
5916 },
5917 border_style: Some(BorderStyle::Solid),
5918 border_widths: EdgesRefinement {
5919 top: Some(AbsoluteLength::Pixels(px(1.))),
5920 left: Some(AbsoluteLength::Pixels(px(1.))),
5921 right: Some(AbsoluteLength::Pixels(px(1.))),
5922 bottom: Some(AbsoluteLength::Pixels(px(1.))),
5923 },
5924 border_color: Some(colors.border_variant),
5925 background: Some(colors.editor_background.into()),
5926 text: Some(TextStyleRefinement {
5927 font_family: Some(theme_settings.buffer_font.family.clone()),
5928 font_fallbacks: theme_settings.buffer_font.fallbacks.clone(),
5929 font_features: Some(theme_settings.buffer_font.features.clone()),
5930 font_size: Some(buffer_font_size.into()),
5931 ..Default::default()
5932 }),
5933 ..Default::default()
5934 },
5935 inline_code: TextStyleRefinement {
5936 font_family: Some(theme_settings.buffer_font.family.clone()),
5937 font_fallbacks: theme_settings.buffer_font.fallbacks.clone(),
5938 font_features: Some(theme_settings.buffer_font.features.clone()),
5939 font_size: Some(buffer_font_size.into()),
5940 background_color: Some(colors.editor_foreground.opacity(0.08)),
5941 ..Default::default()
5942 },
5943 link: TextStyleRefinement {
5944 background_color: Some(colors.editor_foreground.opacity(0.025)),
5945 underline: Some(UnderlineStyle {
5946 color: Some(colors.text_accent.opacity(0.5)),
5947 thickness: px(1.),
5948 ..Default::default()
5949 }),
5950 ..Default::default()
5951 },
5952 ..Default::default()
5953 }
5954}
5955
5956fn plan_label_markdown_style(
5957 status: &acp::PlanEntryStatus,
5958 window: &Window,
5959 cx: &App,
5960) -> MarkdownStyle {
5961 let default_md_style = default_markdown_style(false, false, window, cx);
5962
5963 MarkdownStyle {
5964 base_text_style: TextStyle {
5965 color: cx.theme().colors().text_muted,
5966 strikethrough: if matches!(status, acp::PlanEntryStatus::Completed) {
5967 Some(gpui::StrikethroughStyle {
5968 thickness: px(1.),
5969 color: Some(cx.theme().colors().text_muted.opacity(0.8)),
5970 })
5971 } else {
5972 None
5973 },
5974 ..default_md_style.base_text_style
5975 },
5976 ..default_md_style
5977 }
5978}
5979
5980fn terminal_command_markdown_style(window: &Window, cx: &App) -> MarkdownStyle {
5981 let default_md_style = default_markdown_style(true, false, window, cx);
5982
5983 MarkdownStyle {
5984 base_text_style: TextStyle {
5985 ..default_md_style.base_text_style
5986 },
5987 selection_background_color: cx.theme().colors().element_selection_background,
5988 ..Default::default()
5989 }
5990}
5991
5992#[cfg(test)]
5993pub(crate) mod tests {
5994 use acp_thread::StubAgentConnection;
5995 use agent_client_protocol::SessionId;
5996 use assistant_text_thread::TextThreadStore;
5997 use editor::EditorSettings;
5998 use fs::FakeFs;
5999 use gpui::{EventEmitter, SemanticVersion, TestAppContext, VisualTestContext};
6000 use project::Project;
6001 use serde_json::json;
6002 use settings::SettingsStore;
6003 use std::any::Any;
6004 use std::path::Path;
6005 use workspace::Item;
6006
6007 use super::*;
6008
6009 #[gpui::test]
6010 async fn test_drop(cx: &mut TestAppContext) {
6011 init_test(cx);
6012
6013 let (thread_view, _cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
6014 let weak_view = thread_view.downgrade();
6015 drop(thread_view);
6016 assert!(!weak_view.is_upgradable());
6017 }
6018
6019 #[gpui::test]
6020 async fn test_notification_for_stop_event(cx: &mut TestAppContext) {
6021 init_test(cx);
6022
6023 let (thread_view, cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
6024
6025 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
6026 message_editor.update_in(cx, |editor, window, cx| {
6027 editor.set_text("Hello", window, cx);
6028 });
6029
6030 cx.deactivate_window();
6031
6032 thread_view.update_in(cx, |thread_view, window, cx| {
6033 thread_view.send(window, cx);
6034 });
6035
6036 cx.run_until_parked();
6037
6038 assert!(
6039 cx.windows()
6040 .iter()
6041 .any(|window| window.downcast::<AgentNotification>().is_some())
6042 );
6043 }
6044
6045 #[gpui::test]
6046 async fn test_notification_for_error(cx: &mut TestAppContext) {
6047 init_test(cx);
6048
6049 let (thread_view, cx) =
6050 setup_thread_view(StubAgentServer::new(SaboteurAgentConnection), cx).await;
6051
6052 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
6053 message_editor.update_in(cx, |editor, window, cx| {
6054 editor.set_text("Hello", window, cx);
6055 });
6056
6057 cx.deactivate_window();
6058
6059 thread_view.update_in(cx, |thread_view, window, cx| {
6060 thread_view.send(window, cx);
6061 });
6062
6063 cx.run_until_parked();
6064
6065 assert!(
6066 cx.windows()
6067 .iter()
6068 .any(|window| window.downcast::<AgentNotification>().is_some())
6069 );
6070 }
6071
6072 #[gpui::test]
6073 async fn test_refusal_handling(cx: &mut TestAppContext) {
6074 init_test(cx);
6075
6076 let (thread_view, cx) =
6077 setup_thread_view(StubAgentServer::new(RefusalAgentConnection), cx).await;
6078
6079 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
6080 message_editor.update_in(cx, |editor, window, cx| {
6081 editor.set_text("Do something harmful", window, cx);
6082 });
6083
6084 thread_view.update_in(cx, |thread_view, window, cx| {
6085 thread_view.send(window, cx);
6086 });
6087
6088 cx.run_until_parked();
6089
6090 // Check that the refusal error is set
6091 thread_view.read_with(cx, |thread_view, _cx| {
6092 assert!(
6093 matches!(thread_view.thread_error, Some(ThreadError::Refusal)),
6094 "Expected refusal error to be set"
6095 );
6096 });
6097 }
6098
6099 #[gpui::test]
6100 async fn test_notification_for_tool_authorization(cx: &mut TestAppContext) {
6101 init_test(cx);
6102
6103 let tool_call_id = acp::ToolCallId("1".into());
6104 let tool_call = acp::ToolCall {
6105 id: tool_call_id.clone(),
6106 title: "Label".into(),
6107 kind: acp::ToolKind::Edit,
6108 status: acp::ToolCallStatus::Pending,
6109 content: vec!["hi".into()],
6110 locations: vec![],
6111 raw_input: None,
6112 raw_output: None,
6113 meta: None,
6114 };
6115 let connection =
6116 StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
6117 tool_call_id,
6118 vec![acp::PermissionOption {
6119 id: acp::PermissionOptionId("1".into()),
6120 name: "Allow".into(),
6121 kind: acp::PermissionOptionKind::AllowOnce,
6122 meta: None,
6123 }],
6124 )]));
6125
6126 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
6127
6128 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
6129
6130 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
6131 message_editor.update_in(cx, |editor, window, cx| {
6132 editor.set_text("Hello", window, cx);
6133 });
6134
6135 cx.deactivate_window();
6136
6137 thread_view.update_in(cx, |thread_view, window, cx| {
6138 thread_view.send(window, cx);
6139 });
6140
6141 cx.run_until_parked();
6142
6143 assert!(
6144 cx.windows()
6145 .iter()
6146 .any(|window| window.downcast::<AgentNotification>().is_some())
6147 );
6148 }
6149
6150 #[gpui::test]
6151 async fn test_notification_when_panel_hidden(cx: &mut TestAppContext) {
6152 init_test(cx);
6153
6154 let (thread_view, cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
6155
6156 add_to_workspace(thread_view.clone(), cx);
6157
6158 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
6159
6160 message_editor.update_in(cx, |editor, window, cx| {
6161 editor.set_text("Hello", window, cx);
6162 });
6163
6164 // Window is active (don't deactivate), but panel will be hidden
6165 // Note: In the test environment, the panel is not actually added to the dock,
6166 // so is_agent_panel_hidden will return true
6167
6168 thread_view.update_in(cx, |thread_view, window, cx| {
6169 thread_view.send(window, cx);
6170 });
6171
6172 cx.run_until_parked();
6173
6174 // Should show notification because window is active but panel is hidden
6175 assert!(
6176 cx.windows()
6177 .iter()
6178 .any(|window| window.downcast::<AgentNotification>().is_some()),
6179 "Expected notification when panel is hidden"
6180 );
6181 }
6182
6183 #[gpui::test]
6184 async fn test_notification_still_works_when_window_inactive(cx: &mut TestAppContext) {
6185 init_test(cx);
6186
6187 let (thread_view, cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
6188
6189 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
6190 message_editor.update_in(cx, |editor, window, cx| {
6191 editor.set_text("Hello", window, cx);
6192 });
6193
6194 // Deactivate window - should show notification regardless of setting
6195 cx.deactivate_window();
6196
6197 thread_view.update_in(cx, |thread_view, window, cx| {
6198 thread_view.send(window, cx);
6199 });
6200
6201 cx.run_until_parked();
6202
6203 // Should still show notification when window is inactive (existing behavior)
6204 assert!(
6205 cx.windows()
6206 .iter()
6207 .any(|window| window.downcast::<AgentNotification>().is_some()),
6208 "Expected notification when window is inactive"
6209 );
6210 }
6211
6212 #[gpui::test]
6213 async fn test_notification_respects_never_setting(cx: &mut TestAppContext) {
6214 init_test(cx);
6215
6216 // Set notify_when_agent_waiting to Never
6217 cx.update(|cx| {
6218 AgentSettings::override_global(
6219 AgentSettings {
6220 notify_when_agent_waiting: NotifyWhenAgentWaiting::Never,
6221 ..AgentSettings::get_global(cx).clone()
6222 },
6223 cx,
6224 );
6225 });
6226
6227 let (thread_view, cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
6228
6229 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
6230 message_editor.update_in(cx, |editor, window, cx| {
6231 editor.set_text("Hello", window, cx);
6232 });
6233
6234 // Window is active
6235
6236 thread_view.update_in(cx, |thread_view, window, cx| {
6237 thread_view.send(window, cx);
6238 });
6239
6240 cx.run_until_parked();
6241
6242 // Should NOT show notification because notify_when_agent_waiting is Never
6243 assert!(
6244 !cx.windows()
6245 .iter()
6246 .any(|window| window.downcast::<AgentNotification>().is_some()),
6247 "Expected no notification when notify_when_agent_waiting is Never"
6248 );
6249 }
6250
6251 async fn setup_thread_view(
6252 agent: impl AgentServer + 'static,
6253 cx: &mut TestAppContext,
6254 ) -> (Entity<AcpThreadView>, &mut VisualTestContext) {
6255 let fs = FakeFs::new(cx.executor());
6256 let project = Project::test(fs, [], cx).await;
6257 let (workspace, cx) =
6258 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6259
6260 let text_thread_store =
6261 cx.update(|_window, cx| cx.new(|cx| TextThreadStore::fake(project.clone(), cx)));
6262 let history_store =
6263 cx.update(|_window, cx| cx.new(|cx| HistoryStore::new(text_thread_store, cx)));
6264
6265 let thread_view = cx.update(|window, cx| {
6266 cx.new(|cx| {
6267 AcpThreadView::new(
6268 Rc::new(agent),
6269 None,
6270 None,
6271 workspace.downgrade(),
6272 project,
6273 history_store,
6274 None,
6275 window,
6276 cx,
6277 )
6278 })
6279 });
6280 cx.run_until_parked();
6281 (thread_view, cx)
6282 }
6283
6284 fn add_to_workspace(thread_view: Entity<AcpThreadView>, cx: &mut VisualTestContext) {
6285 let workspace = thread_view.read_with(cx, |thread_view, _cx| thread_view.workspace.clone());
6286
6287 workspace
6288 .update_in(cx, |workspace, window, cx| {
6289 workspace.add_item_to_active_pane(
6290 Box::new(cx.new(|_| ThreadViewItem(thread_view.clone()))),
6291 None,
6292 true,
6293 window,
6294 cx,
6295 );
6296 })
6297 .unwrap();
6298 }
6299
6300 struct ThreadViewItem(Entity<AcpThreadView>);
6301
6302 impl Item for ThreadViewItem {
6303 type Event = ();
6304
6305 fn include_in_nav_history() -> bool {
6306 false
6307 }
6308
6309 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
6310 "Test".into()
6311 }
6312 }
6313
6314 impl EventEmitter<()> for ThreadViewItem {}
6315
6316 impl Focusable for ThreadViewItem {
6317 fn focus_handle(&self, cx: &App) -> FocusHandle {
6318 self.0.read(cx).focus_handle(cx)
6319 }
6320 }
6321
6322 impl Render for ThreadViewItem {
6323 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
6324 self.0.clone().into_any_element()
6325 }
6326 }
6327
6328 struct StubAgentServer<C> {
6329 connection: C,
6330 }
6331
6332 impl<C> StubAgentServer<C> {
6333 fn new(connection: C) -> Self {
6334 Self { connection }
6335 }
6336 }
6337
6338 impl StubAgentServer<StubAgentConnection> {
6339 fn default_response() -> Self {
6340 let conn = StubAgentConnection::new();
6341 conn.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
6342 acp::ContentChunk {
6343 content: "Default response".into(),
6344 meta: None,
6345 },
6346 )]);
6347 Self::new(conn)
6348 }
6349 }
6350
6351 impl<C> AgentServer for StubAgentServer<C>
6352 where
6353 C: 'static + AgentConnection + Send + Clone,
6354 {
6355 fn telemetry_id(&self) -> &'static str {
6356 "test"
6357 }
6358
6359 fn logo(&self) -> ui::IconName {
6360 ui::IconName::Ai
6361 }
6362
6363 fn name(&self) -> SharedString {
6364 "Test".into()
6365 }
6366
6367 fn connect(
6368 &self,
6369 _root_dir: Option<&Path>,
6370 _delegate: AgentServerDelegate,
6371 _cx: &mut App,
6372 ) -> Task<gpui::Result<(Rc<dyn AgentConnection>, Option<task::SpawnInTerminal>)>> {
6373 Task::ready(Ok((Rc::new(self.connection.clone()), None)))
6374 }
6375
6376 fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
6377 self
6378 }
6379 }
6380
6381 #[derive(Clone)]
6382 struct SaboteurAgentConnection;
6383
6384 impl AgentConnection for SaboteurAgentConnection {
6385 fn telemetry_id(&self) -> &'static str {
6386 "saboteur"
6387 }
6388
6389 fn new_thread(
6390 self: Rc<Self>,
6391 project: Entity<Project>,
6392 _cwd: &Path,
6393 cx: &mut gpui::App,
6394 ) -> Task<gpui::Result<Entity<AcpThread>>> {
6395 Task::ready(Ok(cx.new(|cx| {
6396 let action_log = cx.new(|_| ActionLog::new(project.clone()));
6397 AcpThread::new(
6398 "SaboteurAgentConnection",
6399 self,
6400 project,
6401 action_log,
6402 SessionId("test".into()),
6403 watch::Receiver::constant(acp::PromptCapabilities {
6404 image: true,
6405 audio: true,
6406 embedded_context: true,
6407 meta: None,
6408 }),
6409 cx,
6410 )
6411 })))
6412 }
6413
6414 fn auth_methods(&self) -> &[acp::AuthMethod] {
6415 &[]
6416 }
6417
6418 fn authenticate(
6419 &self,
6420 _method_id: acp::AuthMethodId,
6421 _cx: &mut App,
6422 ) -> Task<gpui::Result<()>> {
6423 unimplemented!()
6424 }
6425
6426 fn prompt(
6427 &self,
6428 _id: Option<acp_thread::UserMessageId>,
6429 _params: acp::PromptRequest,
6430 _cx: &mut App,
6431 ) -> Task<gpui::Result<acp::PromptResponse>> {
6432 Task::ready(Err(anyhow::anyhow!("Error prompting")))
6433 }
6434
6435 fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {
6436 unimplemented!()
6437 }
6438
6439 fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
6440 self
6441 }
6442 }
6443
6444 /// Simulates a model which always returns a refusal response
6445 #[derive(Clone)]
6446 struct RefusalAgentConnection;
6447
6448 impl AgentConnection for RefusalAgentConnection {
6449 fn telemetry_id(&self) -> &'static str {
6450 "refusal"
6451 }
6452
6453 fn new_thread(
6454 self: Rc<Self>,
6455 project: Entity<Project>,
6456 _cwd: &Path,
6457 cx: &mut gpui::App,
6458 ) -> Task<gpui::Result<Entity<AcpThread>>> {
6459 Task::ready(Ok(cx.new(|cx| {
6460 let action_log = cx.new(|_| ActionLog::new(project.clone()));
6461 AcpThread::new(
6462 "RefusalAgentConnection",
6463 self,
6464 project,
6465 action_log,
6466 SessionId("test".into()),
6467 watch::Receiver::constant(acp::PromptCapabilities {
6468 image: true,
6469 audio: true,
6470 embedded_context: true,
6471 meta: None,
6472 }),
6473 cx,
6474 )
6475 })))
6476 }
6477
6478 fn auth_methods(&self) -> &[acp::AuthMethod] {
6479 &[]
6480 }
6481
6482 fn authenticate(
6483 &self,
6484 _method_id: acp::AuthMethodId,
6485 _cx: &mut App,
6486 ) -> Task<gpui::Result<()>> {
6487 unimplemented!()
6488 }
6489
6490 fn prompt(
6491 &self,
6492 _id: Option<acp_thread::UserMessageId>,
6493 _params: acp::PromptRequest,
6494 _cx: &mut App,
6495 ) -> Task<gpui::Result<acp::PromptResponse>> {
6496 Task::ready(Ok(acp::PromptResponse {
6497 stop_reason: acp::StopReason::Refusal,
6498 meta: None,
6499 }))
6500 }
6501
6502 fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {
6503 unimplemented!()
6504 }
6505
6506 fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
6507 self
6508 }
6509 }
6510
6511 pub(crate) fn init_test(cx: &mut TestAppContext) {
6512 cx.update(|cx| {
6513 let settings_store = SettingsStore::test(cx);
6514 cx.set_global(settings_store);
6515 language::init(cx);
6516 Project::init_settings(cx);
6517 AgentSettings::register(cx);
6518 workspace::init_settings(cx);
6519 theme::init(theme::LoadThemes::JustBase, cx);
6520 release_channel::init(SemanticVersion::default(), cx);
6521 EditorSettings::register(cx);
6522 prompt_store::init(cx)
6523 });
6524 }
6525
6526 #[gpui::test]
6527 async fn test_rewind_views(cx: &mut TestAppContext) {
6528 init_test(cx);
6529
6530 let fs = FakeFs::new(cx.executor());
6531 fs.insert_tree(
6532 "/project",
6533 json!({
6534 "test1.txt": "old content 1",
6535 "test2.txt": "old content 2"
6536 }),
6537 )
6538 .await;
6539 let project = Project::test(fs, [Path::new("/project")], cx).await;
6540 let (workspace, cx) =
6541 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6542
6543 let text_thread_store =
6544 cx.update(|_window, cx| cx.new(|cx| TextThreadStore::fake(project.clone(), cx)));
6545 let history_store =
6546 cx.update(|_window, cx| cx.new(|cx| HistoryStore::new(text_thread_store, cx)));
6547
6548 let connection = Rc::new(StubAgentConnection::new());
6549 let thread_view = cx.update(|window, cx| {
6550 cx.new(|cx| {
6551 AcpThreadView::new(
6552 Rc::new(StubAgentServer::new(connection.as_ref().clone())),
6553 None,
6554 None,
6555 workspace.downgrade(),
6556 project.clone(),
6557 history_store.clone(),
6558 None,
6559 window,
6560 cx,
6561 )
6562 })
6563 });
6564
6565 cx.run_until_parked();
6566
6567 let thread = thread_view
6568 .read_with(cx, |view, _| view.thread().cloned())
6569 .unwrap();
6570
6571 // First user message
6572 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(acp::ToolCall {
6573 id: acp::ToolCallId("tool1".into()),
6574 title: "Edit file 1".into(),
6575 kind: acp::ToolKind::Edit,
6576 status: acp::ToolCallStatus::Completed,
6577 content: vec![acp::ToolCallContent::Diff {
6578 diff: acp::Diff {
6579 path: "/project/test1.txt".into(),
6580 old_text: Some("old content 1".into()),
6581 new_text: "new content 1".into(),
6582 meta: None,
6583 },
6584 }],
6585 locations: vec![],
6586 raw_input: None,
6587 raw_output: None,
6588 meta: None,
6589 })]);
6590
6591 thread
6592 .update(cx, |thread, cx| thread.send_raw("Give me a diff", cx))
6593 .await
6594 .unwrap();
6595 cx.run_until_parked();
6596
6597 thread.read_with(cx, |thread, _| {
6598 assert_eq!(thread.entries().len(), 2);
6599 });
6600
6601 thread_view.read_with(cx, |view, cx| {
6602 view.entry_view_state.read_with(cx, |entry_view_state, _| {
6603 assert!(
6604 entry_view_state
6605 .entry(0)
6606 .unwrap()
6607 .message_editor()
6608 .is_some()
6609 );
6610 assert!(entry_view_state.entry(1).unwrap().has_content());
6611 });
6612 });
6613
6614 // Second user message
6615 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(acp::ToolCall {
6616 id: acp::ToolCallId("tool2".into()),
6617 title: "Edit file 2".into(),
6618 kind: acp::ToolKind::Edit,
6619 status: acp::ToolCallStatus::Completed,
6620 content: vec![acp::ToolCallContent::Diff {
6621 diff: acp::Diff {
6622 path: "/project/test2.txt".into(),
6623 old_text: Some("old content 2".into()),
6624 new_text: "new content 2".into(),
6625 meta: None,
6626 },
6627 }],
6628 locations: vec![],
6629 raw_input: None,
6630 raw_output: None,
6631 meta: None,
6632 })]);
6633
6634 thread
6635 .update(cx, |thread, cx| thread.send_raw("Another one", cx))
6636 .await
6637 .unwrap();
6638 cx.run_until_parked();
6639
6640 let second_user_message_id = thread.read_with(cx, |thread, _| {
6641 assert_eq!(thread.entries().len(), 4);
6642 let AgentThreadEntry::UserMessage(user_message) = &thread.entries()[2] else {
6643 panic!();
6644 };
6645 user_message.id.clone().unwrap()
6646 });
6647
6648 thread_view.read_with(cx, |view, cx| {
6649 view.entry_view_state.read_with(cx, |entry_view_state, _| {
6650 assert!(
6651 entry_view_state
6652 .entry(0)
6653 .unwrap()
6654 .message_editor()
6655 .is_some()
6656 );
6657 assert!(entry_view_state.entry(1).unwrap().has_content());
6658 assert!(
6659 entry_view_state
6660 .entry(2)
6661 .unwrap()
6662 .message_editor()
6663 .is_some()
6664 );
6665 assert!(entry_view_state.entry(3).unwrap().has_content());
6666 });
6667 });
6668
6669 // Rewind to first message
6670 thread
6671 .update(cx, |thread, cx| thread.rewind(second_user_message_id, cx))
6672 .await
6673 .unwrap();
6674
6675 cx.run_until_parked();
6676
6677 thread.read_with(cx, |thread, _| {
6678 assert_eq!(thread.entries().len(), 2);
6679 });
6680
6681 thread_view.read_with(cx, |view, cx| {
6682 view.entry_view_state.read_with(cx, |entry_view_state, _| {
6683 assert!(
6684 entry_view_state
6685 .entry(0)
6686 .unwrap()
6687 .message_editor()
6688 .is_some()
6689 );
6690 assert!(entry_view_state.entry(1).unwrap().has_content());
6691
6692 // Old views should be dropped
6693 assert!(entry_view_state.entry(2).is_none());
6694 assert!(entry_view_state.entry(3).is_none());
6695 });
6696 });
6697 }
6698
6699 #[gpui::test]
6700 async fn test_message_editing_cancel(cx: &mut TestAppContext) {
6701 init_test(cx);
6702
6703 let connection = StubAgentConnection::new();
6704
6705 connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
6706 acp::ContentChunk {
6707 content: acp::ContentBlock::Text(acp::TextContent {
6708 text: "Response".into(),
6709 annotations: None,
6710 meta: None,
6711 }),
6712 meta: None,
6713 },
6714 )]);
6715
6716 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
6717 add_to_workspace(thread_view.clone(), cx);
6718
6719 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
6720 message_editor.update_in(cx, |editor, window, cx| {
6721 editor.set_text("Original message to edit", window, cx);
6722 });
6723 thread_view.update_in(cx, |thread_view, window, cx| {
6724 thread_view.send(window, cx);
6725 });
6726
6727 cx.run_until_parked();
6728
6729 let user_message_editor = thread_view.read_with(cx, |view, cx| {
6730 assert_eq!(view.editing_message, None);
6731
6732 view.entry_view_state
6733 .read(cx)
6734 .entry(0)
6735 .unwrap()
6736 .message_editor()
6737 .unwrap()
6738 .clone()
6739 });
6740
6741 // Focus
6742 cx.focus(&user_message_editor);
6743 thread_view.read_with(cx, |view, _cx| {
6744 assert_eq!(view.editing_message, Some(0));
6745 });
6746
6747 // Edit
6748 user_message_editor.update_in(cx, |editor, window, cx| {
6749 editor.set_text("Edited message content", window, cx);
6750 });
6751
6752 // Cancel
6753 user_message_editor.update_in(cx, |_editor, window, cx| {
6754 window.dispatch_action(Box::new(editor::actions::Cancel), cx);
6755 });
6756
6757 thread_view.read_with(cx, |view, _cx| {
6758 assert_eq!(view.editing_message, None);
6759 });
6760
6761 user_message_editor.read_with(cx, |editor, cx| {
6762 assert_eq!(editor.text(cx), "Original message to edit");
6763 });
6764 }
6765
6766 #[gpui::test]
6767 async fn test_message_doesnt_send_if_empty(cx: &mut TestAppContext) {
6768 init_test(cx);
6769
6770 let connection = StubAgentConnection::new();
6771
6772 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
6773 add_to_workspace(thread_view.clone(), cx);
6774
6775 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
6776 let mut events = cx.events(&message_editor);
6777 message_editor.update_in(cx, |editor, window, cx| {
6778 editor.set_text("", window, cx);
6779 });
6780
6781 message_editor.update_in(cx, |_editor, window, cx| {
6782 window.dispatch_action(Box::new(Chat), cx);
6783 });
6784 cx.run_until_parked();
6785 // We shouldn't have received any messages
6786 assert!(matches!(
6787 events.try_next(),
6788 Err(futures::channel::mpsc::TryRecvError { .. })
6789 ));
6790 }
6791
6792 #[gpui::test]
6793 async fn test_message_editing_regenerate(cx: &mut TestAppContext) {
6794 init_test(cx);
6795
6796 let connection = StubAgentConnection::new();
6797
6798 connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
6799 acp::ContentChunk {
6800 content: acp::ContentBlock::Text(acp::TextContent {
6801 text: "Response".into(),
6802 annotations: None,
6803 meta: None,
6804 }),
6805 meta: None,
6806 },
6807 )]);
6808
6809 let (thread_view, cx) =
6810 setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
6811 add_to_workspace(thread_view.clone(), cx);
6812
6813 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
6814 message_editor.update_in(cx, |editor, window, cx| {
6815 editor.set_text("Original message to edit", window, cx);
6816 });
6817 thread_view.update_in(cx, |thread_view, window, cx| {
6818 thread_view.send(window, cx);
6819 });
6820
6821 cx.run_until_parked();
6822
6823 let user_message_editor = thread_view.read_with(cx, |view, cx| {
6824 assert_eq!(view.editing_message, None);
6825 assert_eq!(view.thread().unwrap().read(cx).entries().len(), 2);
6826
6827 view.entry_view_state
6828 .read(cx)
6829 .entry(0)
6830 .unwrap()
6831 .message_editor()
6832 .unwrap()
6833 .clone()
6834 });
6835
6836 // Focus
6837 cx.focus(&user_message_editor);
6838
6839 // Edit
6840 user_message_editor.update_in(cx, |editor, window, cx| {
6841 editor.set_text("Edited message content", window, cx);
6842 });
6843
6844 // Send
6845 connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
6846 acp::ContentChunk {
6847 content: acp::ContentBlock::Text(acp::TextContent {
6848 text: "New Response".into(),
6849 annotations: None,
6850 meta: None,
6851 }),
6852 meta: None,
6853 },
6854 )]);
6855
6856 user_message_editor.update_in(cx, |_editor, window, cx| {
6857 window.dispatch_action(Box::new(Chat), cx);
6858 });
6859
6860 cx.run_until_parked();
6861
6862 thread_view.read_with(cx, |view, cx| {
6863 assert_eq!(view.editing_message, None);
6864
6865 let entries = view.thread().unwrap().read(cx).entries();
6866 assert_eq!(entries.len(), 2);
6867 assert_eq!(
6868 entries[0].to_markdown(cx),
6869 "## User\n\nEdited message content\n\n"
6870 );
6871 assert_eq!(
6872 entries[1].to_markdown(cx),
6873 "## Assistant\n\nNew Response\n\n"
6874 );
6875
6876 let new_editor = view.entry_view_state.read_with(cx, |state, _cx| {
6877 assert!(!state.entry(1).unwrap().has_content());
6878 state.entry(0).unwrap().message_editor().unwrap().clone()
6879 });
6880
6881 assert_eq!(new_editor.read(cx).text(cx), "Edited message content");
6882 })
6883 }
6884
6885 #[gpui::test]
6886 async fn test_message_editing_while_generating(cx: &mut TestAppContext) {
6887 init_test(cx);
6888
6889 let connection = StubAgentConnection::new();
6890
6891 let (thread_view, cx) =
6892 setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
6893 add_to_workspace(thread_view.clone(), cx);
6894
6895 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
6896 message_editor.update_in(cx, |editor, window, cx| {
6897 editor.set_text("Original message to edit", window, cx);
6898 });
6899 thread_view.update_in(cx, |thread_view, window, cx| {
6900 thread_view.send(window, cx);
6901 });
6902
6903 cx.run_until_parked();
6904
6905 let (user_message_editor, session_id) = thread_view.read_with(cx, |view, cx| {
6906 let thread = view.thread().unwrap().read(cx);
6907 assert_eq!(thread.entries().len(), 1);
6908
6909 let editor = view
6910 .entry_view_state
6911 .read(cx)
6912 .entry(0)
6913 .unwrap()
6914 .message_editor()
6915 .unwrap()
6916 .clone();
6917
6918 (editor, thread.session_id().clone())
6919 });
6920
6921 // Focus
6922 cx.focus(&user_message_editor);
6923
6924 thread_view.read_with(cx, |view, _cx| {
6925 assert_eq!(view.editing_message, Some(0));
6926 });
6927
6928 // Edit
6929 user_message_editor.update_in(cx, |editor, window, cx| {
6930 editor.set_text("Edited message content", window, cx);
6931 });
6932
6933 thread_view.read_with(cx, |view, _cx| {
6934 assert_eq!(view.editing_message, Some(0));
6935 });
6936
6937 // Finish streaming response
6938 cx.update(|_, cx| {
6939 connection.send_update(
6940 session_id.clone(),
6941 acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk {
6942 content: acp::ContentBlock::Text(acp::TextContent {
6943 text: "Response".into(),
6944 annotations: None,
6945 meta: None,
6946 }),
6947 meta: None,
6948 }),
6949 cx,
6950 );
6951 connection.end_turn(session_id, acp::StopReason::EndTurn);
6952 });
6953
6954 thread_view.read_with(cx, |view, _cx| {
6955 assert_eq!(view.editing_message, Some(0));
6956 });
6957
6958 cx.run_until_parked();
6959
6960 // Should still be editing
6961 cx.update(|window, cx| {
6962 assert!(user_message_editor.focus_handle(cx).is_focused(window));
6963 assert_eq!(thread_view.read(cx).editing_message, Some(0));
6964 assert_eq!(
6965 user_message_editor.read(cx).text(cx),
6966 "Edited message content"
6967 );
6968 });
6969 }
6970
6971 #[gpui::test]
6972 async fn test_interrupt(cx: &mut TestAppContext) {
6973 init_test(cx);
6974
6975 let connection = StubAgentConnection::new();
6976
6977 let (thread_view, cx) =
6978 setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
6979 add_to_workspace(thread_view.clone(), cx);
6980
6981 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
6982 message_editor.update_in(cx, |editor, window, cx| {
6983 editor.set_text("Message 1", window, cx);
6984 });
6985 thread_view.update_in(cx, |thread_view, window, cx| {
6986 thread_view.send(window, cx);
6987 });
6988
6989 let (thread, session_id) = thread_view.read_with(cx, |view, cx| {
6990 let thread = view.thread().unwrap();
6991
6992 (thread.clone(), thread.read(cx).session_id().clone())
6993 });
6994
6995 cx.run_until_parked();
6996
6997 cx.update(|_, cx| {
6998 connection.send_update(
6999 session_id.clone(),
7000 acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk {
7001 content: "Message 1 resp".into(),
7002 meta: None,
7003 }),
7004 cx,
7005 );
7006 });
7007
7008 cx.run_until_parked();
7009
7010 thread.read_with(cx, |thread, cx| {
7011 assert_eq!(
7012 thread.to_markdown(cx),
7013 indoc::indoc! {"
7014 ## User
7015
7016 Message 1
7017
7018 ## Assistant
7019
7020 Message 1 resp
7021
7022 "}
7023 )
7024 });
7025
7026 message_editor.update_in(cx, |editor, window, cx| {
7027 editor.set_text("Message 2", window, cx);
7028 });
7029 thread_view.update_in(cx, |thread_view, window, cx| {
7030 thread_view.send(window, cx);
7031 });
7032
7033 cx.update(|_, cx| {
7034 // Simulate a response sent after beginning to cancel
7035 connection.send_update(
7036 session_id.clone(),
7037 acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk {
7038 content: "onse".into(),
7039 meta: None,
7040 }),
7041 cx,
7042 );
7043 });
7044
7045 cx.run_until_parked();
7046
7047 // Last Message 1 response should appear before Message 2
7048 thread.read_with(cx, |thread, cx| {
7049 assert_eq!(
7050 thread.to_markdown(cx),
7051 indoc::indoc! {"
7052 ## User
7053
7054 Message 1
7055
7056 ## Assistant
7057
7058 Message 1 response
7059
7060 ## User
7061
7062 Message 2
7063
7064 "}
7065 )
7066 });
7067
7068 cx.update(|_, cx| {
7069 connection.send_update(
7070 session_id.clone(),
7071 acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk {
7072 content: "Message 2 response".into(),
7073 meta: None,
7074 }),
7075 cx,
7076 );
7077 connection.end_turn(session_id.clone(), acp::StopReason::EndTurn);
7078 });
7079
7080 cx.run_until_parked();
7081
7082 thread.read_with(cx, |thread, cx| {
7083 assert_eq!(
7084 thread.to_markdown(cx),
7085 indoc::indoc! {"
7086 ## User
7087
7088 Message 1
7089
7090 ## Assistant
7091
7092 Message 1 response
7093
7094 ## User
7095
7096 Message 2
7097
7098 ## Assistant
7099
7100 Message 2 response
7101
7102 "}
7103 )
7104 });
7105 }
7106
7107 #[gpui::test]
7108 async fn test_message_editing_insert_selections(cx: &mut TestAppContext) {
7109 init_test(cx);
7110
7111 let connection = StubAgentConnection::new();
7112 connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
7113 acp::ContentChunk {
7114 content: acp::ContentBlock::Text(acp::TextContent {
7115 text: "Response".into(),
7116 annotations: None,
7117 meta: None,
7118 }),
7119 meta: None,
7120 },
7121 )]);
7122
7123 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
7124 add_to_workspace(thread_view.clone(), cx);
7125
7126 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
7127 message_editor.update_in(cx, |editor, window, cx| {
7128 editor.set_text("Original message to edit", window, cx)
7129 });
7130 thread_view.update_in(cx, |thread_view, window, cx| thread_view.send(window, cx));
7131 cx.run_until_parked();
7132
7133 let user_message_editor = thread_view.read_with(cx, |thread_view, cx| {
7134 thread_view
7135 .entry_view_state
7136 .read(cx)
7137 .entry(0)
7138 .expect("Should have at least one entry")
7139 .message_editor()
7140 .expect("Should have message editor")
7141 .clone()
7142 });
7143
7144 cx.focus(&user_message_editor);
7145 thread_view.read_with(cx, |thread_view, _cx| {
7146 assert_eq!(thread_view.editing_message, Some(0));
7147 });
7148
7149 // Ensure to edit the focused message before proceeding otherwise, since
7150 // its content is not different from what was sent, focus will be lost.
7151 user_message_editor.update_in(cx, |editor, window, cx| {
7152 editor.set_text("Original message to edit with ", window, cx)
7153 });
7154
7155 // Create a simple buffer with some text so we can create a selection
7156 // that will then be added to the message being edited.
7157 let (workspace, project) = thread_view.read_with(cx, |thread_view, _cx| {
7158 (thread_view.workspace.clone(), thread_view.project.clone())
7159 });
7160 let buffer = project.update(cx, |project, cx| {
7161 project.create_local_buffer("let a = 10 + 10;", None, false, cx)
7162 });
7163
7164 workspace
7165 .update_in(cx, |workspace, window, cx| {
7166 let editor = cx.new(|cx| {
7167 let mut editor =
7168 Editor::for_buffer(buffer.clone(), Some(project.clone()), window, cx);
7169
7170 editor.change_selections(Default::default(), window, cx, |selections| {
7171 selections.select_ranges([8..15]);
7172 });
7173
7174 editor
7175 });
7176 workspace.add_item_to_active_pane(Box::new(editor), None, false, window, cx);
7177 })
7178 .unwrap();
7179
7180 thread_view.update_in(cx, |thread_view, window, cx| {
7181 assert_eq!(thread_view.editing_message, Some(0));
7182 thread_view.insert_selections(window, cx);
7183 });
7184
7185 user_message_editor.read_with(cx, |editor, cx| {
7186 let text = editor.editor().read(cx).text(cx);
7187 let expected_text = String::from("Original message to edit with selection ");
7188
7189 assert_eq!(text, expected_text);
7190 });
7191 }
7192
7193 #[gpui::test]
7194 async fn test_insert_selections(cx: &mut TestAppContext) {
7195 init_test(cx);
7196
7197 let connection = StubAgentConnection::new();
7198 connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
7199 acp::ContentChunk {
7200 content: acp::ContentBlock::Text(acp::TextContent {
7201 text: "Response".into(),
7202 annotations: None,
7203 meta: None,
7204 }),
7205 meta: None,
7206 },
7207 )]);
7208
7209 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
7210 add_to_workspace(thread_view.clone(), cx);
7211
7212 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
7213 message_editor.update_in(cx, |editor, window, cx| {
7214 editor.set_text("Can you review this snippet ", window, cx)
7215 });
7216
7217 // Create a simple buffer with some text so we can create a selection
7218 // that will then be added to the message being edited.
7219 let (workspace, project) = thread_view.read_with(cx, |thread_view, _cx| {
7220 (thread_view.workspace.clone(), thread_view.project.clone())
7221 });
7222 let buffer = project.update(cx, |project, cx| {
7223 project.create_local_buffer("let a = 10 + 10;", None, false, cx)
7224 });
7225
7226 workspace
7227 .update_in(cx, |workspace, window, cx| {
7228 let editor = cx.new(|cx| {
7229 let mut editor =
7230 Editor::for_buffer(buffer.clone(), Some(project.clone()), window, cx);
7231
7232 editor.change_selections(Default::default(), window, cx, |selections| {
7233 selections.select_ranges([8..15]);
7234 });
7235
7236 editor
7237 });
7238 workspace.add_item_to_active_pane(Box::new(editor), None, false, window, cx);
7239 })
7240 .unwrap();
7241
7242 thread_view.update_in(cx, |thread_view, window, cx| {
7243 assert_eq!(thread_view.editing_message, None);
7244 thread_view.insert_selections(window, cx);
7245 });
7246
7247 thread_view.read_with(cx, |thread_view, cx| {
7248 let text = thread_view.message_editor.read(cx).text(cx);
7249 let expected_txt = String::from("Can you review this snippet selection ");
7250
7251 assert_eq!(text, expected_txt);
7252 })
7253 }
7254}