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