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) = project.update(cx, |project, cx| {
4074 let path = project.find_project_path(abs_path, cx)?;
4075 project.entry_for_path(&path, cx)
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, _)) = project.update(cx, |project, cx| {
4095 let path = project.find_project_path(path, cx)?;
4096 let entry = project.entry_for_path(&path, cx)?;
4097 Some((path, entry))
4098 }) else {
4099 return;
4100 };
4101
4102 let item = workspace.open_path(path, None, true, window, cx);
4103 window
4104 .spawn(cx, async move |cx| {
4105 let Some(editor) = item.await?.downcast::<Editor>() else {
4106 return Ok(());
4107 };
4108 let range = Point::new(*line_range.start(), 0)
4109 ..Point::new(*line_range.start(), 0);
4110 editor
4111 .update_in(cx, |editor, window, cx| {
4112 editor.change_selections(
4113 SelectionEffects::scroll(Autoscroll::center()),
4114 window,
4115 cx,
4116 |s| s.select_ranges(vec![range]),
4117 );
4118 })
4119 .ok();
4120 anyhow::Ok(())
4121 })
4122 .detach_and_log_err(cx);
4123 }
4124 MentionUri::Selection { abs_path: None, .. } => {}
4125 MentionUri::Thread { id, name } => {
4126 if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
4127 panel.update(cx, |panel, cx| {
4128 panel.load_agent_thread(
4129 DbThreadMetadata {
4130 id,
4131 title: name.into(),
4132 updated_at: Default::default(),
4133 },
4134 window,
4135 cx,
4136 )
4137 });
4138 }
4139 }
4140 MentionUri::TextThread { path, .. } => {
4141 if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
4142 panel.update(cx, |panel, cx| {
4143 panel
4144 .open_saved_prompt_editor(path.as_path().into(), window, cx)
4145 .detach_and_log_err(cx);
4146 });
4147 }
4148 }
4149 MentionUri::Rule { id, .. } => {
4150 let PromptId::User { uuid } = id else {
4151 return;
4152 };
4153 window.dispatch_action(
4154 Box::new(OpenRulesLibrary {
4155 prompt_to_select: Some(uuid.0),
4156 }),
4157 cx,
4158 )
4159 }
4160 MentionUri::Fetch { url } => {
4161 cx.open_url(url.as_str());
4162 }
4163 })
4164 } else {
4165 cx.open_url(&url);
4166 }
4167 }
4168
4169 fn open_tool_call_location(
4170 &self,
4171 entry_ix: usize,
4172 location_ix: usize,
4173 window: &mut Window,
4174 cx: &mut Context<Self>,
4175 ) -> Option<()> {
4176 let (tool_call_location, agent_location) = self
4177 .thread()?
4178 .read(cx)
4179 .entries()
4180 .get(entry_ix)?
4181 .location(location_ix)?;
4182
4183 let project_path = self
4184 .project
4185 .read(cx)
4186 .find_project_path(&tool_call_location.path, cx)?;
4187
4188 let open_task = self
4189 .workspace
4190 .update(cx, |workspace, cx| {
4191 workspace.open_path(project_path, None, true, window, cx)
4192 })
4193 .log_err()?;
4194 window
4195 .spawn(cx, async move |cx| {
4196 let item = open_task.await?;
4197
4198 let Some(active_editor) = item.downcast::<Editor>() else {
4199 return anyhow::Ok(());
4200 };
4201
4202 active_editor.update_in(cx, |editor, window, cx| {
4203 let multibuffer = editor.buffer().read(cx);
4204 let buffer = multibuffer.as_singleton();
4205 if agent_location.buffer.upgrade() == buffer {
4206 let excerpt_id = multibuffer.excerpt_ids().first().cloned();
4207 let anchor = editor::Anchor::in_buffer(
4208 excerpt_id.unwrap(),
4209 buffer.unwrap().read(cx).remote_id(),
4210 agent_location.position,
4211 );
4212 editor.change_selections(Default::default(), window, cx, |selections| {
4213 selections.select_anchor_ranges([anchor..anchor]);
4214 })
4215 } else {
4216 let row = tool_call_location.line.unwrap_or_default();
4217 editor.change_selections(Default::default(), window, cx, |selections| {
4218 selections.select_ranges([Point::new(row, 0)..Point::new(row, 0)]);
4219 })
4220 }
4221 })?;
4222
4223 anyhow::Ok(())
4224 })
4225 .detach_and_log_err(cx);
4226
4227 None
4228 }
4229
4230 pub fn open_thread_as_markdown(
4231 &self,
4232 workspace: Entity<Workspace>,
4233 window: &mut Window,
4234 cx: &mut App,
4235 ) -> Task<Result<()>> {
4236 let markdown_language_task = workspace
4237 .read(cx)
4238 .app_state()
4239 .languages
4240 .language_for_name("Markdown");
4241
4242 let (thread_summary, markdown) = if let Some(thread) = self.thread() {
4243 let thread = thread.read(cx);
4244 (thread.title().to_string(), thread.to_markdown(cx))
4245 } else {
4246 return Task::ready(Ok(()));
4247 };
4248
4249 window.spawn(cx, async move |cx| {
4250 let markdown_language = markdown_language_task.await?;
4251
4252 workspace.update_in(cx, |workspace, window, cx| {
4253 let project = workspace.project().clone();
4254
4255 if !project.read(cx).is_local() {
4256 bail!("failed to open active thread as markdown in remote project");
4257 }
4258
4259 let buffer = project.update(cx, |project, cx| {
4260 project.create_local_buffer(&markdown, Some(markdown_language), cx)
4261 });
4262 let buffer = cx.new(|cx| {
4263 MultiBuffer::singleton(buffer, cx).with_title(thread_summary.clone())
4264 });
4265
4266 workspace.add_item_to_active_pane(
4267 Box::new(cx.new(|cx| {
4268 let mut editor =
4269 Editor::for_multibuffer(buffer, Some(project.clone()), window, cx);
4270 editor.set_breadcrumb_header(thread_summary);
4271 editor
4272 })),
4273 None,
4274 true,
4275 window,
4276 cx,
4277 );
4278
4279 anyhow::Ok(())
4280 })??;
4281 anyhow::Ok(())
4282 })
4283 }
4284
4285 fn scroll_to_top(&mut self, cx: &mut Context<Self>) {
4286 self.list_state.scroll_to(ListOffset::default());
4287 cx.notify();
4288 }
4289
4290 pub fn scroll_to_bottom(&mut self, cx: &mut Context<Self>) {
4291 if let Some(thread) = self.thread() {
4292 let entry_count = thread.read(cx).entries().len();
4293 self.list_state.reset(entry_count);
4294 cx.notify();
4295 }
4296 }
4297
4298 fn notify_with_sound(
4299 &mut self,
4300 caption: impl Into<SharedString>,
4301 icon: IconName,
4302 window: &mut Window,
4303 cx: &mut Context<Self>,
4304 ) {
4305 self.play_notification_sound(window, cx);
4306 self.show_notification(caption, icon, window, cx);
4307 }
4308
4309 fn play_notification_sound(&self, window: &Window, cx: &mut App) {
4310 let settings = AgentSettings::get_global(cx);
4311 if settings.play_sound_when_agent_done && !window.is_window_active() {
4312 Audio::play_sound(Sound::AgentDone, cx);
4313 }
4314 }
4315
4316 fn show_notification(
4317 &mut self,
4318 caption: impl Into<SharedString>,
4319 icon: IconName,
4320 window: &mut Window,
4321 cx: &mut Context<Self>,
4322 ) {
4323 if window.is_window_active() || !self.notifications.is_empty() {
4324 return;
4325 }
4326
4327 // TODO: Change this once we have title summarization for external agents.
4328 let title = self.agent.name();
4329
4330 match AgentSettings::get_global(cx).notify_when_agent_waiting {
4331 NotifyWhenAgentWaiting::PrimaryScreen => {
4332 if let Some(primary) = cx.primary_display() {
4333 self.pop_up(icon, caption.into(), title, window, primary, cx);
4334 }
4335 }
4336 NotifyWhenAgentWaiting::AllScreens => {
4337 let caption = caption.into();
4338 for screen in cx.displays() {
4339 self.pop_up(icon, caption.clone(), title.clone(), window, screen, cx);
4340 }
4341 }
4342 NotifyWhenAgentWaiting::Never => {
4343 // Don't show anything
4344 }
4345 }
4346 }
4347
4348 fn pop_up(
4349 &mut self,
4350 icon: IconName,
4351 caption: SharedString,
4352 title: SharedString,
4353 window: &mut Window,
4354 screen: Rc<dyn PlatformDisplay>,
4355 cx: &mut Context<Self>,
4356 ) {
4357 let options = AgentNotification::window_options(screen, cx);
4358
4359 let project_name = self.workspace.upgrade().and_then(|workspace| {
4360 workspace
4361 .read(cx)
4362 .project()
4363 .read(cx)
4364 .visible_worktrees(cx)
4365 .next()
4366 .map(|worktree| worktree.read(cx).root_name().to_string())
4367 });
4368
4369 if let Some(screen_window) = cx
4370 .open_window(options, |_, cx| {
4371 cx.new(|_| {
4372 AgentNotification::new(title.clone(), caption.clone(), icon, project_name)
4373 })
4374 })
4375 .log_err()
4376 && let Some(pop_up) = screen_window.entity(cx).log_err()
4377 {
4378 self.notification_subscriptions
4379 .entry(screen_window)
4380 .or_insert_with(Vec::new)
4381 .push(cx.subscribe_in(&pop_up, window, {
4382 |this, _, event, window, cx| match event {
4383 AgentNotificationEvent::Accepted => {
4384 let handle = window.window_handle();
4385 cx.activate(true);
4386
4387 let workspace_handle = this.workspace.clone();
4388
4389 // If there are multiple Zed windows, activate the correct one.
4390 cx.defer(move |cx| {
4391 handle
4392 .update(cx, |_view, window, _cx| {
4393 window.activate_window();
4394
4395 if let Some(workspace) = workspace_handle.upgrade() {
4396 workspace.update(_cx, |workspace, cx| {
4397 workspace.focus_panel::<AgentPanel>(window, cx);
4398 });
4399 }
4400 })
4401 .log_err();
4402 });
4403
4404 this.dismiss_notifications(cx);
4405 }
4406 AgentNotificationEvent::Dismissed => {
4407 this.dismiss_notifications(cx);
4408 }
4409 }
4410 }));
4411
4412 self.notifications.push(screen_window);
4413
4414 // If the user manually refocuses the original window, dismiss the popup.
4415 self.notification_subscriptions
4416 .entry(screen_window)
4417 .or_insert_with(Vec::new)
4418 .push({
4419 let pop_up_weak = pop_up.downgrade();
4420
4421 cx.observe_window_activation(window, move |_, window, cx| {
4422 if window.is_window_active()
4423 && let Some(pop_up) = pop_up_weak.upgrade()
4424 {
4425 pop_up.update(cx, |_, cx| {
4426 cx.emit(AgentNotificationEvent::Dismissed);
4427 });
4428 }
4429 })
4430 });
4431 }
4432 }
4433
4434 fn dismiss_notifications(&mut self, cx: &mut Context<Self>) {
4435 for window in self.notifications.drain(..) {
4436 window
4437 .update(cx, |_, window, _| {
4438 window.remove_window();
4439 })
4440 .ok();
4441
4442 self.notification_subscriptions.remove(&window);
4443 }
4444 }
4445
4446 fn render_thread_controls(
4447 &self,
4448 thread: &Entity<AcpThread>,
4449 cx: &Context<Self>,
4450 ) -> impl IntoElement {
4451 let is_generating = matches!(thread.read(cx).status(), ThreadStatus::Generating);
4452 if is_generating {
4453 return h_flex().id("thread-controls-container").child(
4454 div()
4455 .py_2()
4456 .px(rems_from_px(22.))
4457 .child(SpinnerLabel::new().size(LabelSize::Small)),
4458 );
4459 }
4460
4461 let open_as_markdown = IconButton::new("open-as-markdown", IconName::FileMarkdown)
4462 .shape(ui::IconButtonShape::Square)
4463 .icon_size(IconSize::Small)
4464 .icon_color(Color::Ignored)
4465 .tooltip(Tooltip::text("Open Thread as Markdown"))
4466 .on_click(cx.listener(move |this, _, window, cx| {
4467 if let Some(workspace) = this.workspace.upgrade() {
4468 this.open_thread_as_markdown(workspace, window, cx)
4469 .detach_and_log_err(cx);
4470 }
4471 }));
4472
4473 let scroll_to_top = IconButton::new("scroll_to_top", IconName::ArrowUp)
4474 .shape(ui::IconButtonShape::Square)
4475 .icon_size(IconSize::Small)
4476 .icon_color(Color::Ignored)
4477 .tooltip(Tooltip::text("Scroll To Top"))
4478 .on_click(cx.listener(move |this, _, _, cx| {
4479 this.scroll_to_top(cx);
4480 }));
4481
4482 let mut container = h_flex()
4483 .id("thread-controls-container")
4484 .group("thread-controls-container")
4485 .w_full()
4486 .py_2()
4487 .px_5()
4488 .gap_px()
4489 .opacity(0.6)
4490 .hover(|style| style.opacity(1.))
4491 .flex_wrap()
4492 .justify_end();
4493
4494 if AgentSettings::get_global(cx).enable_feedback
4495 && self
4496 .thread()
4497 .is_some_and(|thread| thread.read(cx).connection().telemetry().is_some())
4498 {
4499 let feedback = self.thread_feedback.feedback;
4500
4501 container = container
4502 .child(
4503 div().visible_on_hover("thread-controls-container").child(
4504 Label::new(match feedback {
4505 Some(ThreadFeedback::Positive) => "Thanks for your feedback!",
4506 Some(ThreadFeedback::Negative) => {
4507 "We appreciate your feedback and will use it to improve."
4508 }
4509 None => {
4510 "Rating the thread sends all of your current conversation to the Zed team."
4511 }
4512 })
4513 .color(Color::Muted)
4514 .size(LabelSize::XSmall)
4515 .truncate(),
4516 ),
4517 )
4518 .child(
4519 IconButton::new("feedback-thumbs-up", IconName::ThumbsUp)
4520 .shape(ui::IconButtonShape::Square)
4521 .icon_size(IconSize::Small)
4522 .icon_color(match feedback {
4523 Some(ThreadFeedback::Positive) => Color::Accent,
4524 _ => Color::Ignored,
4525 })
4526 .tooltip(Tooltip::text("Helpful Response"))
4527 .on_click(cx.listener(move |this, _, window, cx| {
4528 this.handle_feedback_click(ThreadFeedback::Positive, window, cx);
4529 })),
4530 )
4531 .child(
4532 IconButton::new("feedback-thumbs-down", IconName::ThumbsDown)
4533 .shape(ui::IconButtonShape::Square)
4534 .icon_size(IconSize::Small)
4535 .icon_color(match feedback {
4536 Some(ThreadFeedback::Negative) => Color::Accent,
4537 _ => Color::Ignored,
4538 })
4539 .tooltip(Tooltip::text("Not Helpful"))
4540 .on_click(cx.listener(move |this, _, window, cx| {
4541 this.handle_feedback_click(ThreadFeedback::Negative, window, cx);
4542 })),
4543 );
4544 }
4545
4546 container.child(open_as_markdown).child(scroll_to_top)
4547 }
4548
4549 fn render_feedback_feedback_editor(editor: Entity<Editor>, cx: &Context<Self>) -> Div {
4550 h_flex()
4551 .key_context("AgentFeedbackMessageEditor")
4552 .on_action(cx.listener(move |this, _: &menu::Cancel, _, cx| {
4553 this.thread_feedback.dismiss_comments();
4554 cx.notify();
4555 }))
4556 .on_action(cx.listener(move |this, _: &menu::Confirm, _window, cx| {
4557 this.submit_feedback_message(cx);
4558 }))
4559 .p_2()
4560 .mb_2()
4561 .mx_5()
4562 .gap_1()
4563 .rounded_md()
4564 .border_1()
4565 .border_color(cx.theme().colors().border)
4566 .bg(cx.theme().colors().editor_background)
4567 .child(div().w_full().child(editor))
4568 .child(
4569 h_flex()
4570 .child(
4571 IconButton::new("dismiss-feedback-message", IconName::Close)
4572 .icon_color(Color::Error)
4573 .icon_size(IconSize::XSmall)
4574 .shape(ui::IconButtonShape::Square)
4575 .on_click(cx.listener(move |this, _, _window, cx| {
4576 this.thread_feedback.dismiss_comments();
4577 cx.notify();
4578 })),
4579 )
4580 .child(
4581 IconButton::new("submit-feedback-message", IconName::Return)
4582 .icon_size(IconSize::XSmall)
4583 .shape(ui::IconButtonShape::Square)
4584 .on_click(cx.listener(move |this, _, _window, cx| {
4585 this.submit_feedback_message(cx);
4586 })),
4587 ),
4588 )
4589 }
4590
4591 fn handle_feedback_click(
4592 &mut self,
4593 feedback: ThreadFeedback,
4594 window: &mut Window,
4595 cx: &mut Context<Self>,
4596 ) {
4597 let Some(thread) = self.thread().cloned() else {
4598 return;
4599 };
4600
4601 self.thread_feedback.submit(thread, feedback, window, cx);
4602 cx.notify();
4603 }
4604
4605 fn submit_feedback_message(&mut self, cx: &mut Context<Self>) {
4606 let Some(thread) = self.thread().cloned() else {
4607 return;
4608 };
4609
4610 self.thread_feedback.submit_comments(thread, cx);
4611 cx.notify();
4612 }
4613
4614 fn render_vertical_scrollbar(&self, cx: &mut Context<Self>) -> Stateful<Div> {
4615 div()
4616 .id("acp-thread-scrollbar")
4617 .occlude()
4618 .on_mouse_move(cx.listener(|_, _, _, cx| {
4619 cx.notify();
4620 cx.stop_propagation()
4621 }))
4622 .on_hover(|_, _, cx| {
4623 cx.stop_propagation();
4624 })
4625 .on_any_mouse_down(|_, _, cx| {
4626 cx.stop_propagation();
4627 })
4628 .on_mouse_up(
4629 MouseButton::Left,
4630 cx.listener(|_, _, _, cx| {
4631 cx.stop_propagation();
4632 }),
4633 )
4634 .on_scroll_wheel(cx.listener(|_, _, _, cx| {
4635 cx.notify();
4636 }))
4637 .h_full()
4638 .absolute()
4639 .right_1()
4640 .top_1()
4641 .bottom_0()
4642 .w(px(12.))
4643 .cursor_default()
4644 .children(Scrollbar::vertical(self.scrollbar_state.clone()).map(|s| s.auto_hide(cx)))
4645 }
4646
4647 fn render_token_limit_callout(
4648 &self,
4649 line_height: Pixels,
4650 cx: &mut Context<Self>,
4651 ) -> Option<Callout> {
4652 let token_usage = self.thread()?.read(cx).token_usage()?;
4653 let ratio = token_usage.ratio();
4654
4655 let (severity, title) = match ratio {
4656 acp_thread::TokenUsageRatio::Normal => return None,
4657 acp_thread::TokenUsageRatio::Warning => {
4658 (Severity::Warning, "Thread reaching the token limit soon")
4659 }
4660 acp_thread::TokenUsageRatio::Exceeded => {
4661 (Severity::Error, "Thread reached the token limit")
4662 }
4663 };
4664
4665 let burn_mode_available = self.as_native_thread(cx).is_some_and(|thread| {
4666 thread.read(cx).completion_mode() == CompletionMode::Normal
4667 && thread
4668 .read(cx)
4669 .model()
4670 .is_some_and(|model| model.supports_burn_mode())
4671 });
4672
4673 let description = if burn_mode_available {
4674 "To continue, start a new thread from a summary or turn Burn Mode on."
4675 } else {
4676 "To continue, start a new thread from a summary."
4677 };
4678
4679 Some(
4680 Callout::new()
4681 .severity(severity)
4682 .line_height(line_height)
4683 .title(title)
4684 .description(description)
4685 .actions_slot(
4686 h_flex()
4687 .gap_0p5()
4688 .child(
4689 Button::new("start-new-thread", "Start New Thread")
4690 .label_size(LabelSize::Small)
4691 .on_click(cx.listener(|this, _, window, cx| {
4692 let Some(thread) = this.thread() else {
4693 return;
4694 };
4695 let session_id = thread.read(cx).session_id().clone();
4696 window.dispatch_action(
4697 crate::NewNativeAgentThreadFromSummary {
4698 from_session_id: session_id,
4699 }
4700 .boxed_clone(),
4701 cx,
4702 );
4703 })),
4704 )
4705 .when(burn_mode_available, |this| {
4706 this.child(
4707 IconButton::new("burn-mode-callout", IconName::ZedBurnMode)
4708 .icon_size(IconSize::XSmall)
4709 .on_click(cx.listener(|this, _event, window, cx| {
4710 this.toggle_burn_mode(&ToggleBurnMode, window, cx);
4711 })),
4712 )
4713 }),
4714 ),
4715 )
4716 }
4717
4718 fn render_usage_callout(&self, line_height: Pixels, cx: &mut Context<Self>) -> Option<Div> {
4719 if !self.is_using_zed_ai_models(cx) {
4720 return None;
4721 }
4722
4723 let user_store = self.project.read(cx).user_store().read(cx);
4724 if user_store.is_usage_based_billing_enabled() {
4725 return None;
4726 }
4727
4728 let plan = user_store.plan().unwrap_or(cloud_llm_client::Plan::ZedFree);
4729
4730 let usage = user_store.model_request_usage()?;
4731
4732 Some(
4733 div()
4734 .child(UsageCallout::new(plan, usage))
4735 .line_height(line_height),
4736 )
4737 }
4738
4739 fn agent_font_size_changed(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
4740 self.entry_view_state.update(cx, |entry_view_state, cx| {
4741 entry_view_state.agent_font_size_changed(cx);
4742 });
4743 }
4744
4745 pub(crate) fn insert_dragged_files(
4746 &self,
4747 paths: Vec<project::ProjectPath>,
4748 added_worktrees: Vec<Entity<project::Worktree>>,
4749 window: &mut Window,
4750 cx: &mut Context<Self>,
4751 ) {
4752 self.message_editor.update(cx, |message_editor, cx| {
4753 message_editor.insert_dragged_files(paths, added_worktrees, window, cx);
4754 })
4755 }
4756
4757 pub(crate) fn insert_selections(&self, window: &mut Window, cx: &mut Context<Self>) {
4758 self.message_editor.update(cx, |message_editor, cx| {
4759 message_editor.insert_selections(window, cx);
4760 })
4761 }
4762
4763 fn render_thread_retry_status_callout(
4764 &self,
4765 _window: &mut Window,
4766 _cx: &mut Context<Self>,
4767 ) -> Option<Callout> {
4768 let state = self.thread_retry_status.as_ref()?;
4769
4770 let next_attempt_in = state
4771 .duration
4772 .saturating_sub(Instant::now().saturating_duration_since(state.started_at));
4773 if next_attempt_in.is_zero() {
4774 return None;
4775 }
4776
4777 let next_attempt_in_secs = next_attempt_in.as_secs() + 1;
4778
4779 let retry_message = if state.max_attempts == 1 {
4780 if next_attempt_in_secs == 1 {
4781 "Retrying. Next attempt in 1 second.".to_string()
4782 } else {
4783 format!("Retrying. Next attempt in {next_attempt_in_secs} seconds.")
4784 }
4785 } else if next_attempt_in_secs == 1 {
4786 format!(
4787 "Retrying. Next attempt in 1 second (Attempt {} of {}).",
4788 state.attempt, state.max_attempts,
4789 )
4790 } else {
4791 format!(
4792 "Retrying. Next attempt in {next_attempt_in_secs} seconds (Attempt {} of {}).",
4793 state.attempt, state.max_attempts,
4794 )
4795 };
4796
4797 Some(
4798 Callout::new()
4799 .severity(Severity::Warning)
4800 .title(state.last_error.clone())
4801 .description(retry_message),
4802 )
4803 }
4804
4805 fn render_thread_error(&self, window: &mut Window, cx: &mut Context<Self>) -> Option<Div> {
4806 let content = match self.thread_error.as_ref()? {
4807 ThreadError::Other(error) => self.render_any_thread_error(error.clone(), cx),
4808 ThreadError::Refusal => self.render_refusal_error(cx),
4809 ThreadError::AuthenticationRequired(error) => {
4810 self.render_authentication_required_error(error.clone(), cx)
4811 }
4812 ThreadError::PaymentRequired => self.render_payment_required_error(cx),
4813 ThreadError::ModelRequestLimitReached(plan) => {
4814 self.render_model_request_limit_reached_error(*plan, cx)
4815 }
4816 ThreadError::ToolUseLimitReached => {
4817 self.render_tool_use_limit_reached_error(window, cx)?
4818 }
4819 };
4820
4821 Some(div().child(content))
4822 }
4823
4824 fn render_new_version_callout(&self, version: &SharedString, cx: &mut Context<Self>) -> Div {
4825 v_flex().w_full().justify_end().child(
4826 h_flex()
4827 .p_2()
4828 .pr_3()
4829 .w_full()
4830 .gap_1p5()
4831 .border_t_1()
4832 .border_color(cx.theme().colors().border)
4833 .bg(cx.theme().colors().element_background)
4834 .child(
4835 h_flex()
4836 .flex_1()
4837 .gap_1p5()
4838 .child(
4839 Icon::new(IconName::Download)
4840 .color(Color::Accent)
4841 .size(IconSize::Small),
4842 )
4843 .child(Label::new("New version available").size(LabelSize::Small)),
4844 )
4845 .child(
4846 Button::new("update-button", format!("Update to v{}", version))
4847 .label_size(LabelSize::Small)
4848 .style(ButtonStyle::Tinted(TintColor::Accent))
4849 .on_click(cx.listener(|this, _, window, cx| {
4850 this.reset(window, cx);
4851 })),
4852 ),
4853 )
4854 }
4855
4856 fn get_current_model_name(&self, cx: &App) -> SharedString {
4857 // For native agent (Zed Agent), use the specific model name (e.g., "Claude 3.5 Sonnet")
4858 // For ACP agents, use the agent name (e.g., "Claude Code", "Gemini CLI")
4859 // This provides better clarity about what refused the request
4860 if self
4861 .agent
4862 .clone()
4863 .downcast::<agent2::NativeAgentServer>()
4864 .is_some()
4865 {
4866 // Native agent - use the model name
4867 self.model_selector
4868 .as_ref()
4869 .and_then(|selector| selector.read(cx).active_model_name(cx))
4870 .unwrap_or_else(|| SharedString::from("The model"))
4871 } else {
4872 // ACP agent - use the agent name (e.g., "Claude Code", "Gemini CLI")
4873 self.agent.name()
4874 }
4875 }
4876
4877 fn render_refusal_error(&self, cx: &mut Context<'_, Self>) -> Callout {
4878 let model_or_agent_name = self.get_current_model_name(cx);
4879 let refusal_message = format!(
4880 "{} 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.",
4881 model_or_agent_name
4882 );
4883
4884 Callout::new()
4885 .severity(Severity::Error)
4886 .title("Request Refused")
4887 .icon(IconName::XCircle)
4888 .description(refusal_message.clone())
4889 .actions_slot(self.create_copy_button(&refusal_message))
4890 .dismiss_action(self.dismiss_error_button(cx))
4891 }
4892
4893 fn render_any_thread_error(&self, error: SharedString, cx: &mut Context<'_, Self>) -> Callout {
4894 let can_resume = self
4895 .thread()
4896 .map_or(false, |thread| thread.read(cx).can_resume(cx));
4897
4898 let can_enable_burn_mode = self.as_native_thread(cx).map_or(false, |thread| {
4899 let thread = thread.read(cx);
4900 let supports_burn_mode = thread
4901 .model()
4902 .map_or(false, |model| model.supports_burn_mode());
4903 supports_burn_mode && thread.completion_mode() == CompletionMode::Normal
4904 });
4905
4906 Callout::new()
4907 .severity(Severity::Error)
4908 .title("Error")
4909 .icon(IconName::XCircle)
4910 .description(error.clone())
4911 .actions_slot(
4912 h_flex()
4913 .gap_0p5()
4914 .when(can_resume && can_enable_burn_mode, |this| {
4915 this.child(
4916 Button::new("enable-burn-mode-and-retry", "Enable Burn Mode and Retry")
4917 .icon(IconName::ZedBurnMode)
4918 .icon_position(IconPosition::Start)
4919 .icon_size(IconSize::Small)
4920 .label_size(LabelSize::Small)
4921 .on_click(cx.listener(|this, _, window, cx| {
4922 this.toggle_burn_mode(&ToggleBurnMode, window, cx);
4923 this.resume_chat(cx);
4924 })),
4925 )
4926 })
4927 .when(can_resume, |this| {
4928 this.child(
4929 Button::new("retry", "Retry")
4930 .icon(IconName::RotateCw)
4931 .icon_position(IconPosition::Start)
4932 .icon_size(IconSize::Small)
4933 .label_size(LabelSize::Small)
4934 .on_click(cx.listener(|this, _, _window, cx| {
4935 this.resume_chat(cx);
4936 })),
4937 )
4938 })
4939 .child(self.create_copy_button(error.to_string())),
4940 )
4941 .dismiss_action(self.dismiss_error_button(cx))
4942 }
4943
4944 fn render_payment_required_error(&self, cx: &mut Context<Self>) -> Callout {
4945 const ERROR_MESSAGE: &str =
4946 "You reached your free usage limit. Upgrade to Zed Pro for more prompts.";
4947
4948 Callout::new()
4949 .severity(Severity::Error)
4950 .icon(IconName::XCircle)
4951 .title("Free Usage Exceeded")
4952 .description(ERROR_MESSAGE)
4953 .actions_slot(
4954 h_flex()
4955 .gap_0p5()
4956 .child(self.upgrade_button(cx))
4957 .child(self.create_copy_button(ERROR_MESSAGE)),
4958 )
4959 .dismiss_action(self.dismiss_error_button(cx))
4960 }
4961
4962 fn render_authentication_required_error(
4963 &self,
4964 error: SharedString,
4965 cx: &mut Context<Self>,
4966 ) -> Callout {
4967 Callout::new()
4968 .severity(Severity::Error)
4969 .title("Authentication Required")
4970 .icon(IconName::XCircle)
4971 .description(error.clone())
4972 .actions_slot(
4973 h_flex()
4974 .gap_0p5()
4975 .child(self.authenticate_button(cx))
4976 .child(self.create_copy_button(error)),
4977 )
4978 .dismiss_action(self.dismiss_error_button(cx))
4979 }
4980
4981 fn render_model_request_limit_reached_error(
4982 &self,
4983 plan: cloud_llm_client::Plan,
4984 cx: &mut Context<Self>,
4985 ) -> Callout {
4986 let error_message = match plan {
4987 cloud_llm_client::Plan::ZedPro => "Upgrade to usage-based billing for more prompts.",
4988 cloud_llm_client::Plan::ZedProTrial | cloud_llm_client::Plan::ZedFree => {
4989 "Upgrade to Zed Pro for more prompts."
4990 }
4991 };
4992
4993 Callout::new()
4994 .severity(Severity::Error)
4995 .title("Model Prompt Limit Reached")
4996 .icon(IconName::XCircle)
4997 .description(error_message)
4998 .actions_slot(
4999 h_flex()
5000 .gap_0p5()
5001 .child(self.upgrade_button(cx))
5002 .child(self.create_copy_button(error_message)),
5003 )
5004 .dismiss_action(self.dismiss_error_button(cx))
5005 }
5006
5007 fn render_tool_use_limit_reached_error(
5008 &self,
5009 window: &mut Window,
5010 cx: &mut Context<Self>,
5011 ) -> Option<Callout> {
5012 let thread = self.as_native_thread(cx)?;
5013 let supports_burn_mode = thread
5014 .read(cx)
5015 .model()
5016 .is_some_and(|model| model.supports_burn_mode());
5017
5018 let focus_handle = self.focus_handle(cx);
5019
5020 Some(
5021 Callout::new()
5022 .icon(IconName::Info)
5023 .title("Consecutive tool use limit reached.")
5024 .actions_slot(
5025 h_flex()
5026 .gap_0p5()
5027 .when(supports_burn_mode, |this| {
5028 this.child(
5029 Button::new("continue-burn-mode", "Continue with Burn Mode")
5030 .style(ButtonStyle::Filled)
5031 .style(ButtonStyle::Tinted(ui::TintColor::Accent))
5032 .layer(ElevationIndex::ModalSurface)
5033 .label_size(LabelSize::Small)
5034 .key_binding(
5035 KeyBinding::for_action_in(
5036 &ContinueWithBurnMode,
5037 &focus_handle,
5038 window,
5039 cx,
5040 )
5041 .map(|kb| kb.size(rems_from_px(10.))),
5042 )
5043 .tooltip(Tooltip::text(
5044 "Enable Burn Mode for unlimited tool use.",
5045 ))
5046 .on_click({
5047 cx.listener(move |this, _, _window, cx| {
5048 thread.update(cx, |thread, cx| {
5049 thread
5050 .set_completion_mode(CompletionMode::Burn, cx);
5051 });
5052 this.resume_chat(cx);
5053 })
5054 }),
5055 )
5056 })
5057 .child(
5058 Button::new("continue-conversation", "Continue")
5059 .layer(ElevationIndex::ModalSurface)
5060 .label_size(LabelSize::Small)
5061 .key_binding(
5062 KeyBinding::for_action_in(
5063 &ContinueThread,
5064 &focus_handle,
5065 window,
5066 cx,
5067 )
5068 .map(|kb| kb.size(rems_from_px(10.))),
5069 )
5070 .on_click(cx.listener(|this, _, _window, cx| {
5071 this.resume_chat(cx);
5072 })),
5073 ),
5074 ),
5075 )
5076 }
5077
5078 fn create_copy_button(&self, message: impl Into<String>) -> impl IntoElement {
5079 let message = message.into();
5080
5081 IconButton::new("copy", IconName::Copy)
5082 .icon_size(IconSize::Small)
5083 .icon_color(Color::Muted)
5084 .tooltip(Tooltip::text("Copy Error Message"))
5085 .on_click(move |_, _, cx| {
5086 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
5087 })
5088 }
5089
5090 fn dismiss_error_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
5091 IconButton::new("dismiss", IconName::Close)
5092 .icon_size(IconSize::Small)
5093 .icon_color(Color::Muted)
5094 .tooltip(Tooltip::text("Dismiss Error"))
5095 .on_click(cx.listener({
5096 move |this, _, _, cx| {
5097 this.clear_thread_error(cx);
5098 cx.notify();
5099 }
5100 }))
5101 }
5102
5103 fn authenticate_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
5104 Button::new("authenticate", "Authenticate")
5105 .label_size(LabelSize::Small)
5106 .style(ButtonStyle::Filled)
5107 .on_click(cx.listener({
5108 move |this, _, window, cx| {
5109 let agent = this.agent.clone();
5110 let ThreadState::Ready { thread, .. } = &this.thread_state else {
5111 return;
5112 };
5113
5114 let connection = thread.read(cx).connection().clone();
5115 let err = AuthRequired {
5116 description: None,
5117 provider_id: None,
5118 };
5119 this.clear_thread_error(cx);
5120 let this = cx.weak_entity();
5121 window.defer(cx, |window, cx| {
5122 Self::handle_auth_required(this, err, agent, connection, window, cx);
5123 })
5124 }
5125 }))
5126 }
5127
5128 pub(crate) fn reauthenticate(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5129 let agent = self.agent.clone();
5130 let ThreadState::Ready { thread, .. } = &self.thread_state else {
5131 return;
5132 };
5133
5134 let connection = thread.read(cx).connection().clone();
5135 let err = AuthRequired {
5136 description: None,
5137 provider_id: None,
5138 };
5139 self.clear_thread_error(cx);
5140 let this = cx.weak_entity();
5141 window.defer(cx, |window, cx| {
5142 Self::handle_auth_required(this, err, agent, connection, window, cx);
5143 })
5144 }
5145
5146 fn upgrade_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
5147 Button::new("upgrade", "Upgrade")
5148 .label_size(LabelSize::Small)
5149 .style(ButtonStyle::Tinted(ui::TintColor::Accent))
5150 .on_click(cx.listener({
5151 move |this, _, _, cx| {
5152 this.clear_thread_error(cx);
5153 cx.open_url(&zed_urls::upgrade_to_zed_pro_url(cx));
5154 }
5155 }))
5156 }
5157
5158 pub fn delete_history_entry(&mut self, entry: HistoryEntry, cx: &mut Context<Self>) {
5159 let task = match entry {
5160 HistoryEntry::AcpThread(thread) => self.history_store.update(cx, |history, cx| {
5161 history.delete_thread(thread.id.clone(), cx)
5162 }),
5163 HistoryEntry::TextThread(context) => self.history_store.update(cx, |history, cx| {
5164 history.delete_text_thread(context.path.clone(), cx)
5165 }),
5166 };
5167 task.detach_and_log_err(cx);
5168 }
5169}
5170
5171fn loading_contents_spinner(size: IconSize) -> AnyElement {
5172 Icon::new(IconName::LoadCircle)
5173 .size(size)
5174 .color(Color::Accent)
5175 .with_rotate_animation(3)
5176 .into_any_element()
5177}
5178
5179impl Focusable for AcpThreadView {
5180 fn focus_handle(&self, cx: &App) -> FocusHandle {
5181 match self.thread_state {
5182 ThreadState::Loading { .. } | ThreadState::Ready { .. } => {
5183 self.message_editor.focus_handle(cx)
5184 }
5185 ThreadState::LoadError(_) | ThreadState::Unauthenticated { .. } => {
5186 self.focus_handle.clone()
5187 }
5188 }
5189 }
5190}
5191
5192impl Render for AcpThreadView {
5193 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
5194 let has_messages = self.list_state.item_count() > 0;
5195 let line_height = TextSize::Small.rems(cx).to_pixels(window.rem_size()) * 1.5;
5196
5197 v_flex()
5198 .size_full()
5199 .key_context("AcpThread")
5200 .on_action(cx.listener(Self::open_agent_diff))
5201 .on_action(cx.listener(Self::toggle_burn_mode))
5202 .on_action(cx.listener(Self::keep_all))
5203 .on_action(cx.listener(Self::reject_all))
5204 .track_focus(&self.focus_handle)
5205 .bg(cx.theme().colors().panel_background)
5206 .child(match &self.thread_state {
5207 ThreadState::Unauthenticated {
5208 connection,
5209 description,
5210 configuration_view,
5211 pending_auth_method,
5212 ..
5213 } => self.render_auth_required_state(
5214 connection,
5215 description.as_ref(),
5216 configuration_view.as_ref(),
5217 pending_auth_method.as_ref(),
5218 window,
5219 cx,
5220 ),
5221 ThreadState::Loading { .. } => v_flex()
5222 .flex_1()
5223 .child(self.render_recent_history(window, cx)),
5224 ThreadState::LoadError(e) => v_flex()
5225 .flex_1()
5226 .size_full()
5227 .items_center()
5228 .justify_end()
5229 .child(self.render_load_error(e, window, cx)),
5230 ThreadState::Ready { .. } => v_flex().flex_1().map(|this| {
5231 if has_messages {
5232 this.child(
5233 list(
5234 self.list_state.clone(),
5235 cx.processor(|this, index: usize, window, cx| {
5236 let Some((entry, len)) = this.thread().and_then(|thread| {
5237 let entries = &thread.read(cx).entries();
5238 Some((entries.get(index)?, entries.len()))
5239 }) else {
5240 return Empty.into_any();
5241 };
5242 this.render_entry(index, len, entry, window, cx)
5243 }),
5244 )
5245 .with_sizing_behavior(gpui::ListSizingBehavior::Auto)
5246 .flex_grow()
5247 .into_any(),
5248 )
5249 .child(self.render_vertical_scrollbar(cx))
5250 } else {
5251 this.child(self.render_recent_history(window, cx))
5252 }
5253 }),
5254 })
5255 // The activity bar is intentionally rendered outside of the ThreadState::Ready match
5256 // above so that the scrollbar doesn't render behind it. The current setup allows
5257 // the scrollbar to stop exactly at the activity bar start.
5258 .when(has_messages, |this| match &self.thread_state {
5259 ThreadState::Ready { thread, .. } => {
5260 this.children(self.render_activity_bar(thread, window, cx))
5261 }
5262 _ => this,
5263 })
5264 .children(self.render_thread_retry_status_callout(window, cx))
5265 .children(self.render_thread_error(window, cx))
5266 .when_some(
5267 self.new_server_version_available.as_ref().filter(|_| {
5268 !has_messages || !matches!(self.thread_state, ThreadState::Ready { .. })
5269 }),
5270 |this, version| this.child(self.render_new_version_callout(&version, cx)),
5271 )
5272 .children(
5273 if let Some(usage_callout) = self.render_usage_callout(line_height, cx) {
5274 Some(usage_callout.into_any_element())
5275 } else {
5276 self.render_token_limit_callout(line_height, cx)
5277 .map(|token_limit_callout| token_limit_callout.into_any_element())
5278 },
5279 )
5280 .child(self.render_message_editor(window, cx))
5281 }
5282}
5283
5284fn default_markdown_style(
5285 buffer_font: bool,
5286 muted_text: bool,
5287 window: &Window,
5288 cx: &App,
5289) -> MarkdownStyle {
5290 let theme_settings = ThemeSettings::get_global(cx);
5291 let colors = cx.theme().colors();
5292
5293 let buffer_font_size = TextSize::Small.rems(cx);
5294
5295 let mut text_style = window.text_style();
5296 let line_height = buffer_font_size * 1.75;
5297
5298 let font_family = if buffer_font {
5299 theme_settings.buffer_font.family.clone()
5300 } else {
5301 theme_settings.ui_font.family.clone()
5302 };
5303
5304 let font_size = if buffer_font {
5305 TextSize::Small.rems(cx)
5306 } else {
5307 TextSize::Default.rems(cx)
5308 };
5309
5310 let text_color = if muted_text {
5311 colors.text_muted
5312 } else {
5313 colors.text
5314 };
5315
5316 text_style.refine(&TextStyleRefinement {
5317 font_family: Some(font_family),
5318 font_fallbacks: theme_settings.ui_font.fallbacks.clone(),
5319 font_features: Some(theme_settings.ui_font.features.clone()),
5320 font_size: Some(font_size.into()),
5321 line_height: Some(line_height.into()),
5322 color: Some(text_color),
5323 ..Default::default()
5324 });
5325
5326 MarkdownStyle {
5327 base_text_style: text_style.clone(),
5328 syntax: cx.theme().syntax().clone(),
5329 selection_background_color: colors.element_selection_background,
5330 code_block_overflow_x_scroll: true,
5331 table_overflow_x_scroll: true,
5332 heading_level_styles: Some(HeadingLevelStyles {
5333 h1: Some(TextStyleRefinement {
5334 font_size: Some(rems(1.15).into()),
5335 ..Default::default()
5336 }),
5337 h2: Some(TextStyleRefinement {
5338 font_size: Some(rems(1.1).into()),
5339 ..Default::default()
5340 }),
5341 h3: Some(TextStyleRefinement {
5342 font_size: Some(rems(1.05).into()),
5343 ..Default::default()
5344 }),
5345 h4: Some(TextStyleRefinement {
5346 font_size: Some(rems(1.).into()),
5347 ..Default::default()
5348 }),
5349 h5: Some(TextStyleRefinement {
5350 font_size: Some(rems(0.95).into()),
5351 ..Default::default()
5352 }),
5353 h6: Some(TextStyleRefinement {
5354 font_size: Some(rems(0.875).into()),
5355 ..Default::default()
5356 }),
5357 }),
5358 code_block: StyleRefinement {
5359 padding: EdgesRefinement {
5360 top: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
5361 left: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
5362 right: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
5363 bottom: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
5364 },
5365 margin: EdgesRefinement {
5366 top: Some(Length::Definite(Pixels(8.).into())),
5367 left: Some(Length::Definite(Pixels(0.).into())),
5368 right: Some(Length::Definite(Pixels(0.).into())),
5369 bottom: Some(Length::Definite(Pixels(12.).into())),
5370 },
5371 border_style: Some(BorderStyle::Solid),
5372 border_widths: EdgesRefinement {
5373 top: Some(AbsoluteLength::Pixels(Pixels(1.))),
5374 left: Some(AbsoluteLength::Pixels(Pixels(1.))),
5375 right: Some(AbsoluteLength::Pixels(Pixels(1.))),
5376 bottom: Some(AbsoluteLength::Pixels(Pixels(1.))),
5377 },
5378 border_color: Some(colors.border_variant),
5379 background: Some(colors.editor_background.into()),
5380 text: Some(TextStyleRefinement {
5381 font_family: Some(theme_settings.buffer_font.family.clone()),
5382 font_fallbacks: theme_settings.buffer_font.fallbacks.clone(),
5383 font_features: Some(theme_settings.buffer_font.features.clone()),
5384 font_size: Some(buffer_font_size.into()),
5385 ..Default::default()
5386 }),
5387 ..Default::default()
5388 },
5389 inline_code: TextStyleRefinement {
5390 font_family: Some(theme_settings.buffer_font.family.clone()),
5391 font_fallbacks: theme_settings.buffer_font.fallbacks.clone(),
5392 font_features: Some(theme_settings.buffer_font.features.clone()),
5393 font_size: Some(buffer_font_size.into()),
5394 background_color: Some(colors.editor_foreground.opacity(0.08)),
5395 ..Default::default()
5396 },
5397 link: TextStyleRefinement {
5398 background_color: Some(colors.editor_foreground.opacity(0.025)),
5399 underline: Some(UnderlineStyle {
5400 color: Some(colors.text_accent.opacity(0.5)),
5401 thickness: px(1.),
5402 ..Default::default()
5403 }),
5404 ..Default::default()
5405 },
5406 ..Default::default()
5407 }
5408}
5409
5410fn plan_label_markdown_style(
5411 status: &acp::PlanEntryStatus,
5412 window: &Window,
5413 cx: &App,
5414) -> MarkdownStyle {
5415 let default_md_style = default_markdown_style(false, false, window, cx);
5416
5417 MarkdownStyle {
5418 base_text_style: TextStyle {
5419 color: cx.theme().colors().text_muted,
5420 strikethrough: if matches!(status, acp::PlanEntryStatus::Completed) {
5421 Some(gpui::StrikethroughStyle {
5422 thickness: px(1.),
5423 color: Some(cx.theme().colors().text_muted.opacity(0.8)),
5424 })
5425 } else {
5426 None
5427 },
5428 ..default_md_style.base_text_style
5429 },
5430 ..default_md_style
5431 }
5432}
5433
5434fn terminal_command_markdown_style(window: &Window, cx: &App) -> MarkdownStyle {
5435 let default_md_style = default_markdown_style(true, false, window, cx);
5436
5437 MarkdownStyle {
5438 base_text_style: TextStyle {
5439 ..default_md_style.base_text_style
5440 },
5441 selection_background_color: cx.theme().colors().element_selection_background,
5442 ..Default::default()
5443 }
5444}
5445
5446#[cfg(test)]
5447pub(crate) mod tests {
5448 use acp_thread::StubAgentConnection;
5449 use agent_client_protocol::SessionId;
5450 use assistant_context::ContextStore;
5451 use editor::EditorSettings;
5452 use fs::FakeFs;
5453 use gpui::{EventEmitter, SemanticVersion, TestAppContext, VisualTestContext};
5454 use project::Project;
5455 use serde_json::json;
5456 use settings::SettingsStore;
5457 use std::any::Any;
5458 use std::path::Path;
5459 use workspace::Item;
5460
5461 use super::*;
5462
5463 #[gpui::test]
5464 async fn test_drop(cx: &mut TestAppContext) {
5465 init_test(cx);
5466
5467 let (thread_view, _cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
5468 let weak_view = thread_view.downgrade();
5469 drop(thread_view);
5470 assert!(!weak_view.is_upgradable());
5471 }
5472
5473 #[gpui::test]
5474 async fn test_notification_for_stop_event(cx: &mut TestAppContext) {
5475 init_test(cx);
5476
5477 let (thread_view, cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
5478
5479 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
5480 message_editor.update_in(cx, |editor, window, cx| {
5481 editor.set_text("Hello", window, cx);
5482 });
5483
5484 cx.deactivate_window();
5485
5486 thread_view.update_in(cx, |thread_view, window, cx| {
5487 thread_view.send(window, cx);
5488 });
5489
5490 cx.run_until_parked();
5491
5492 assert!(
5493 cx.windows()
5494 .iter()
5495 .any(|window| window.downcast::<AgentNotification>().is_some())
5496 );
5497 }
5498
5499 #[gpui::test]
5500 async fn test_notification_for_error(cx: &mut TestAppContext) {
5501 init_test(cx);
5502
5503 let (thread_view, cx) =
5504 setup_thread_view(StubAgentServer::new(SaboteurAgentConnection), cx).await;
5505
5506 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
5507 message_editor.update_in(cx, |editor, window, cx| {
5508 editor.set_text("Hello", window, cx);
5509 });
5510
5511 cx.deactivate_window();
5512
5513 thread_view.update_in(cx, |thread_view, window, cx| {
5514 thread_view.send(window, cx);
5515 });
5516
5517 cx.run_until_parked();
5518
5519 assert!(
5520 cx.windows()
5521 .iter()
5522 .any(|window| window.downcast::<AgentNotification>().is_some())
5523 );
5524 }
5525
5526 #[gpui::test]
5527 async fn test_refusal_handling(cx: &mut TestAppContext) {
5528 init_test(cx);
5529
5530 let (thread_view, cx) =
5531 setup_thread_view(StubAgentServer::new(RefusalAgentConnection), cx).await;
5532
5533 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
5534 message_editor.update_in(cx, |editor, window, cx| {
5535 editor.set_text("Do something harmful", window, cx);
5536 });
5537
5538 thread_view.update_in(cx, |thread_view, window, cx| {
5539 thread_view.send(window, cx);
5540 });
5541
5542 cx.run_until_parked();
5543
5544 // Check that the refusal error is set
5545 thread_view.read_with(cx, |thread_view, _cx| {
5546 assert!(
5547 matches!(thread_view.thread_error, Some(ThreadError::Refusal)),
5548 "Expected refusal error to be set"
5549 );
5550 });
5551 }
5552
5553 #[gpui::test]
5554 async fn test_notification_for_tool_authorization(cx: &mut TestAppContext) {
5555 init_test(cx);
5556
5557 let tool_call_id = acp::ToolCallId("1".into());
5558 let tool_call = acp::ToolCall {
5559 id: tool_call_id.clone(),
5560 title: "Label".into(),
5561 kind: acp::ToolKind::Edit,
5562 status: acp::ToolCallStatus::Pending,
5563 content: vec!["hi".into()],
5564 locations: vec![],
5565 raw_input: None,
5566 raw_output: None,
5567 };
5568 let connection =
5569 StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
5570 tool_call_id,
5571 vec![acp::PermissionOption {
5572 id: acp::PermissionOptionId("1".into()),
5573 name: "Allow".into(),
5574 kind: acp::PermissionOptionKind::AllowOnce,
5575 }],
5576 )]));
5577
5578 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
5579
5580 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
5581
5582 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
5583 message_editor.update_in(cx, |editor, window, cx| {
5584 editor.set_text("Hello", window, cx);
5585 });
5586
5587 cx.deactivate_window();
5588
5589 thread_view.update_in(cx, |thread_view, window, cx| {
5590 thread_view.send(window, cx);
5591 });
5592
5593 cx.run_until_parked();
5594
5595 assert!(
5596 cx.windows()
5597 .iter()
5598 .any(|window| window.downcast::<AgentNotification>().is_some())
5599 );
5600 }
5601
5602 async fn setup_thread_view(
5603 agent: impl AgentServer + 'static,
5604 cx: &mut TestAppContext,
5605 ) -> (Entity<AcpThreadView>, &mut VisualTestContext) {
5606 let fs = FakeFs::new(cx.executor());
5607 let project = Project::test(fs, [], cx).await;
5608 let (workspace, cx) =
5609 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5610
5611 let context_store =
5612 cx.update(|_window, cx| cx.new(|cx| ContextStore::fake(project.clone(), cx)));
5613 let history_store =
5614 cx.update(|_window, cx| cx.new(|cx| HistoryStore::new(context_store, cx)));
5615
5616 let thread_view = cx.update(|window, cx| {
5617 cx.new(|cx| {
5618 AcpThreadView::new(
5619 Rc::new(agent),
5620 None,
5621 None,
5622 workspace.downgrade(),
5623 project,
5624 history_store,
5625 None,
5626 window,
5627 cx,
5628 )
5629 })
5630 });
5631 cx.run_until_parked();
5632 (thread_view, cx)
5633 }
5634
5635 fn add_to_workspace(thread_view: Entity<AcpThreadView>, cx: &mut VisualTestContext) {
5636 let workspace = thread_view.read_with(cx, |thread_view, _cx| thread_view.workspace.clone());
5637
5638 workspace
5639 .update_in(cx, |workspace, window, cx| {
5640 workspace.add_item_to_active_pane(
5641 Box::new(cx.new(|_| ThreadViewItem(thread_view.clone()))),
5642 None,
5643 true,
5644 window,
5645 cx,
5646 );
5647 })
5648 .unwrap();
5649 }
5650
5651 struct ThreadViewItem(Entity<AcpThreadView>);
5652
5653 impl Item for ThreadViewItem {
5654 type Event = ();
5655
5656 fn include_in_nav_history() -> bool {
5657 false
5658 }
5659
5660 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
5661 "Test".into()
5662 }
5663 }
5664
5665 impl EventEmitter<()> for ThreadViewItem {}
5666
5667 impl Focusable for ThreadViewItem {
5668 fn focus_handle(&self, cx: &App) -> FocusHandle {
5669 self.0.read(cx).focus_handle(cx)
5670 }
5671 }
5672
5673 impl Render for ThreadViewItem {
5674 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
5675 self.0.clone().into_any_element()
5676 }
5677 }
5678
5679 struct StubAgentServer<C> {
5680 connection: C,
5681 }
5682
5683 impl<C> StubAgentServer<C> {
5684 fn new(connection: C) -> Self {
5685 Self { connection }
5686 }
5687 }
5688
5689 impl StubAgentServer<StubAgentConnection> {
5690 fn default_response() -> Self {
5691 let conn = StubAgentConnection::new();
5692 conn.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk {
5693 content: "Default response".into(),
5694 }]);
5695 Self::new(conn)
5696 }
5697 }
5698
5699 impl<C> AgentServer for StubAgentServer<C>
5700 where
5701 C: 'static + AgentConnection + Send + Clone,
5702 {
5703 fn telemetry_id(&self) -> &'static str {
5704 "test"
5705 }
5706
5707 fn logo(&self) -> ui::IconName {
5708 ui::IconName::Ai
5709 }
5710
5711 fn name(&self) -> SharedString {
5712 "Test".into()
5713 }
5714
5715 fn connect(
5716 &self,
5717 _root_dir: &Path,
5718 _delegate: AgentServerDelegate,
5719 _cx: &mut App,
5720 ) -> Task<gpui::Result<Rc<dyn AgentConnection>>> {
5721 Task::ready(Ok(Rc::new(self.connection.clone())))
5722 }
5723
5724 fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
5725 self
5726 }
5727 }
5728
5729 #[derive(Clone)]
5730 struct SaboteurAgentConnection;
5731
5732 impl AgentConnection for SaboteurAgentConnection {
5733 fn new_thread(
5734 self: Rc<Self>,
5735 project: Entity<Project>,
5736 _cwd: &Path,
5737 cx: &mut gpui::App,
5738 ) -> Task<gpui::Result<Entity<AcpThread>>> {
5739 Task::ready(Ok(cx.new(|cx| {
5740 let action_log = cx.new(|_| ActionLog::new(project.clone()));
5741 AcpThread::new(
5742 "SaboteurAgentConnection",
5743 self,
5744 project,
5745 action_log,
5746 SessionId("test".into()),
5747 watch::Receiver::constant(acp::PromptCapabilities {
5748 image: true,
5749 audio: true,
5750 embedded_context: true,
5751 }),
5752 cx,
5753 )
5754 })))
5755 }
5756
5757 fn auth_methods(&self) -> &[acp::AuthMethod] {
5758 &[]
5759 }
5760
5761 fn authenticate(
5762 &self,
5763 _method_id: acp::AuthMethodId,
5764 _cx: &mut App,
5765 ) -> Task<gpui::Result<()>> {
5766 unimplemented!()
5767 }
5768
5769 fn prompt(
5770 &self,
5771 _id: Option<acp_thread::UserMessageId>,
5772 _params: acp::PromptRequest,
5773 _cx: &mut App,
5774 ) -> Task<gpui::Result<acp::PromptResponse>> {
5775 Task::ready(Err(anyhow::anyhow!("Error prompting")))
5776 }
5777
5778 fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {
5779 unimplemented!()
5780 }
5781
5782 fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
5783 self
5784 }
5785 }
5786
5787 /// Simulates a model which always returns a refusal response
5788 #[derive(Clone)]
5789 struct RefusalAgentConnection;
5790
5791 impl AgentConnection for RefusalAgentConnection {
5792 fn new_thread(
5793 self: Rc<Self>,
5794 project: Entity<Project>,
5795 _cwd: &Path,
5796 cx: &mut gpui::App,
5797 ) -> Task<gpui::Result<Entity<AcpThread>>> {
5798 Task::ready(Ok(cx.new(|cx| {
5799 let action_log = cx.new(|_| ActionLog::new(project.clone()));
5800 AcpThread::new(
5801 "RefusalAgentConnection",
5802 self,
5803 project,
5804 action_log,
5805 SessionId("test".into()),
5806 watch::Receiver::constant(acp::PromptCapabilities {
5807 image: true,
5808 audio: true,
5809 embedded_context: true,
5810 }),
5811 cx,
5812 )
5813 })))
5814 }
5815
5816 fn auth_methods(&self) -> &[acp::AuthMethod] {
5817 &[]
5818 }
5819
5820 fn authenticate(
5821 &self,
5822 _method_id: acp::AuthMethodId,
5823 _cx: &mut App,
5824 ) -> Task<gpui::Result<()>> {
5825 unimplemented!()
5826 }
5827
5828 fn prompt(
5829 &self,
5830 _id: Option<acp_thread::UserMessageId>,
5831 _params: acp::PromptRequest,
5832 _cx: &mut App,
5833 ) -> Task<gpui::Result<acp::PromptResponse>> {
5834 Task::ready(Ok(acp::PromptResponse {
5835 stop_reason: acp::StopReason::Refusal,
5836 }))
5837 }
5838
5839 fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {
5840 unimplemented!()
5841 }
5842
5843 fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
5844 self
5845 }
5846 }
5847
5848 pub(crate) fn init_test(cx: &mut TestAppContext) {
5849 cx.update(|cx| {
5850 let settings_store = SettingsStore::test(cx);
5851 cx.set_global(settings_store);
5852 language::init(cx);
5853 Project::init_settings(cx);
5854 AgentSettings::register(cx);
5855 workspace::init_settings(cx);
5856 ThemeSettings::register(cx);
5857 release_channel::init(SemanticVersion::default(), cx);
5858 EditorSettings::register(cx);
5859 prompt_store::init(cx)
5860 });
5861 }
5862
5863 #[gpui::test]
5864 async fn test_rewind_views(cx: &mut TestAppContext) {
5865 init_test(cx);
5866
5867 let fs = FakeFs::new(cx.executor());
5868 fs.insert_tree(
5869 "/project",
5870 json!({
5871 "test1.txt": "old content 1",
5872 "test2.txt": "old content 2"
5873 }),
5874 )
5875 .await;
5876 let project = Project::test(fs, [Path::new("/project")], cx).await;
5877 let (workspace, cx) =
5878 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5879
5880 let context_store =
5881 cx.update(|_window, cx| cx.new(|cx| ContextStore::fake(project.clone(), cx)));
5882 let history_store =
5883 cx.update(|_window, cx| cx.new(|cx| HistoryStore::new(context_store, cx)));
5884
5885 let connection = Rc::new(StubAgentConnection::new());
5886 let thread_view = cx.update(|window, cx| {
5887 cx.new(|cx| {
5888 AcpThreadView::new(
5889 Rc::new(StubAgentServer::new(connection.as_ref().clone())),
5890 None,
5891 None,
5892 workspace.downgrade(),
5893 project.clone(),
5894 history_store.clone(),
5895 None,
5896 window,
5897 cx,
5898 )
5899 })
5900 });
5901
5902 cx.run_until_parked();
5903
5904 let thread = thread_view
5905 .read_with(cx, |view, _| view.thread().cloned())
5906 .unwrap();
5907
5908 // First user message
5909 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(acp::ToolCall {
5910 id: acp::ToolCallId("tool1".into()),
5911 title: "Edit file 1".into(),
5912 kind: acp::ToolKind::Edit,
5913 status: acp::ToolCallStatus::Completed,
5914 content: vec![acp::ToolCallContent::Diff {
5915 diff: acp::Diff {
5916 path: "/project/test1.txt".into(),
5917 old_text: Some("old content 1".into()),
5918 new_text: "new content 1".into(),
5919 },
5920 }],
5921 locations: vec![],
5922 raw_input: None,
5923 raw_output: None,
5924 })]);
5925
5926 thread
5927 .update(cx, |thread, cx| thread.send_raw("Give me a diff", cx))
5928 .await
5929 .unwrap();
5930 cx.run_until_parked();
5931
5932 thread.read_with(cx, |thread, _| {
5933 assert_eq!(thread.entries().len(), 2);
5934 });
5935
5936 thread_view.read_with(cx, |view, cx| {
5937 view.entry_view_state.read_with(cx, |entry_view_state, _| {
5938 assert!(
5939 entry_view_state
5940 .entry(0)
5941 .unwrap()
5942 .message_editor()
5943 .is_some()
5944 );
5945 assert!(entry_view_state.entry(1).unwrap().has_content());
5946 });
5947 });
5948
5949 // Second user message
5950 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(acp::ToolCall {
5951 id: acp::ToolCallId("tool2".into()),
5952 title: "Edit file 2".into(),
5953 kind: acp::ToolKind::Edit,
5954 status: acp::ToolCallStatus::Completed,
5955 content: vec![acp::ToolCallContent::Diff {
5956 diff: acp::Diff {
5957 path: "/project/test2.txt".into(),
5958 old_text: Some("old content 2".into()),
5959 new_text: "new content 2".into(),
5960 },
5961 }],
5962 locations: vec![],
5963 raw_input: None,
5964 raw_output: None,
5965 })]);
5966
5967 thread
5968 .update(cx, |thread, cx| thread.send_raw("Another one", cx))
5969 .await
5970 .unwrap();
5971 cx.run_until_parked();
5972
5973 let second_user_message_id = thread.read_with(cx, |thread, _| {
5974 assert_eq!(thread.entries().len(), 4);
5975 let AgentThreadEntry::UserMessage(user_message) = &thread.entries()[2] else {
5976 panic!();
5977 };
5978 user_message.id.clone().unwrap()
5979 });
5980
5981 thread_view.read_with(cx, |view, cx| {
5982 view.entry_view_state.read_with(cx, |entry_view_state, _| {
5983 assert!(
5984 entry_view_state
5985 .entry(0)
5986 .unwrap()
5987 .message_editor()
5988 .is_some()
5989 );
5990 assert!(entry_view_state.entry(1).unwrap().has_content());
5991 assert!(
5992 entry_view_state
5993 .entry(2)
5994 .unwrap()
5995 .message_editor()
5996 .is_some()
5997 );
5998 assert!(entry_view_state.entry(3).unwrap().has_content());
5999 });
6000 });
6001
6002 // Rewind to first message
6003 thread
6004 .update(cx, |thread, cx| thread.rewind(second_user_message_id, cx))
6005 .await
6006 .unwrap();
6007
6008 cx.run_until_parked();
6009
6010 thread.read_with(cx, |thread, _| {
6011 assert_eq!(thread.entries().len(), 2);
6012 });
6013
6014 thread_view.read_with(cx, |view, cx| {
6015 view.entry_view_state.read_with(cx, |entry_view_state, _| {
6016 assert!(
6017 entry_view_state
6018 .entry(0)
6019 .unwrap()
6020 .message_editor()
6021 .is_some()
6022 );
6023 assert!(entry_view_state.entry(1).unwrap().has_content());
6024
6025 // Old views should be dropped
6026 assert!(entry_view_state.entry(2).is_none());
6027 assert!(entry_view_state.entry(3).is_none());
6028 });
6029 });
6030 }
6031
6032 #[gpui::test]
6033 async fn test_message_editing_cancel(cx: &mut TestAppContext) {
6034 init_test(cx);
6035
6036 let connection = StubAgentConnection::new();
6037
6038 connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk {
6039 content: acp::ContentBlock::Text(acp::TextContent {
6040 text: "Response".into(),
6041 annotations: None,
6042 }),
6043 }]);
6044
6045 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
6046 add_to_workspace(thread_view.clone(), cx);
6047
6048 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
6049 message_editor.update_in(cx, |editor, window, cx| {
6050 editor.set_text("Original message to edit", window, cx);
6051 });
6052 thread_view.update_in(cx, |thread_view, window, cx| {
6053 thread_view.send(window, cx);
6054 });
6055
6056 cx.run_until_parked();
6057
6058 let user_message_editor = thread_view.read_with(cx, |view, cx| {
6059 assert_eq!(view.editing_message, None);
6060
6061 view.entry_view_state
6062 .read(cx)
6063 .entry(0)
6064 .unwrap()
6065 .message_editor()
6066 .unwrap()
6067 .clone()
6068 });
6069
6070 // Focus
6071 cx.focus(&user_message_editor);
6072 thread_view.read_with(cx, |view, _cx| {
6073 assert_eq!(view.editing_message, Some(0));
6074 });
6075
6076 // Edit
6077 user_message_editor.update_in(cx, |editor, window, cx| {
6078 editor.set_text("Edited message content", window, cx);
6079 });
6080
6081 // Cancel
6082 user_message_editor.update_in(cx, |_editor, window, cx| {
6083 window.dispatch_action(Box::new(editor::actions::Cancel), cx);
6084 });
6085
6086 thread_view.read_with(cx, |view, _cx| {
6087 assert_eq!(view.editing_message, None);
6088 });
6089
6090 user_message_editor.read_with(cx, |editor, cx| {
6091 assert_eq!(editor.text(cx), "Original message to edit");
6092 });
6093 }
6094
6095 #[gpui::test]
6096 async fn test_message_doesnt_send_if_empty(cx: &mut TestAppContext) {
6097 init_test(cx);
6098
6099 let connection = StubAgentConnection::new();
6100
6101 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
6102 add_to_workspace(thread_view.clone(), cx);
6103
6104 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
6105 let mut events = cx.events(&message_editor);
6106 message_editor.update_in(cx, |editor, window, cx| {
6107 editor.set_text("", window, cx);
6108 });
6109
6110 message_editor.update_in(cx, |_editor, window, cx| {
6111 window.dispatch_action(Box::new(Chat), cx);
6112 });
6113 cx.run_until_parked();
6114 // We shouldn't have received any messages
6115 assert!(matches!(
6116 events.try_next(),
6117 Err(futures::channel::mpsc::TryRecvError { .. })
6118 ));
6119 }
6120
6121 #[gpui::test]
6122 async fn test_message_editing_regenerate(cx: &mut TestAppContext) {
6123 init_test(cx);
6124
6125 let connection = StubAgentConnection::new();
6126
6127 connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk {
6128 content: acp::ContentBlock::Text(acp::TextContent {
6129 text: "Response".into(),
6130 annotations: None,
6131 }),
6132 }]);
6133
6134 let (thread_view, cx) =
6135 setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
6136 add_to_workspace(thread_view.clone(), cx);
6137
6138 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
6139 message_editor.update_in(cx, |editor, window, cx| {
6140 editor.set_text("Original message to edit", window, cx);
6141 });
6142 thread_view.update_in(cx, |thread_view, window, cx| {
6143 thread_view.send(window, cx);
6144 });
6145
6146 cx.run_until_parked();
6147
6148 let user_message_editor = thread_view.read_with(cx, |view, cx| {
6149 assert_eq!(view.editing_message, None);
6150 assert_eq!(view.thread().unwrap().read(cx).entries().len(), 2);
6151
6152 view.entry_view_state
6153 .read(cx)
6154 .entry(0)
6155 .unwrap()
6156 .message_editor()
6157 .unwrap()
6158 .clone()
6159 });
6160
6161 // Focus
6162 cx.focus(&user_message_editor);
6163
6164 // Edit
6165 user_message_editor.update_in(cx, |editor, window, cx| {
6166 editor.set_text("Edited message content", window, cx);
6167 });
6168
6169 // Send
6170 connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk {
6171 content: acp::ContentBlock::Text(acp::TextContent {
6172 text: "New Response".into(),
6173 annotations: None,
6174 }),
6175 }]);
6176
6177 user_message_editor.update_in(cx, |_editor, window, cx| {
6178 window.dispatch_action(Box::new(Chat), cx);
6179 });
6180
6181 cx.run_until_parked();
6182
6183 thread_view.read_with(cx, |view, cx| {
6184 assert_eq!(view.editing_message, None);
6185
6186 let entries = view.thread().unwrap().read(cx).entries();
6187 assert_eq!(entries.len(), 2);
6188 assert_eq!(
6189 entries[0].to_markdown(cx),
6190 "## User\n\nEdited message content\n\n"
6191 );
6192 assert_eq!(
6193 entries[1].to_markdown(cx),
6194 "## Assistant\n\nNew Response\n\n"
6195 );
6196
6197 let new_editor = view.entry_view_state.read_with(cx, |state, _cx| {
6198 assert!(!state.entry(1).unwrap().has_content());
6199 state.entry(0).unwrap().message_editor().unwrap().clone()
6200 });
6201
6202 assert_eq!(new_editor.read(cx).text(cx), "Edited message content");
6203 })
6204 }
6205
6206 #[gpui::test]
6207 async fn test_message_editing_while_generating(cx: &mut TestAppContext) {
6208 init_test(cx);
6209
6210 let connection = StubAgentConnection::new();
6211
6212 let (thread_view, cx) =
6213 setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
6214 add_to_workspace(thread_view.clone(), cx);
6215
6216 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
6217 message_editor.update_in(cx, |editor, window, cx| {
6218 editor.set_text("Original message to edit", window, cx);
6219 });
6220 thread_view.update_in(cx, |thread_view, window, cx| {
6221 thread_view.send(window, cx);
6222 });
6223
6224 cx.run_until_parked();
6225
6226 let (user_message_editor, session_id) = thread_view.read_with(cx, |view, cx| {
6227 let thread = view.thread().unwrap().read(cx);
6228 assert_eq!(thread.entries().len(), 1);
6229
6230 let editor = view
6231 .entry_view_state
6232 .read(cx)
6233 .entry(0)
6234 .unwrap()
6235 .message_editor()
6236 .unwrap()
6237 .clone();
6238
6239 (editor, thread.session_id().clone())
6240 });
6241
6242 // Focus
6243 cx.focus(&user_message_editor);
6244
6245 thread_view.read_with(cx, |view, _cx| {
6246 assert_eq!(view.editing_message, Some(0));
6247 });
6248
6249 // Edit
6250 user_message_editor.update_in(cx, |editor, window, cx| {
6251 editor.set_text("Edited message content", window, cx);
6252 });
6253
6254 thread_view.read_with(cx, |view, _cx| {
6255 assert_eq!(view.editing_message, Some(0));
6256 });
6257
6258 // Finish streaming response
6259 cx.update(|_, cx| {
6260 connection.send_update(
6261 session_id.clone(),
6262 acp::SessionUpdate::AgentMessageChunk {
6263 content: acp::ContentBlock::Text(acp::TextContent {
6264 text: "Response".into(),
6265 annotations: None,
6266 }),
6267 },
6268 cx,
6269 );
6270 connection.end_turn(session_id, acp::StopReason::EndTurn);
6271 });
6272
6273 thread_view.read_with(cx, |view, _cx| {
6274 assert_eq!(view.editing_message, Some(0));
6275 });
6276
6277 cx.run_until_parked();
6278
6279 // Should still be editing
6280 cx.update(|window, cx| {
6281 assert!(user_message_editor.focus_handle(cx).is_focused(window));
6282 assert_eq!(thread_view.read(cx).editing_message, Some(0));
6283 assert_eq!(
6284 user_message_editor.read(cx).text(cx),
6285 "Edited message content"
6286 );
6287 });
6288 }
6289
6290 #[gpui::test]
6291 async fn test_interrupt(cx: &mut TestAppContext) {
6292 init_test(cx);
6293
6294 let connection = StubAgentConnection::new();
6295
6296 let (thread_view, cx) =
6297 setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
6298 add_to_workspace(thread_view.clone(), cx);
6299
6300 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
6301 message_editor.update_in(cx, |editor, window, cx| {
6302 editor.set_text("Message 1", window, cx);
6303 });
6304 thread_view.update_in(cx, |thread_view, window, cx| {
6305 thread_view.send(window, cx);
6306 });
6307
6308 let (thread, session_id) = thread_view.read_with(cx, |view, cx| {
6309 let thread = view.thread().unwrap();
6310
6311 (thread.clone(), thread.read(cx).session_id().clone())
6312 });
6313
6314 cx.run_until_parked();
6315
6316 cx.update(|_, cx| {
6317 connection.send_update(
6318 session_id.clone(),
6319 acp::SessionUpdate::AgentMessageChunk {
6320 content: "Message 1 resp".into(),
6321 },
6322 cx,
6323 );
6324 });
6325
6326 cx.run_until_parked();
6327
6328 thread.read_with(cx, |thread, cx| {
6329 assert_eq!(
6330 thread.to_markdown(cx),
6331 indoc::indoc! {"
6332 ## User
6333
6334 Message 1
6335
6336 ## Assistant
6337
6338 Message 1 resp
6339
6340 "}
6341 )
6342 });
6343
6344 message_editor.update_in(cx, |editor, window, cx| {
6345 editor.set_text("Message 2", window, cx);
6346 });
6347 thread_view.update_in(cx, |thread_view, window, cx| {
6348 thread_view.send(window, cx);
6349 });
6350
6351 cx.update(|_, cx| {
6352 // Simulate a response sent after beginning to cancel
6353 connection.send_update(
6354 session_id.clone(),
6355 acp::SessionUpdate::AgentMessageChunk {
6356 content: "onse".into(),
6357 },
6358 cx,
6359 );
6360 });
6361
6362 cx.run_until_parked();
6363
6364 // Last Message 1 response should appear before Message 2
6365 thread.read_with(cx, |thread, cx| {
6366 assert_eq!(
6367 thread.to_markdown(cx),
6368 indoc::indoc! {"
6369 ## User
6370
6371 Message 1
6372
6373 ## Assistant
6374
6375 Message 1 response
6376
6377 ## User
6378
6379 Message 2
6380
6381 "}
6382 )
6383 });
6384
6385 cx.update(|_, cx| {
6386 connection.send_update(
6387 session_id.clone(),
6388 acp::SessionUpdate::AgentMessageChunk {
6389 content: "Message 2 response".into(),
6390 },
6391 cx,
6392 );
6393 connection.end_turn(session_id.clone(), acp::StopReason::EndTurn);
6394 });
6395
6396 cx.run_until_parked();
6397
6398 thread.read_with(cx, |thread, cx| {
6399 assert_eq!(
6400 thread.to_markdown(cx),
6401 indoc::indoc! {"
6402 ## User
6403
6404 Message 1
6405
6406 ## Assistant
6407
6408 Message 1 response
6409
6410 ## User
6411
6412 Message 2
6413
6414 ## Assistant
6415
6416 Message 2 response
6417
6418 "}
6419 )
6420 });
6421 }
6422}