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