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::{ANTHROPIC_PROVIDER_ID, 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 && provider_id != ANTHROPIC_PROVIDER_ID
677 {
678 let registry = LanguageModelRegistry::global(cx);
679
680 let sub = window.subscribe(®istry, cx, {
681 let provider_id = provider_id.clone();
682 let this = this.clone();
683 move |_, ev, window, cx| {
684 if let language_model::Event::ProviderStateChanged(updated_provider_id) = &ev
685 && &provider_id == updated_provider_id
686 && LanguageModelRegistry::global(cx)
687 .read(cx)
688 .provider(&provider_id)
689 .map_or(false, |provider| provider.is_authenticated(cx))
690 {
691 this.update(cx, |this, cx| {
692 this.reset(window, cx);
693 })
694 .ok();
695 }
696 }
697 });
698
699 let view = registry.read(cx).provider(&provider_id).map(|provider| {
700 provider.configuration_view(
701 language_model::ConfigurationViewTargetAgent::Other(agent_name.clone()),
702 window,
703 cx,
704 )
705 });
706
707 (view, Some(sub))
708 } else {
709 (None, None)
710 };
711
712 this.update(cx, |this, cx| {
713 this.thread_state = ThreadState::Unauthenticated {
714 pending_auth_method: None,
715 connection,
716 configuration_view,
717 description: err
718 .description
719 .clone()
720 .map(|desc| cx.new(|cx| Markdown::new(desc.into(), None, None, cx))),
721 _subscription: subscription,
722 };
723 if this.message_editor.focus_handle(cx).is_focused(window) {
724 this.focus_handle.focus(window)
725 }
726 cx.notify();
727 })
728 .ok();
729 }
730
731 fn handle_load_error(
732 &mut self,
733 err: anyhow::Error,
734 window: &mut Window,
735 cx: &mut Context<Self>,
736 ) {
737 if let Some(load_err) = err.downcast_ref::<LoadError>() {
738 self.thread_state = ThreadState::LoadError(load_err.clone());
739 } else {
740 self.thread_state = ThreadState::LoadError(LoadError::Other(err.to_string().into()))
741 }
742 if self.message_editor.focus_handle(cx).is_focused(window) {
743 self.focus_handle.focus(window)
744 }
745 cx.notify();
746 }
747
748 pub fn workspace(&self) -> &WeakEntity<Workspace> {
749 &self.workspace
750 }
751
752 pub fn thread(&self) -> Option<&Entity<AcpThread>> {
753 match &self.thread_state {
754 ThreadState::Ready { thread, .. } => Some(thread),
755 ThreadState::Unauthenticated { .. }
756 | ThreadState::Loading { .. }
757 | ThreadState::LoadError { .. } => None,
758 }
759 }
760
761 pub fn title(&self, cx: &App) -> SharedString {
762 match &self.thread_state {
763 ThreadState::Ready { .. } | ThreadState::Unauthenticated { .. } => "New Thread".into(),
764 ThreadState::Loading(loading_view) => loading_view.read(cx).title.clone(),
765 ThreadState::LoadError(error) => match error {
766 LoadError::Unsupported { .. } => format!("Upgrade {}", self.agent.name()).into(),
767 LoadError::FailedToInstall(_) => {
768 format!("Failed to Install {}", self.agent.name()).into()
769 }
770 LoadError::Exited { .. } => format!("{} Exited", self.agent.name()).into(),
771 LoadError::Other(_) => format!("Error Loading {}", self.agent.name()).into(),
772 },
773 }
774 }
775
776 pub fn title_editor(&self) -> Option<Entity<Editor>> {
777 if let ThreadState::Ready { title_editor, .. } = &self.thread_state {
778 title_editor.clone()
779 } else {
780 None
781 }
782 }
783
784 pub fn cancel_generation(&mut self, cx: &mut Context<Self>) {
785 self.thread_error.take();
786 self.thread_retry_status.take();
787
788 if let Some(thread) = self.thread() {
789 self._cancel_task = Some(thread.update(cx, |thread, cx| thread.cancel(cx)));
790 }
791 }
792
793 pub fn expand_message_editor(
794 &mut self,
795 _: &ExpandMessageEditor,
796 _window: &mut Window,
797 cx: &mut Context<Self>,
798 ) {
799 self.set_editor_is_expanded(!self.editor_expanded, cx);
800 cx.notify();
801 }
802
803 fn set_editor_is_expanded(&mut self, is_expanded: bool, cx: &mut Context<Self>) {
804 self.editor_expanded = is_expanded;
805 self.message_editor.update(cx, |editor, cx| {
806 if is_expanded {
807 editor.set_mode(
808 EditorMode::Full {
809 scale_ui_elements_with_buffer_font_size: false,
810 show_active_line_background: false,
811 sized_by_content: false,
812 },
813 cx,
814 )
815 } else {
816 editor.set_mode(
817 EditorMode::AutoHeight {
818 min_lines: MIN_EDITOR_LINES,
819 max_lines: Some(MAX_EDITOR_LINES),
820 },
821 cx,
822 )
823 }
824 });
825 cx.notify();
826 }
827
828 pub fn handle_title_editor_event(
829 &mut self,
830 title_editor: &Entity<Editor>,
831 event: &EditorEvent,
832 window: &mut Window,
833 cx: &mut Context<Self>,
834 ) {
835 let Some(thread) = self.thread() else { return };
836
837 match event {
838 EditorEvent::BufferEdited => {
839 let new_title = title_editor.read(cx).text(cx);
840 thread.update(cx, |thread, cx| {
841 thread
842 .set_title(new_title.into(), cx)
843 .detach_and_log_err(cx);
844 })
845 }
846 EditorEvent::Blurred => {
847 if title_editor.read(cx).text(cx).is_empty() {
848 title_editor.update(cx, |editor, cx| {
849 editor.set_text("New Thread", window, cx);
850 });
851 }
852 }
853 _ => {}
854 }
855 }
856
857 pub fn handle_message_editor_event(
858 &mut self,
859 _: &Entity<MessageEditor>,
860 event: &MessageEditorEvent,
861 window: &mut Window,
862 cx: &mut Context<Self>,
863 ) {
864 match event {
865 MessageEditorEvent::Send => self.send(window, cx),
866 MessageEditorEvent::Cancel => self.cancel_generation(cx),
867 MessageEditorEvent::Focus => {
868 self.cancel_editing(&Default::default(), window, cx);
869 }
870 MessageEditorEvent::LostFocus => {}
871 }
872 }
873
874 pub fn handle_entry_view_event(
875 &mut self,
876 _: &Entity<EntryViewState>,
877 event: &EntryViewEvent,
878 window: &mut Window,
879 cx: &mut Context<Self>,
880 ) {
881 match &event.view_event {
882 ViewEvent::NewDiff(tool_call_id) => {
883 if AgentSettings::get_global(cx).expand_edit_card {
884 self.expanded_tool_calls.insert(tool_call_id.clone());
885 }
886 }
887 ViewEvent::NewTerminal(tool_call_id) => {
888 if AgentSettings::get_global(cx).expand_terminal_card {
889 self.expanded_tool_calls.insert(tool_call_id.clone());
890 }
891 }
892 ViewEvent::TerminalMovedToBackground(tool_call_id) => {
893 self.expanded_tool_calls.remove(tool_call_id);
894 }
895 ViewEvent::MessageEditorEvent(_editor, MessageEditorEvent::Focus) => {
896 if let Some(thread) = self.thread()
897 && let Some(AgentThreadEntry::UserMessage(user_message)) =
898 thread.read(cx).entries().get(event.entry_index)
899 && user_message.id.is_some()
900 {
901 self.editing_message = Some(event.entry_index);
902 cx.notify();
903 }
904 }
905 ViewEvent::MessageEditorEvent(editor, MessageEditorEvent::LostFocus) => {
906 if let Some(thread) = self.thread()
907 && let Some(AgentThreadEntry::UserMessage(user_message)) =
908 thread.read(cx).entries().get(event.entry_index)
909 && user_message.id.is_some()
910 {
911 if editor.read(cx).text(cx).as_str() == user_message.content.to_markdown(cx) {
912 self.editing_message = None;
913 cx.notify();
914 }
915 }
916 }
917 ViewEvent::MessageEditorEvent(editor, MessageEditorEvent::Send) => {
918 self.regenerate(event.entry_index, editor, window, cx);
919 }
920 ViewEvent::MessageEditorEvent(_editor, MessageEditorEvent::Cancel) => {
921 self.cancel_editing(&Default::default(), window, cx);
922 }
923 }
924 }
925
926 fn resume_chat(&mut self, cx: &mut Context<Self>) {
927 self.thread_error.take();
928 let Some(thread) = self.thread() else {
929 return;
930 };
931 if !thread.read(cx).can_resume(cx) {
932 return;
933 }
934
935 let task = thread.update(cx, |thread, cx| thread.resume(cx));
936 cx.spawn(async move |this, cx| {
937 let result = task.await;
938
939 this.update(cx, |this, cx| {
940 if let Err(err) = result {
941 this.handle_thread_error(err, cx);
942 }
943 })
944 })
945 .detach();
946 }
947
948 fn send(&mut self, window: &mut Window, cx: &mut Context<Self>) {
949 let Some(thread) = self.thread() else { return };
950
951 if self.is_loading_contents {
952 return;
953 }
954
955 self.history_store.update(cx, |history, cx| {
956 history.push_recently_opened_entry(
957 HistoryEntryId::AcpThread(thread.read(cx).session_id().clone()),
958 cx,
959 );
960 });
961
962 if thread.read(cx).status() != ThreadStatus::Idle {
963 self.stop_current_and_send_new_message(window, cx);
964 return;
965 }
966
967 let text = self.message_editor.read(cx).text(cx);
968 let text = text.trim();
969 if text == "/login" || text == "/logout" {
970 let ThreadState::Ready { thread, .. } = &self.thread_state else {
971 return;
972 };
973
974 let connection = thread.read(cx).connection().clone();
975 if !connection
976 .auth_methods()
977 .iter()
978 .any(|method| method.id.0.as_ref() == "claude-login")
979 {
980 return;
981 };
982 let this = cx.weak_entity();
983 let agent = self.agent.clone();
984 window.defer(cx, |window, cx| {
985 Self::handle_auth_required(
986 this,
987 AuthRequired {
988 description: None,
989 provider_id: None,
990 },
991 agent,
992 connection,
993 window,
994 cx,
995 );
996 });
997 cx.notify();
998 return;
999 }
1000
1001 let contents = self
1002 .message_editor
1003 .update(cx, |message_editor, cx| message_editor.contents(cx));
1004 self.send_impl(contents, window, cx)
1005 }
1006
1007 fn stop_current_and_send_new_message(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1008 let Some(thread) = self.thread().cloned() else {
1009 return;
1010 };
1011
1012 let cancelled = thread.update(cx, |thread, cx| thread.cancel(cx));
1013
1014 let contents = self
1015 .message_editor
1016 .update(cx, |message_editor, cx| message_editor.contents(cx));
1017
1018 cx.spawn_in(window, async move |this, cx| {
1019 cancelled.await;
1020
1021 this.update_in(cx, |this, window, cx| {
1022 this.send_impl(contents, window, cx);
1023 })
1024 .ok();
1025 })
1026 .detach();
1027 }
1028
1029 fn send_impl(
1030 &mut self,
1031 contents: Task<Result<(Vec<acp::ContentBlock>, Vec<Entity<Buffer>>)>>,
1032 window: &mut Window,
1033 cx: &mut Context<Self>,
1034 ) {
1035 let agent_telemetry_id = self.agent.telemetry_id();
1036
1037 self.thread_error.take();
1038 self.editing_message.take();
1039 self.thread_feedback.clear();
1040
1041 let Some(thread) = self.thread() else {
1042 return;
1043 };
1044 let thread = thread.downgrade();
1045 if self.should_be_following {
1046 self.workspace
1047 .update(cx, |workspace, cx| {
1048 workspace.follow(CollaboratorId::Agent, window, cx);
1049 })
1050 .ok();
1051 }
1052
1053 self.is_loading_contents = true;
1054 let guard = cx.new(|_| ());
1055 cx.observe_release(&guard, |this, _guard, cx| {
1056 this.is_loading_contents = false;
1057 cx.notify();
1058 })
1059 .detach();
1060
1061 let task = cx.spawn_in(window, async move |this, cx| {
1062 let (contents, tracked_buffers) = contents.await?;
1063
1064 if contents.is_empty() {
1065 return Ok(());
1066 }
1067
1068 this.update_in(cx, |this, window, cx| {
1069 this.set_editor_is_expanded(false, cx);
1070 this.scroll_to_bottom(cx);
1071 this.message_editor.update(cx, |message_editor, cx| {
1072 message_editor.clear(window, cx);
1073 });
1074 })?;
1075 let send = thread.update(cx, |thread, cx| {
1076 thread.action_log().update(cx, |action_log, cx| {
1077 for buffer in tracked_buffers {
1078 action_log.buffer_read(buffer, cx)
1079 }
1080 });
1081 drop(guard);
1082
1083 telemetry::event!("Agent Message Sent", agent = agent_telemetry_id);
1084
1085 thread.send(contents, cx)
1086 })?;
1087 send.await
1088 });
1089
1090 cx.spawn(async move |this, cx| {
1091 if let Err(err) = task.await {
1092 this.update(cx, |this, cx| {
1093 this.handle_thread_error(err, cx);
1094 })
1095 .ok();
1096 } else {
1097 this.update(cx, |this, cx| {
1098 this.should_be_following = this
1099 .workspace
1100 .update(cx, |workspace, _| {
1101 workspace.is_being_followed(CollaboratorId::Agent)
1102 })
1103 .unwrap_or_default();
1104 })
1105 .ok();
1106 }
1107 })
1108 .detach();
1109 }
1110
1111 fn cancel_editing(&mut self, _: &ClickEvent, window: &mut Window, cx: &mut Context<Self>) {
1112 let Some(thread) = self.thread().cloned() else {
1113 return;
1114 };
1115
1116 if let Some(index) = self.editing_message.take()
1117 && let Some(editor) = self
1118 .entry_view_state
1119 .read(cx)
1120 .entry(index)
1121 .and_then(|e| e.message_editor())
1122 .cloned()
1123 {
1124 editor.update(cx, |editor, cx| {
1125 if let Some(user_message) = thread
1126 .read(cx)
1127 .entries()
1128 .get(index)
1129 .and_then(|e| e.user_message())
1130 {
1131 editor.set_message(user_message.chunks.clone(), window, cx);
1132 }
1133 })
1134 };
1135 self.focus_handle(cx).focus(window);
1136 cx.notify();
1137 }
1138
1139 fn regenerate(
1140 &mut self,
1141 entry_ix: usize,
1142 message_editor: &Entity<MessageEditor>,
1143 window: &mut Window,
1144 cx: &mut Context<Self>,
1145 ) {
1146 let Some(thread) = self.thread().cloned() else {
1147 return;
1148 };
1149 if self.is_loading_contents {
1150 return;
1151 }
1152
1153 let Some(user_message_id) = thread.update(cx, |thread, _| {
1154 thread.entries().get(entry_ix)?.user_message()?.id.clone()
1155 }) else {
1156 return;
1157 };
1158
1159 let contents = message_editor.update(cx, |message_editor, cx| message_editor.contents(cx));
1160
1161 let task = cx.spawn(async move |_, cx| {
1162 let contents = contents.await?;
1163 thread
1164 .update(cx, |thread, cx| thread.rewind(user_message_id, cx))?
1165 .await?;
1166 Ok(contents)
1167 });
1168 self.send_impl(task, window, cx);
1169 }
1170
1171 fn open_agent_diff(&mut self, _: &OpenAgentDiff, window: &mut Window, cx: &mut Context<Self>) {
1172 if let Some(thread) = self.thread() {
1173 AgentDiffPane::deploy(thread.clone(), self.workspace.clone(), window, cx).log_err();
1174 }
1175 }
1176
1177 fn open_edited_buffer(
1178 &mut self,
1179 buffer: &Entity<Buffer>,
1180 window: &mut Window,
1181 cx: &mut Context<Self>,
1182 ) {
1183 let Some(thread) = self.thread() else {
1184 return;
1185 };
1186
1187 let Some(diff) =
1188 AgentDiffPane::deploy(thread.clone(), self.workspace.clone(), window, cx).log_err()
1189 else {
1190 return;
1191 };
1192
1193 diff.update(cx, |diff, cx| {
1194 diff.move_to_path(PathKey::for_buffer(buffer, cx), window, cx)
1195 })
1196 }
1197
1198 fn handle_open_rules(&mut self, _: &ClickEvent, window: &mut Window, cx: &mut Context<Self>) {
1199 let Some(thread) = self.as_native_thread(cx) else {
1200 return;
1201 };
1202 let project_context = thread.read(cx).project_context().read(cx);
1203
1204 let project_entry_ids = project_context
1205 .worktrees
1206 .iter()
1207 .flat_map(|worktree| worktree.rules_file.as_ref())
1208 .map(|rules_file| ProjectEntryId::from_usize(rules_file.project_entry_id))
1209 .collect::<Vec<_>>();
1210
1211 self.workspace
1212 .update(cx, move |workspace, cx| {
1213 // TODO: Open a multibuffer instead? In some cases this doesn't make the set of rules
1214 // files clear. For example, if rules file 1 is already open but rules file 2 is not,
1215 // this would open and focus rules file 2 in a tab that is not next to rules file 1.
1216 let project = workspace.project().read(cx);
1217 let project_paths = project_entry_ids
1218 .into_iter()
1219 .flat_map(|entry_id| project.path_for_entry(entry_id, cx))
1220 .collect::<Vec<_>>();
1221 for project_path in project_paths {
1222 workspace
1223 .open_path(project_path, None, true, window, cx)
1224 .detach_and_log_err(cx);
1225 }
1226 })
1227 .ok();
1228 }
1229
1230 fn handle_thread_error(&mut self, error: anyhow::Error, cx: &mut Context<Self>) {
1231 self.thread_error = Some(ThreadError::from_err(error, &self.agent));
1232 cx.notify();
1233 }
1234
1235 fn clear_thread_error(&mut self, cx: &mut Context<Self>) {
1236 self.thread_error = None;
1237 cx.notify();
1238 }
1239
1240 fn handle_thread_event(
1241 &mut self,
1242 thread: &Entity<AcpThread>,
1243 event: &AcpThreadEvent,
1244 window: &mut Window,
1245 cx: &mut Context<Self>,
1246 ) {
1247 match event {
1248 AcpThreadEvent::NewEntry => {
1249 let len = thread.read(cx).entries().len();
1250 let index = len - 1;
1251 self.entry_view_state.update(cx, |view_state, cx| {
1252 view_state.sync_entry(index, thread, window, cx);
1253 self.list_state.splice_focusable(
1254 index..index,
1255 [view_state
1256 .entry(index)
1257 .and_then(|entry| entry.focus_handle(cx))],
1258 );
1259 });
1260 }
1261 AcpThreadEvent::EntryUpdated(index) => {
1262 self.entry_view_state.update(cx, |view_state, cx| {
1263 view_state.sync_entry(*index, thread, window, cx)
1264 });
1265 }
1266 AcpThreadEvent::EntriesRemoved(range) => {
1267 self.entry_view_state
1268 .update(cx, |view_state, _cx| view_state.remove(range.clone()));
1269 self.list_state.splice(range.clone(), 0);
1270 }
1271 AcpThreadEvent::ToolAuthorizationRequired => {
1272 self.notify_with_sound("Waiting for tool confirmation", IconName::Info, window, cx);
1273 }
1274 AcpThreadEvent::Retry(retry) => {
1275 self.thread_retry_status = Some(retry.clone());
1276 }
1277 AcpThreadEvent::Stopped => {
1278 self.thread_retry_status.take();
1279 let used_tools = thread.read(cx).used_tools_since_last_user_message();
1280 self.notify_with_sound(
1281 if used_tools {
1282 "Finished running tools"
1283 } else {
1284 "New message"
1285 },
1286 IconName::ZedAssistant,
1287 window,
1288 cx,
1289 );
1290 }
1291 AcpThreadEvent::Refusal => {
1292 self.thread_retry_status.take();
1293 self.thread_error = Some(ThreadError::Refusal);
1294 let model_or_agent_name = self.get_current_model_name(cx);
1295 let notification_message =
1296 format!("{} refused to respond to this request", model_or_agent_name);
1297 self.notify_with_sound(¬ification_message, IconName::Warning, window, cx);
1298 }
1299 AcpThreadEvent::Error => {
1300 self.thread_retry_status.take();
1301 self.notify_with_sound(
1302 "Agent stopped due to an error",
1303 IconName::Warning,
1304 window,
1305 cx,
1306 );
1307 }
1308 AcpThreadEvent::LoadError(error) => {
1309 self.thread_retry_status.take();
1310 self.thread_state = ThreadState::LoadError(error.clone());
1311 if self.message_editor.focus_handle(cx).is_focused(window) {
1312 self.focus_handle.focus(window)
1313 }
1314 }
1315 AcpThreadEvent::TitleUpdated => {
1316 let title = thread.read(cx).title();
1317 if let Some(title_editor) = self.title_editor() {
1318 title_editor.update(cx, |editor, cx| {
1319 if editor.text(cx) != title {
1320 editor.set_text(title, window, cx);
1321 }
1322 });
1323 }
1324 }
1325 AcpThreadEvent::PromptCapabilitiesUpdated => {
1326 self.prompt_capabilities
1327 .set(thread.read(cx).prompt_capabilities());
1328 }
1329 AcpThreadEvent::TokenUsageUpdated => {}
1330 AcpThreadEvent::AvailableCommandsUpdated(available_commands) => {
1331 let mut available_commands = available_commands.clone();
1332
1333 if thread
1334 .read(cx)
1335 .connection()
1336 .auth_methods()
1337 .iter()
1338 .any(|method| method.id.0.as_ref() == "claude-login")
1339 {
1340 available_commands.push(acp::AvailableCommand {
1341 name: "login".to_owned(),
1342 description: "Authenticate".to_owned(),
1343 input: None,
1344 });
1345 available_commands.push(acp::AvailableCommand {
1346 name: "logout".to_owned(),
1347 description: "Authenticate".to_owned(),
1348 input: None,
1349 });
1350 }
1351
1352 self.available_commands.replace(available_commands);
1353 }
1354 }
1355 cx.notify();
1356 }
1357
1358 fn authenticate(
1359 &mut self,
1360 method: acp::AuthMethodId,
1361 window: &mut Window,
1362 cx: &mut Context<Self>,
1363 ) {
1364 let ThreadState::Unauthenticated {
1365 connection,
1366 pending_auth_method,
1367 configuration_view,
1368 ..
1369 } = &mut self.thread_state
1370 else {
1371 return;
1372 };
1373
1374 if method.0.as_ref() == "gemini-api-key" {
1375 let registry = LanguageModelRegistry::global(cx);
1376 let provider = registry
1377 .read(cx)
1378 .provider(&language_model::GOOGLE_PROVIDER_ID)
1379 .unwrap();
1380 if !provider.is_authenticated(cx) {
1381 let this = cx.weak_entity();
1382 let agent = self.agent.clone();
1383 let connection = connection.clone();
1384 window.defer(cx, |window, cx| {
1385 Self::handle_auth_required(
1386 this,
1387 AuthRequired {
1388 description: Some("GEMINI_API_KEY must be set".to_owned()),
1389 provider_id: Some(language_model::GOOGLE_PROVIDER_ID),
1390 },
1391 agent,
1392 connection,
1393 window,
1394 cx,
1395 );
1396 });
1397 return;
1398 }
1399 } else if method.0.as_ref() == "anthropic-api-key" {
1400 let registry = LanguageModelRegistry::global(cx);
1401 let provider = registry
1402 .read(cx)
1403 .provider(&language_model::ANTHROPIC_PROVIDER_ID)
1404 .unwrap();
1405 let this = cx.weak_entity();
1406 let agent = self.agent.clone();
1407 let connection = connection.clone();
1408 window.defer(cx, move |window, cx| {
1409 if !provider.is_authenticated(cx) {
1410 Self::handle_auth_required(
1411 this,
1412 AuthRequired {
1413 description: Some("ANTHROPIC_API_KEY must be set".to_owned()),
1414 provider_id: Some(language_model::ANTHROPIC_PROVIDER_ID),
1415 },
1416 agent,
1417 connection,
1418 window,
1419 cx,
1420 );
1421 } else {
1422 this.update(cx, |this, cx| {
1423 this.thread_state = Self::initial_state(
1424 agent,
1425 None,
1426 this.workspace.clone(),
1427 this.project.clone(),
1428 window,
1429 cx,
1430 )
1431 })
1432 .ok();
1433 }
1434 });
1435 return;
1436 } else if method.0.as_ref() == "vertex-ai"
1437 && std::env::var("GOOGLE_API_KEY").is_err()
1438 && (std::env::var("GOOGLE_CLOUD_PROJECT").is_err()
1439 || (std::env::var("GOOGLE_CLOUD_PROJECT").is_err()))
1440 {
1441 let this = cx.weak_entity();
1442 let agent = self.agent.clone();
1443 let connection = connection.clone();
1444
1445 window.defer(cx, |window, cx| {
1446 Self::handle_auth_required(
1447 this,
1448 AuthRequired {
1449 description: Some(
1450 "GOOGLE_API_KEY must be set in the environment to use Vertex AI authentication for Gemini CLI. Please export it and restart Zed."
1451 .to_owned(),
1452 ),
1453 provider_id: None,
1454 },
1455 agent,
1456 connection,
1457 window,
1458 cx,
1459 )
1460 });
1461 return;
1462 }
1463
1464 self.thread_error.take();
1465 configuration_view.take();
1466 pending_auth_method.replace(method.clone());
1467 let authenticate = if method.0.as_ref() == "claude-login" {
1468 if let Some(workspace) = self.workspace.upgrade() {
1469 Self::spawn_claude_login(&workspace, window, cx)
1470 } else {
1471 Task::ready(Ok(()))
1472 }
1473 } else {
1474 connection.authenticate(method, cx)
1475 };
1476 cx.notify();
1477 self.auth_task =
1478 Some(cx.spawn_in(window, {
1479 let agent = self.agent.clone();
1480 async move |this, cx| {
1481 let result = authenticate.await;
1482
1483 match &result {
1484 Ok(_) => telemetry::event!(
1485 "Authenticate Agent Succeeded",
1486 agent = agent.telemetry_id()
1487 ),
1488 Err(_) => {
1489 telemetry::event!(
1490 "Authenticate Agent Failed",
1491 agent = agent.telemetry_id(),
1492 )
1493 }
1494 }
1495
1496 this.update_in(cx, |this, window, cx| {
1497 if let Err(err) = result {
1498 if let ThreadState::Unauthenticated {
1499 pending_auth_method,
1500 ..
1501 } = &mut this.thread_state
1502 {
1503 pending_auth_method.take();
1504 }
1505 this.handle_thread_error(err, cx);
1506 } else {
1507 this.reset(window, cx);
1508 }
1509 this.auth_task.take()
1510 })
1511 .ok();
1512 }
1513 }));
1514 }
1515
1516 fn spawn_claude_login(
1517 workspace: &Entity<Workspace>,
1518 window: &mut Window,
1519 cx: &mut App,
1520 ) -> Task<Result<()>> {
1521 let Some(terminal_panel) = workspace.read(cx).panel::<TerminalPanel>(cx) else {
1522 return Task::ready(Ok(()));
1523 };
1524 let project_entity = workspace.read(cx).project();
1525 let project = project_entity.read(cx);
1526 let cwd = project.first_project_directory(cx);
1527 let shell = project.terminal_settings(&cwd, cx).shell.clone();
1528
1529 let delegate = AgentServerDelegate::new(project_entity.clone(), None, None);
1530 let command = ClaudeCode::login_command(delegate, cx);
1531
1532 window.spawn(cx, async move |cx| {
1533 let login_command = command.await?;
1534 let command = login_command
1535 .path
1536 .to_str()
1537 .with_context(|| format!("invalid login command: {:?}", login_command.path))?;
1538 let command = shlex::try_quote(command)?;
1539 let args = login_command
1540 .arguments
1541 .iter()
1542 .map(|arg| {
1543 Ok(shlex::try_quote(arg)
1544 .context("Failed to quote argument")?
1545 .to_string())
1546 })
1547 .collect::<Result<Vec<_>>>()?;
1548
1549 let terminal = terminal_panel.update_in(cx, |terminal_panel, window, cx| {
1550 terminal_panel.spawn_task(
1551 &SpawnInTerminal {
1552 id: task::TaskId("claude-login".into()),
1553 full_label: "claude /login".to_owned(),
1554 label: "claude /login".to_owned(),
1555 command: Some(command.into()),
1556 args,
1557 command_label: "claude /login".to_owned(),
1558 cwd,
1559 use_new_terminal: true,
1560 allow_concurrent_runs: true,
1561 hide: task::HideStrategy::Always,
1562 shell,
1563 ..Default::default()
1564 },
1565 window,
1566 cx,
1567 )
1568 })?;
1569
1570 let terminal = terminal.await?;
1571 let mut exit_status = terminal
1572 .read_with(cx, |terminal, cx| terminal.wait_for_completed_task(cx))?
1573 .fuse();
1574
1575 let logged_in = cx
1576 .spawn({
1577 let terminal = terminal.clone();
1578 async move |cx| {
1579 loop {
1580 cx.background_executor().timer(Duration::from_secs(1)).await;
1581 let content =
1582 terminal.update(cx, |terminal, _cx| terminal.get_content())?;
1583 if content.contains("Login successful") {
1584 return anyhow::Ok(());
1585 }
1586 }
1587 }
1588 })
1589 .fuse();
1590 futures::pin_mut!(logged_in);
1591 futures::select_biased! {
1592 result = logged_in => {
1593 if let Err(e) = result {
1594 log::error!("{e}");
1595 return Err(anyhow!("exited before logging in"));
1596 }
1597 }
1598 _ = exit_status => {
1599 return Err(anyhow!("exited before logging in"));
1600 }
1601 }
1602 terminal.update(cx, |terminal, _| terminal.kill_active_task())?;
1603 Ok(())
1604 })
1605 }
1606
1607 fn authorize_tool_call(
1608 &mut self,
1609 tool_call_id: acp::ToolCallId,
1610 option_id: acp::PermissionOptionId,
1611 option_kind: acp::PermissionOptionKind,
1612 window: &mut Window,
1613 cx: &mut Context<Self>,
1614 ) {
1615 let Some(thread) = self.thread() else {
1616 return;
1617 };
1618 thread.update(cx, |thread, cx| {
1619 thread.authorize_tool_call(tool_call_id, option_id, option_kind, cx);
1620 });
1621 if self.should_be_following {
1622 self.workspace
1623 .update(cx, |workspace, cx| {
1624 workspace.follow(CollaboratorId::Agent, window, cx);
1625 })
1626 .ok();
1627 }
1628 cx.notify();
1629 }
1630
1631 fn rewind(&mut self, message_id: &UserMessageId, cx: &mut Context<Self>) {
1632 let Some(thread) = self.thread() else {
1633 return;
1634 };
1635 thread
1636 .update(cx, |thread, cx| thread.rewind(message_id.clone(), cx))
1637 .detach_and_log_err(cx);
1638 cx.notify();
1639 }
1640
1641 fn render_entry(
1642 &self,
1643 entry_ix: usize,
1644 total_entries: usize,
1645 entry: &AgentThreadEntry,
1646 window: &mut Window,
1647 cx: &Context<Self>,
1648 ) -> AnyElement {
1649 let primary = match &entry {
1650 AgentThreadEntry::UserMessage(message) => {
1651 let Some(editor) = self
1652 .entry_view_state
1653 .read(cx)
1654 .entry(entry_ix)
1655 .and_then(|entry| entry.message_editor())
1656 .cloned()
1657 else {
1658 return Empty.into_any_element();
1659 };
1660
1661 let editing = self.editing_message == Some(entry_ix);
1662 let editor_focus = editor.focus_handle(cx).is_focused(window);
1663 let focus_border = cx.theme().colors().border_focused;
1664
1665 let rules_item = if entry_ix == 0 {
1666 self.render_rules_item(cx)
1667 } else {
1668 None
1669 };
1670
1671 let has_checkpoint_button = message
1672 .checkpoint
1673 .as_ref()
1674 .is_some_and(|checkpoint| checkpoint.show);
1675
1676 let agent_name = self.agent.name();
1677
1678 v_flex()
1679 .id(("user_message", entry_ix))
1680 .map(|this| {
1681 if entry_ix == 0 && !has_checkpoint_button && rules_item.is_none() {
1682 this.pt(rems_from_px(18.))
1683 } else if rules_item.is_some() {
1684 this.pt_3()
1685 } else {
1686 this.pt_2()
1687 }
1688 })
1689 .pb_3()
1690 .px_2()
1691 .gap_1p5()
1692 .w_full()
1693 .children(rules_item)
1694 .children(message.id.clone().and_then(|message_id| {
1695 message.checkpoint.as_ref()?.show.then(|| {
1696 h_flex()
1697 .px_3()
1698 .gap_2()
1699 .child(Divider::horizontal())
1700 .child(
1701 Button::new("restore-checkpoint", "Restore Checkpoint")
1702 .icon(IconName::Undo)
1703 .icon_size(IconSize::XSmall)
1704 .icon_position(IconPosition::Start)
1705 .label_size(LabelSize::XSmall)
1706 .icon_color(Color::Muted)
1707 .color(Color::Muted)
1708 .on_click(cx.listener(move |this, _, _window, cx| {
1709 this.rewind(&message_id, cx);
1710 }))
1711 )
1712 .child(Divider::horizontal())
1713 })
1714 }))
1715 .child(
1716 div()
1717 .relative()
1718 .child(
1719 div()
1720 .py_3()
1721 .px_2()
1722 .rounded_md()
1723 .shadow_md()
1724 .bg(cx.theme().colors().editor_background)
1725 .border_1()
1726 .when(editing && !editor_focus, |this| this.border_dashed())
1727 .border_color(cx.theme().colors().border)
1728 .map(|this|{
1729 if editing && editor_focus {
1730 this.border_color(focus_border)
1731 } else if message.id.is_some() {
1732 this.hover(|s| s.border_color(focus_border.opacity(0.8)))
1733 } else {
1734 this
1735 }
1736 })
1737 .text_xs()
1738 .child(editor.clone().into_any_element()),
1739 )
1740 .when(editor_focus, |this| {
1741 let base_container = h_flex()
1742 .absolute()
1743 .top_neg_3p5()
1744 .right_3()
1745 .gap_1()
1746 .rounded_sm()
1747 .border_1()
1748 .border_color(cx.theme().colors().border)
1749 .bg(cx.theme().colors().editor_background)
1750 .overflow_hidden();
1751
1752 if message.id.is_some() {
1753 this.child(
1754 base_container
1755 .child(
1756 IconButton::new("cancel", IconName::Close)
1757 .disabled(self.is_loading_contents)
1758 .icon_color(Color::Error)
1759 .icon_size(IconSize::XSmall)
1760 .on_click(cx.listener(Self::cancel_editing))
1761 )
1762 .child(
1763 if self.is_loading_contents {
1764 div()
1765 .id("loading-edited-message-content")
1766 .tooltip(Tooltip::text("Loading Added Context…"))
1767 .child(loading_contents_spinner(IconSize::XSmall))
1768 .into_any_element()
1769 } else {
1770 IconButton::new("regenerate", IconName::Return)
1771 .icon_color(Color::Muted)
1772 .icon_size(IconSize::XSmall)
1773 .tooltip(Tooltip::text(
1774 "Editing will restart the thread from this point."
1775 ))
1776 .on_click(cx.listener({
1777 let editor = editor.clone();
1778 move |this, _, window, cx| {
1779 this.regenerate(
1780 entry_ix, &editor, window, cx,
1781 );
1782 }
1783 })).into_any_element()
1784 }
1785 )
1786 )
1787 } else {
1788 this.child(
1789 base_container
1790 .border_dashed()
1791 .child(
1792 IconButton::new("editing_unavailable", IconName::PencilUnavailable)
1793 .icon_size(IconSize::Small)
1794 .icon_color(Color::Muted)
1795 .style(ButtonStyle::Transparent)
1796 .tooltip(move |_window, cx| {
1797 cx.new(|_| UnavailableEditingTooltip::new(agent_name.clone()))
1798 .into()
1799 })
1800 )
1801 )
1802 }
1803 }),
1804 )
1805 .into_any()
1806 }
1807 AgentThreadEntry::AssistantMessage(AssistantMessage { chunks }) => {
1808 let is_last = entry_ix + 1 == total_entries;
1809
1810 let style = default_markdown_style(false, false, window, cx);
1811 let message_body = v_flex()
1812 .w_full()
1813 .gap_3()
1814 .children(chunks.iter().enumerate().filter_map(
1815 |(chunk_ix, chunk)| match chunk {
1816 AssistantMessageChunk::Message { block } => {
1817 block.markdown().map(|md| {
1818 self.render_markdown(md.clone(), style.clone())
1819 .into_any_element()
1820 })
1821 }
1822 AssistantMessageChunk::Thought { block } => {
1823 block.markdown().map(|md| {
1824 self.render_thinking_block(
1825 entry_ix,
1826 chunk_ix,
1827 md.clone(),
1828 window,
1829 cx,
1830 )
1831 .into_any_element()
1832 })
1833 }
1834 },
1835 ))
1836 .into_any();
1837
1838 v_flex()
1839 .px_5()
1840 .py_1p5()
1841 .when(is_last, |this| this.pb_4())
1842 .w_full()
1843 .text_ui(cx)
1844 .child(message_body)
1845 .into_any()
1846 }
1847 AgentThreadEntry::ToolCall(tool_call) => {
1848 let has_terminals = tool_call.terminals().next().is_some();
1849
1850 div().w_full().map(|this| {
1851 if has_terminals {
1852 this.children(tool_call.terminals().map(|terminal| {
1853 self.render_terminal_tool_call(
1854 entry_ix, terminal, tool_call, window, cx,
1855 )
1856 }))
1857 } else {
1858 this.child(self.render_tool_call(entry_ix, tool_call, window, cx))
1859 }
1860 })
1861 }
1862 .into_any(),
1863 };
1864
1865 let Some(thread) = self.thread() else {
1866 return primary;
1867 };
1868
1869 let primary = if entry_ix == total_entries - 1 {
1870 v_flex()
1871 .w_full()
1872 .child(primary)
1873 .child(self.render_thread_controls(&thread, cx))
1874 .when_some(
1875 self.thread_feedback.comments_editor.clone(),
1876 |this, editor| this.child(Self::render_feedback_feedback_editor(editor, cx)),
1877 )
1878 .into_any_element()
1879 } else {
1880 primary
1881 };
1882
1883 if let Some(editing_index) = self.editing_message.as_ref()
1884 && *editing_index < entry_ix
1885 {
1886 let backdrop = div()
1887 .id(("backdrop", entry_ix))
1888 .size_full()
1889 .absolute()
1890 .inset_0()
1891 .bg(cx.theme().colors().panel_background)
1892 .opacity(0.8)
1893 .block_mouse_except_scroll()
1894 .on_click(cx.listener(Self::cancel_editing));
1895
1896 div()
1897 .relative()
1898 .child(primary)
1899 .child(backdrop)
1900 .into_any_element()
1901 } else {
1902 primary
1903 }
1904 }
1905
1906 fn tool_card_header_bg(&self, cx: &Context<Self>) -> Hsla {
1907 cx.theme()
1908 .colors()
1909 .element_background
1910 .blend(cx.theme().colors().editor_foreground.opacity(0.025))
1911 }
1912
1913 fn tool_card_border_color(&self, cx: &Context<Self>) -> Hsla {
1914 cx.theme().colors().border.opacity(0.8)
1915 }
1916
1917 fn tool_name_font_size(&self) -> Rems {
1918 rems_from_px(13.)
1919 }
1920
1921 fn render_thinking_block(
1922 &self,
1923 entry_ix: usize,
1924 chunk_ix: usize,
1925 chunk: Entity<Markdown>,
1926 window: &Window,
1927 cx: &Context<Self>,
1928 ) -> AnyElement {
1929 let header_id = SharedString::from(format!("thinking-block-header-{}", entry_ix));
1930 let card_header_id = SharedString::from("inner-card-header");
1931
1932 let key = (entry_ix, chunk_ix);
1933
1934 let is_open = self.expanded_thinking_blocks.contains(&key);
1935
1936 let scroll_handle = self
1937 .entry_view_state
1938 .read(cx)
1939 .entry(entry_ix)
1940 .and_then(|entry| entry.scroll_handle_for_assistant_message_chunk(chunk_ix));
1941
1942 let thinking_content = {
1943 div()
1944 .id(("thinking-content", chunk_ix))
1945 .when_some(scroll_handle, |this, scroll_handle| {
1946 this.track_scroll(&scroll_handle)
1947 })
1948 .text_ui_sm(cx)
1949 .overflow_hidden()
1950 .child(
1951 self.render_markdown(chunk, default_markdown_style(false, false, window, cx)),
1952 )
1953 };
1954
1955 v_flex()
1956 .gap_1()
1957 .child(
1958 h_flex()
1959 .id(header_id)
1960 .group(&card_header_id)
1961 .relative()
1962 .w_full()
1963 .pr_1()
1964 .justify_between()
1965 .child(
1966 h_flex()
1967 .h(window.line_height() - px(2.))
1968 .gap_1p5()
1969 .overflow_hidden()
1970 .child(
1971 Icon::new(IconName::ToolThink)
1972 .size(IconSize::Small)
1973 .color(Color::Muted),
1974 )
1975 .child(
1976 div()
1977 .text_size(self.tool_name_font_size())
1978 .text_color(cx.theme().colors().text_muted)
1979 .child("Thinking"),
1980 ),
1981 )
1982 .child(
1983 Disclosure::new(("expand", entry_ix), is_open)
1984 .opened_icon(IconName::ChevronUp)
1985 .closed_icon(IconName::ChevronDown)
1986 .visible_on_hover(&card_header_id)
1987 .on_click(cx.listener({
1988 move |this, _event, _window, cx| {
1989 if is_open {
1990 this.expanded_thinking_blocks.remove(&key);
1991 } else {
1992 this.expanded_thinking_blocks.insert(key);
1993 }
1994 cx.notify();
1995 }
1996 })),
1997 )
1998 .on_click(cx.listener({
1999 move |this, _event, _window, cx| {
2000 if is_open {
2001 this.expanded_thinking_blocks.remove(&key);
2002 } else {
2003 this.expanded_thinking_blocks.insert(key);
2004 }
2005 cx.notify();
2006 }
2007 })),
2008 )
2009 .when(is_open, |this| {
2010 this.child(
2011 div()
2012 .ml_1p5()
2013 .pl_3p5()
2014 .border_l_1()
2015 .border_color(self.tool_card_border_color(cx))
2016 .child(thinking_content),
2017 )
2018 })
2019 .into_any_element()
2020 }
2021
2022 fn render_tool_call(
2023 &self,
2024 entry_ix: usize,
2025 tool_call: &ToolCall,
2026 window: &Window,
2027 cx: &Context<Self>,
2028 ) -> Div {
2029 let card_header_id = SharedString::from("inner-tool-call-header");
2030
2031 let tool_icon =
2032 if tool_call.kind == acp::ToolKind::Edit && tool_call.locations.len() == 1 {
2033 FileIcons::get_icon(&tool_call.locations[0].path, cx)
2034 .map(Icon::from_path)
2035 .unwrap_or(Icon::new(IconName::ToolPencil))
2036 } else {
2037 Icon::new(match tool_call.kind {
2038 acp::ToolKind::Read => IconName::ToolSearch,
2039 acp::ToolKind::Edit => IconName::ToolPencil,
2040 acp::ToolKind::Delete => IconName::ToolDeleteFile,
2041 acp::ToolKind::Move => IconName::ArrowRightLeft,
2042 acp::ToolKind::Search => IconName::ToolSearch,
2043 acp::ToolKind::Execute => IconName::ToolTerminal,
2044 acp::ToolKind::Think => IconName::ToolThink,
2045 acp::ToolKind::Fetch => IconName::ToolWeb,
2046 acp::ToolKind::Other => IconName::ToolHammer,
2047 })
2048 }
2049 .size(IconSize::Small)
2050 .color(Color::Muted);
2051
2052 let failed_or_canceled = match &tool_call.status {
2053 ToolCallStatus::Rejected | ToolCallStatus::Canceled | ToolCallStatus::Failed => true,
2054 _ => false,
2055 };
2056
2057 let has_location = tool_call.locations.len() == 1;
2058 let needs_confirmation = matches!(
2059 tool_call.status,
2060 ToolCallStatus::WaitingForConfirmation { .. }
2061 );
2062 let is_edit =
2063 matches!(tool_call.kind, acp::ToolKind::Edit) || tool_call.diffs().next().is_some();
2064 let use_card_layout = needs_confirmation || is_edit;
2065
2066 let is_collapsible = !tool_call.content.is_empty() && !needs_confirmation;
2067
2068 let is_open = needs_confirmation || self.expanded_tool_calls.contains(&tool_call.id);
2069
2070 let gradient_overlay = {
2071 div()
2072 .absolute()
2073 .top_0()
2074 .right_0()
2075 .w_12()
2076 .h_full()
2077 .map(|this| {
2078 if use_card_layout {
2079 this.bg(linear_gradient(
2080 90.,
2081 linear_color_stop(self.tool_card_header_bg(cx), 1.),
2082 linear_color_stop(self.tool_card_header_bg(cx).opacity(0.2), 0.),
2083 ))
2084 } else {
2085 this.bg(linear_gradient(
2086 90.,
2087 linear_color_stop(cx.theme().colors().panel_background, 1.),
2088 linear_color_stop(
2089 cx.theme().colors().panel_background.opacity(0.2),
2090 0.,
2091 ),
2092 ))
2093 }
2094 })
2095 };
2096
2097 let tool_output_display = if is_open {
2098 match &tool_call.status {
2099 ToolCallStatus::WaitingForConfirmation { options, .. } => v_flex()
2100 .w_full()
2101 .children(tool_call.content.iter().map(|content| {
2102 div()
2103 .child(self.render_tool_call_content(
2104 entry_ix,
2105 content,
2106 tool_call,
2107 use_card_layout,
2108 window,
2109 cx,
2110 ))
2111 .into_any_element()
2112 }))
2113 .child(self.render_permission_buttons(
2114 options,
2115 entry_ix,
2116 tool_call.id.clone(),
2117 cx,
2118 ))
2119 .into_any(),
2120 ToolCallStatus::Pending | ToolCallStatus::InProgress
2121 if is_edit
2122 && tool_call.content.is_empty()
2123 && self.as_native_connection(cx).is_some() =>
2124 {
2125 self.render_diff_loading(cx).into_any()
2126 }
2127 ToolCallStatus::Pending
2128 | ToolCallStatus::InProgress
2129 | ToolCallStatus::Completed
2130 | ToolCallStatus::Failed
2131 | ToolCallStatus::Canceled => v_flex()
2132 .w_full()
2133 .children(tool_call.content.iter().map(|content| {
2134 div().child(self.render_tool_call_content(
2135 entry_ix,
2136 content,
2137 tool_call,
2138 use_card_layout,
2139 window,
2140 cx,
2141 ))
2142 }))
2143 .into_any(),
2144 ToolCallStatus::Rejected => Empty.into_any(),
2145 }
2146 .into()
2147 } else {
2148 None
2149 };
2150
2151 v_flex()
2152 .map(|this| {
2153 if use_card_layout {
2154 this.my_1p5()
2155 .rounded_md()
2156 .border_1()
2157 .border_color(self.tool_card_border_color(cx))
2158 .bg(cx.theme().colors().editor_background)
2159 .overflow_hidden()
2160 } else {
2161 this.my_1()
2162 }
2163 })
2164 .map(|this| {
2165 if has_location && !use_card_layout {
2166 this.ml_4()
2167 } else {
2168 this.ml_5()
2169 }
2170 })
2171 .mr_5()
2172 .child(
2173 h_flex()
2174 .group(&card_header_id)
2175 .relative()
2176 .w_full()
2177 .gap_1()
2178 .justify_between()
2179 .when(use_card_layout, |this| {
2180 this.p_0p5()
2181 .rounded_t(rems_from_px(5.))
2182 .bg(self.tool_card_header_bg(cx))
2183 })
2184 .child(
2185 h_flex()
2186 .relative()
2187 .w_full()
2188 .h(window.line_height() - px(2.))
2189 .text_size(self.tool_name_font_size())
2190 .gap_1p5()
2191 .when(has_location || use_card_layout, |this| this.px_1())
2192 .when(has_location, |this| {
2193 this.cursor(CursorStyle::PointingHand)
2194 .rounded(rems_from_px(3.)) // Concentric border radius
2195 .hover(|s| s.bg(cx.theme().colors().element_hover.opacity(0.5)))
2196 })
2197 .overflow_hidden()
2198 .child(tool_icon)
2199 .child(if has_location {
2200 let name = tool_call.locations[0]
2201 .path
2202 .file_name()
2203 .unwrap_or_default()
2204 .display()
2205 .to_string();
2206
2207 h_flex()
2208 .id(("open-tool-call-location", entry_ix))
2209 .w_full()
2210 .map(|this| {
2211 if use_card_layout {
2212 this.text_color(cx.theme().colors().text)
2213 } else {
2214 this.text_color(cx.theme().colors().text_muted)
2215 }
2216 })
2217 .child(name)
2218 .tooltip(Tooltip::text("Jump to File"))
2219 .on_click(cx.listener(move |this, _, window, cx| {
2220 this.open_tool_call_location(entry_ix, 0, window, cx);
2221 }))
2222 .into_any_element()
2223 } else {
2224 h_flex()
2225 .w_full()
2226 .child(self.render_markdown(
2227 tool_call.label.clone(),
2228 default_markdown_style(false, true, window, cx),
2229 ))
2230 .into_any()
2231 })
2232 .when(!has_location, |this| this.child(gradient_overlay)),
2233 )
2234 .when(is_collapsible || failed_or_canceled, |this| {
2235 this.child(
2236 h_flex()
2237 .px_1()
2238 .gap_px()
2239 .when(is_collapsible, |this| {
2240 this.child(
2241 Disclosure::new(("expand", entry_ix), is_open)
2242 .opened_icon(IconName::ChevronUp)
2243 .closed_icon(IconName::ChevronDown)
2244 .visible_on_hover(&card_header_id)
2245 .on_click(cx.listener({
2246 let id = tool_call.id.clone();
2247 move |this: &mut Self, _, _, cx: &mut Context<Self>| {
2248 if is_open {
2249 this.expanded_tool_calls.remove(&id);
2250 } else {
2251 this.expanded_tool_calls.insert(id.clone());
2252 }
2253 cx.notify();
2254 }
2255 })),
2256 )
2257 })
2258 .when(failed_or_canceled, |this| {
2259 this.child(
2260 Icon::new(IconName::Close)
2261 .color(Color::Error)
2262 .size(IconSize::Small),
2263 )
2264 }),
2265 )
2266 }),
2267 )
2268 .children(tool_output_display)
2269 }
2270
2271 fn render_tool_call_content(
2272 &self,
2273 entry_ix: usize,
2274 content: &ToolCallContent,
2275 tool_call: &ToolCall,
2276 card_layout: bool,
2277 window: &Window,
2278 cx: &Context<Self>,
2279 ) -> AnyElement {
2280 match content {
2281 ToolCallContent::ContentBlock(content) => {
2282 if let Some(resource_link) = content.resource_link() {
2283 self.render_resource_link(resource_link, cx)
2284 } else if let Some(markdown) = content.markdown() {
2285 self.render_markdown_output(
2286 markdown.clone(),
2287 tool_call.id.clone(),
2288 card_layout,
2289 window,
2290 cx,
2291 )
2292 } else {
2293 Empty.into_any_element()
2294 }
2295 }
2296 ToolCallContent::Diff(diff) => self.render_diff_editor(entry_ix, diff, tool_call, cx),
2297 ToolCallContent::Terminal(terminal) => {
2298 self.render_terminal_tool_call(entry_ix, terminal, tool_call, window, cx)
2299 }
2300 }
2301 }
2302
2303 fn render_markdown_output(
2304 &self,
2305 markdown: Entity<Markdown>,
2306 tool_call_id: acp::ToolCallId,
2307 card_layout: bool,
2308 window: &Window,
2309 cx: &Context<Self>,
2310 ) -> AnyElement {
2311 let button_id = SharedString::from(format!("tool_output-{:?}", tool_call_id));
2312
2313 v_flex()
2314 .mt_1p5()
2315 .gap_2()
2316 .when(!card_layout, |this| {
2317 this.ml(rems(0.4))
2318 .px_3p5()
2319 .border_l_1()
2320 .border_color(self.tool_card_border_color(cx))
2321 })
2322 .when(card_layout, |this| {
2323 this.p_2()
2324 .border_t_1()
2325 .border_color(self.tool_card_border_color(cx))
2326 })
2327 .text_sm()
2328 .text_color(cx.theme().colors().text_muted)
2329 .child(self.render_markdown(markdown, default_markdown_style(false, false, window, cx)))
2330 .when(!card_layout, |this| {
2331 this.child(
2332 IconButton::new(button_id, IconName::ChevronUp)
2333 .full_width()
2334 .style(ButtonStyle::Outlined)
2335 .icon_color(Color::Muted)
2336 .on_click(cx.listener({
2337 move |this: &mut Self, _, _, cx: &mut Context<Self>| {
2338 this.expanded_tool_calls.remove(&tool_call_id);
2339 cx.notify();
2340 }
2341 })),
2342 )
2343 })
2344 .into_any_element()
2345 }
2346
2347 fn render_resource_link(
2348 &self,
2349 resource_link: &acp::ResourceLink,
2350 cx: &Context<Self>,
2351 ) -> AnyElement {
2352 let uri: SharedString = resource_link.uri.clone().into();
2353 let is_file = resource_link.uri.strip_prefix("file://");
2354
2355 let label: SharedString = if let Some(abs_path) = is_file {
2356 if let Some(project_path) = self
2357 .project
2358 .read(cx)
2359 .project_path_for_absolute_path(&Path::new(abs_path), cx)
2360 && let Some(worktree) = self
2361 .project
2362 .read(cx)
2363 .worktree_for_id(project_path.worktree_id, cx)
2364 {
2365 worktree
2366 .read(cx)
2367 .full_path(&project_path.path)
2368 .to_string_lossy()
2369 .to_string()
2370 .into()
2371 } else {
2372 abs_path.to_string().into()
2373 }
2374 } else {
2375 uri.clone()
2376 };
2377
2378 let button_id = SharedString::from(format!("item-{}", uri));
2379
2380 div()
2381 .ml(rems(0.4))
2382 .pl_2p5()
2383 .border_l_1()
2384 .border_color(self.tool_card_border_color(cx))
2385 .overflow_hidden()
2386 .child(
2387 Button::new(button_id, label)
2388 .label_size(LabelSize::Small)
2389 .color(Color::Muted)
2390 .truncate(true)
2391 .when(is_file.is_none(), |this| {
2392 this.icon(IconName::ArrowUpRight)
2393 .icon_size(IconSize::XSmall)
2394 .icon_color(Color::Muted)
2395 })
2396 .on_click(cx.listener({
2397 let workspace = self.workspace.clone();
2398 move |_, _, window, cx: &mut Context<Self>| {
2399 Self::open_link(uri.clone(), &workspace, window, cx);
2400 }
2401 })),
2402 )
2403 .into_any_element()
2404 }
2405
2406 fn render_permission_buttons(
2407 &self,
2408 options: &[acp::PermissionOption],
2409 entry_ix: usize,
2410 tool_call_id: acp::ToolCallId,
2411 cx: &Context<Self>,
2412 ) -> Div {
2413 h_flex()
2414 .py_1()
2415 .pl_2()
2416 .pr_1()
2417 .gap_1()
2418 .justify_between()
2419 .flex_wrap()
2420 .border_t_1()
2421 .border_color(self.tool_card_border_color(cx))
2422 .child(
2423 div()
2424 .min_w(rems_from_px(145.))
2425 .child(LoadingLabel::new("Waiting for Confirmation").size(LabelSize::Small)),
2426 )
2427 .child(h_flex().gap_0p5().children(options.iter().map(|option| {
2428 let option_id = SharedString::from(option.id.0.clone());
2429 Button::new((option_id, entry_ix), option.name.clone())
2430 .map(|this| match option.kind {
2431 acp::PermissionOptionKind::AllowOnce => {
2432 this.icon(IconName::Check).icon_color(Color::Success)
2433 }
2434 acp::PermissionOptionKind::AllowAlways => {
2435 this.icon(IconName::CheckDouble).icon_color(Color::Success)
2436 }
2437 acp::PermissionOptionKind::RejectOnce => {
2438 this.icon(IconName::Close).icon_color(Color::Error)
2439 }
2440 acp::PermissionOptionKind::RejectAlways => {
2441 this.icon(IconName::Close).icon_color(Color::Error)
2442 }
2443 })
2444 .icon_position(IconPosition::Start)
2445 .icon_size(IconSize::XSmall)
2446 .label_size(LabelSize::Small)
2447 .on_click(cx.listener({
2448 let tool_call_id = tool_call_id.clone();
2449 let option_id = option.id.clone();
2450 let option_kind = option.kind;
2451 move |this, _, window, cx| {
2452 this.authorize_tool_call(
2453 tool_call_id.clone(),
2454 option_id.clone(),
2455 option_kind,
2456 window,
2457 cx,
2458 );
2459 }
2460 }))
2461 })))
2462 }
2463
2464 fn render_diff_loading(&self, cx: &Context<Self>) -> AnyElement {
2465 let bar = |n: u64, width_class: &str| {
2466 let bg_color = cx.theme().colors().element_active;
2467 let base = h_flex().h_1().rounded_full();
2468
2469 let modified = match width_class {
2470 "w_4_5" => base.w_3_4(),
2471 "w_1_4" => base.w_1_4(),
2472 "w_2_4" => base.w_2_4(),
2473 "w_3_5" => base.w_3_5(),
2474 "w_2_5" => base.w_2_5(),
2475 _ => base.w_1_2(),
2476 };
2477
2478 modified.with_animation(
2479 ElementId::Integer(n),
2480 Animation::new(Duration::from_secs(2)).repeat(),
2481 move |tab, delta| {
2482 let delta = (delta - 0.15 * n as f32) / 0.7;
2483 let delta = 1.0 - (0.5 - delta).abs() * 2.;
2484 let delta = ease_in_out(delta.clamp(0., 1.));
2485 let delta = 0.1 + 0.9 * delta;
2486
2487 tab.bg(bg_color.opacity(delta))
2488 },
2489 )
2490 };
2491
2492 v_flex()
2493 .p_3()
2494 .gap_1()
2495 .rounded_b_md()
2496 .bg(cx.theme().colors().editor_background)
2497 .child(bar(0, "w_4_5"))
2498 .child(bar(1, "w_1_4"))
2499 .child(bar(2, "w_2_4"))
2500 .child(bar(3, "w_3_5"))
2501 .child(bar(4, "w_2_5"))
2502 .into_any_element()
2503 }
2504
2505 fn render_diff_editor(
2506 &self,
2507 entry_ix: usize,
2508 diff: &Entity<acp_thread::Diff>,
2509 tool_call: &ToolCall,
2510 cx: &Context<Self>,
2511 ) -> AnyElement {
2512 let tool_progress = matches!(
2513 &tool_call.status,
2514 ToolCallStatus::InProgress | ToolCallStatus::Pending
2515 );
2516
2517 v_flex()
2518 .h_full()
2519 .border_t_1()
2520 .border_color(self.tool_card_border_color(cx))
2521 .child(
2522 if let Some(entry) = self.entry_view_state.read(cx).entry(entry_ix)
2523 && let Some(editor) = entry.editor_for_diff(diff)
2524 && diff.read(cx).has_revealed_range(cx)
2525 {
2526 editor.into_any_element()
2527 } else if tool_progress && self.as_native_connection(cx).is_some() {
2528 self.render_diff_loading(cx)
2529 } else {
2530 Empty.into_any()
2531 },
2532 )
2533 .into_any()
2534 }
2535
2536 fn render_terminal_tool_call(
2537 &self,
2538 entry_ix: usize,
2539 terminal: &Entity<acp_thread::Terminal>,
2540 tool_call: &ToolCall,
2541 window: &Window,
2542 cx: &Context<Self>,
2543 ) -> AnyElement {
2544 let terminal_data = terminal.read(cx);
2545 let working_dir = terminal_data.working_dir();
2546 let command = terminal_data.command();
2547 let started_at = terminal_data.started_at();
2548
2549 let tool_failed = matches!(
2550 &tool_call.status,
2551 ToolCallStatus::Rejected | ToolCallStatus::Canceled | ToolCallStatus::Failed
2552 );
2553
2554 let output = terminal_data.output();
2555 let command_finished = output.is_some();
2556 let truncated_output =
2557 output.is_some_and(|output| output.original_content_len > output.content.len());
2558 let output_line_count = output.map(|output| output.content_line_count).unwrap_or(0);
2559
2560 let command_failed = command_finished
2561 && output.is_some_and(|o| o.exit_status.is_none_or(|status| !status.success()));
2562
2563 let time_elapsed = if let Some(output) = output {
2564 output.ended_at.duration_since(started_at)
2565 } else {
2566 started_at.elapsed()
2567 };
2568
2569 let header_id =
2570 SharedString::from(format!("terminal-tool-header-{}", terminal.entity_id()));
2571 let header_group = SharedString::from(format!(
2572 "terminal-tool-header-group-{}",
2573 terminal.entity_id()
2574 ));
2575 let header_bg = cx
2576 .theme()
2577 .colors()
2578 .element_background
2579 .blend(cx.theme().colors().editor_foreground.opacity(0.025));
2580 let border_color = cx.theme().colors().border.opacity(0.6);
2581
2582 let working_dir = working_dir
2583 .as_ref()
2584 .map(|path| format!("{}", path.display()))
2585 .unwrap_or_else(|| "current directory".to_string());
2586
2587 let is_expanded = self.expanded_tool_calls.contains(&tool_call.id);
2588
2589 let header = h_flex()
2590 .id(header_id)
2591 .flex_none()
2592 .gap_1()
2593 .justify_between()
2594 .rounded_t_md()
2595 .child(
2596 div()
2597 .id(("command-target-path", terminal.entity_id()))
2598 .w_full()
2599 .max_w_full()
2600 .overflow_x_scroll()
2601 .child(
2602 Label::new(working_dir)
2603 .buffer_font(cx)
2604 .size(LabelSize::XSmall)
2605 .color(Color::Muted),
2606 ),
2607 )
2608 .when(!command_finished, |header| {
2609 header
2610 .gap_1p5()
2611 .child(
2612 Button::new(
2613 SharedString::from(format!("stop-terminal-{}", terminal.entity_id())),
2614 "Stop",
2615 )
2616 .icon(IconName::Stop)
2617 .icon_position(IconPosition::Start)
2618 .icon_size(IconSize::Small)
2619 .icon_color(Color::Error)
2620 .label_size(LabelSize::Small)
2621 .tooltip(move |window, cx| {
2622 Tooltip::with_meta(
2623 "Stop This Command",
2624 None,
2625 "Also possible by placing your cursor inside the terminal and using regular terminal bindings.",
2626 window,
2627 cx,
2628 )
2629 })
2630 .on_click({
2631 let terminal = terminal.clone();
2632 cx.listener(move |_this, _event, _window, cx| {
2633 let inner_terminal = terminal.read(cx).inner().clone();
2634 inner_terminal.update(cx, |inner_terminal, _cx| {
2635 inner_terminal.kill_active_task();
2636 });
2637 })
2638 }),
2639 )
2640 .child(Divider::vertical())
2641 .child(
2642 Icon::new(IconName::ArrowCircle)
2643 .size(IconSize::XSmall)
2644 .color(Color::Info)
2645 .with_rotate_animation(2)
2646 )
2647 })
2648 .when(truncated_output, |header| {
2649 let tooltip = if let Some(output) = output {
2650 if output_line_count + 10 > terminal::MAX_SCROLL_HISTORY_LINES {
2651 format!("Output exceeded terminal max lines and was \
2652 truncated, the model received the first {}.", format_file_size(output.content.len() as u64, true))
2653 } else {
2654 format!(
2655 "Output is {} long, and to avoid unexpected token usage, \
2656 only {} was sent back to the agent.",
2657 format_file_size(output.original_content_len as u64, true),
2658 format_file_size(output.content.len() as u64, true)
2659 )
2660 }
2661 } else {
2662 "Output was truncated".to_string()
2663 };
2664
2665 header.child(
2666 h_flex()
2667 .id(("terminal-tool-truncated-label", terminal.entity_id()))
2668 .gap_1()
2669 .child(
2670 Icon::new(IconName::Info)
2671 .size(IconSize::XSmall)
2672 .color(Color::Ignored),
2673 )
2674 .child(
2675 Label::new("Truncated")
2676 .color(Color::Muted)
2677 .size(LabelSize::XSmall),
2678 )
2679 .tooltip(Tooltip::text(tooltip)),
2680 )
2681 })
2682 .when(time_elapsed > Duration::from_secs(10), |header| {
2683 header.child(
2684 Label::new(format!("({})", duration_alt_display(time_elapsed)))
2685 .buffer_font(cx)
2686 .color(Color::Muted)
2687 .size(LabelSize::XSmall),
2688 )
2689 })
2690 .when(tool_failed || command_failed, |header| {
2691 header.child(
2692 div()
2693 .id(("terminal-tool-error-code-indicator", terminal.entity_id()))
2694 .child(
2695 Icon::new(IconName::Close)
2696 .size(IconSize::Small)
2697 .color(Color::Error),
2698 )
2699 .when_some(output.and_then(|o| o.exit_status), |this, status| {
2700 this.tooltip(Tooltip::text(format!(
2701 "Exited with code {}",
2702 status.code().unwrap_or(-1),
2703 )))
2704 }),
2705 )
2706 })
2707 .child(
2708 Disclosure::new(
2709 SharedString::from(format!(
2710 "terminal-tool-disclosure-{}",
2711 terminal.entity_id()
2712 )),
2713 is_expanded,
2714 )
2715 .opened_icon(IconName::ChevronUp)
2716 .closed_icon(IconName::ChevronDown)
2717 .visible_on_hover(&header_group)
2718 .on_click(cx.listener({
2719 let id = tool_call.id.clone();
2720 move |this, _event, _window, _cx| {
2721 if is_expanded {
2722 this.expanded_tool_calls.remove(&id);
2723 } else {
2724 this.expanded_tool_calls.insert(id.clone());
2725 }
2726 }
2727 })),
2728 );
2729
2730 let terminal_view = self
2731 .entry_view_state
2732 .read(cx)
2733 .entry(entry_ix)
2734 .and_then(|entry| entry.terminal(terminal));
2735 let show_output = is_expanded && terminal_view.is_some();
2736
2737 v_flex()
2738 .my_1p5()
2739 .mx_5()
2740 .border_1()
2741 .when(tool_failed || command_failed, |card| card.border_dashed())
2742 .border_color(border_color)
2743 .rounded_md()
2744 .overflow_hidden()
2745 .child(
2746 v_flex()
2747 .group(&header_group)
2748 .py_1p5()
2749 .pr_1p5()
2750 .pl_2()
2751 .gap_0p5()
2752 .bg(header_bg)
2753 .text_xs()
2754 .child(header)
2755 .child(
2756 MarkdownElement::new(
2757 command.clone(),
2758 terminal_command_markdown_style(window, cx),
2759 )
2760 .code_block_renderer(
2761 markdown::CodeBlockRenderer::Default {
2762 copy_button: false,
2763 copy_button_on_hover: true,
2764 border: false,
2765 },
2766 ),
2767 ),
2768 )
2769 .when(show_output, |this| {
2770 this.child(
2771 div()
2772 .pt_2()
2773 .border_t_1()
2774 .when(tool_failed || command_failed, |card| card.border_dashed())
2775 .border_color(border_color)
2776 .bg(cx.theme().colors().editor_background)
2777 .rounded_b_md()
2778 .text_ui_sm(cx)
2779 .h_full()
2780 .children(terminal_view.map(|terminal_view| {
2781 if terminal_view
2782 .read(cx)
2783 .content_mode(window, cx)
2784 .is_scrollable()
2785 {
2786 div().h_72().child(terminal_view).into_any_element()
2787 } else {
2788 terminal_view.into_any_element()
2789 }
2790 })),
2791 )
2792 })
2793 .into_any()
2794 }
2795
2796 fn render_rules_item(&self, cx: &Context<Self>) -> Option<AnyElement> {
2797 let project_context = self
2798 .as_native_thread(cx)?
2799 .read(cx)
2800 .project_context()
2801 .read(cx);
2802
2803 let user_rules_text = if project_context.user_rules.is_empty() {
2804 None
2805 } else if project_context.user_rules.len() == 1 {
2806 let user_rules = &project_context.user_rules[0];
2807
2808 match user_rules.title.as_ref() {
2809 Some(title) => Some(format!("Using \"{title}\" user rule")),
2810 None => Some("Using user rule".into()),
2811 }
2812 } else {
2813 Some(format!(
2814 "Using {} user rules",
2815 project_context.user_rules.len()
2816 ))
2817 };
2818
2819 let first_user_rules_id = project_context
2820 .user_rules
2821 .first()
2822 .map(|user_rules| user_rules.uuid.0);
2823
2824 let rules_files = project_context
2825 .worktrees
2826 .iter()
2827 .filter_map(|worktree| worktree.rules_file.as_ref())
2828 .collect::<Vec<_>>();
2829
2830 let rules_file_text = match rules_files.as_slice() {
2831 &[] => None,
2832 &[rules_file] => Some(format!(
2833 "Using project {:?} file",
2834 rules_file.path_in_worktree
2835 )),
2836 rules_files => Some(format!("Using {} project rules files", rules_files.len())),
2837 };
2838
2839 if user_rules_text.is_none() && rules_file_text.is_none() {
2840 return None;
2841 }
2842
2843 let has_both = user_rules_text.is_some() && rules_file_text.is_some();
2844
2845 Some(
2846 h_flex()
2847 .px_2p5()
2848 .child(
2849 Icon::new(IconName::Attach)
2850 .size(IconSize::XSmall)
2851 .color(Color::Disabled),
2852 )
2853 .when_some(user_rules_text, |parent, user_rules_text| {
2854 parent.child(
2855 h_flex()
2856 .id("user-rules")
2857 .ml_1()
2858 .mr_1p5()
2859 .child(
2860 Label::new(user_rules_text)
2861 .size(LabelSize::XSmall)
2862 .color(Color::Muted)
2863 .truncate(),
2864 )
2865 .hover(|s| s.bg(cx.theme().colors().element_hover))
2866 .tooltip(Tooltip::text("View User Rules"))
2867 .on_click(move |_event, window, cx| {
2868 window.dispatch_action(
2869 Box::new(OpenRulesLibrary {
2870 prompt_to_select: first_user_rules_id,
2871 }),
2872 cx,
2873 )
2874 }),
2875 )
2876 })
2877 .when(has_both, |this| {
2878 this.child(
2879 Label::new("•")
2880 .size(LabelSize::XSmall)
2881 .color(Color::Disabled),
2882 )
2883 })
2884 .when_some(rules_file_text, |parent, rules_file_text| {
2885 parent.child(
2886 h_flex()
2887 .id("project-rules")
2888 .ml_1p5()
2889 .child(
2890 Label::new(rules_file_text)
2891 .size(LabelSize::XSmall)
2892 .color(Color::Muted),
2893 )
2894 .hover(|s| s.bg(cx.theme().colors().element_hover))
2895 .tooltip(Tooltip::text("View Project Rules"))
2896 .on_click(cx.listener(Self::handle_open_rules)),
2897 )
2898 })
2899 .into_any(),
2900 )
2901 }
2902
2903 fn render_empty_state_section_header(
2904 &self,
2905 label: impl Into<SharedString>,
2906 action_slot: Option<AnyElement>,
2907 cx: &mut Context<Self>,
2908 ) -> impl IntoElement {
2909 div().pl_1().pr_1p5().child(
2910 h_flex()
2911 .mt_2()
2912 .pl_1p5()
2913 .pb_1()
2914 .w_full()
2915 .justify_between()
2916 .border_b_1()
2917 .border_color(cx.theme().colors().border_variant)
2918 .child(
2919 Label::new(label.into())
2920 .size(LabelSize::Small)
2921 .color(Color::Muted),
2922 )
2923 .children(action_slot),
2924 )
2925 }
2926
2927 fn render_recent_history(&self, window: &mut Window, cx: &mut Context<Self>) -> AnyElement {
2928 let render_history = self
2929 .agent
2930 .clone()
2931 .downcast::<agent2::NativeAgentServer>()
2932 .is_some()
2933 && self
2934 .history_store
2935 .update(cx, |history_store, cx| !history_store.is_empty(cx));
2936
2937 v_flex()
2938 .size_full()
2939 .when(render_history, |this| {
2940 let recent_history: Vec<_> = self.history_store.update(cx, |history_store, _| {
2941 history_store.entries().take(3).collect()
2942 });
2943 this.justify_end().child(
2944 v_flex()
2945 .child(
2946 self.render_empty_state_section_header(
2947 "Recent",
2948 Some(
2949 Button::new("view-history", "View All")
2950 .style(ButtonStyle::Subtle)
2951 .label_size(LabelSize::Small)
2952 .key_binding(
2953 KeyBinding::for_action_in(
2954 &OpenHistory,
2955 &self.focus_handle(cx),
2956 window,
2957 cx,
2958 )
2959 .map(|kb| kb.size(rems_from_px(12.))),
2960 )
2961 .on_click(move |_event, window, cx| {
2962 window.dispatch_action(OpenHistory.boxed_clone(), cx);
2963 })
2964 .into_any_element(),
2965 ),
2966 cx,
2967 ),
2968 )
2969 .child(
2970 v_flex().p_1().pr_1p5().gap_1().children(
2971 recent_history
2972 .into_iter()
2973 .enumerate()
2974 .map(|(index, entry)| {
2975 // TODO: Add keyboard navigation.
2976 let is_hovered =
2977 self.hovered_recent_history_item == Some(index);
2978 crate::acp::thread_history::AcpHistoryEntryElement::new(
2979 entry,
2980 cx.entity().downgrade(),
2981 )
2982 .hovered(is_hovered)
2983 .on_hover(cx.listener(
2984 move |this, is_hovered, _window, cx| {
2985 if *is_hovered {
2986 this.hovered_recent_history_item = Some(index);
2987 } else if this.hovered_recent_history_item
2988 == Some(index)
2989 {
2990 this.hovered_recent_history_item = None;
2991 }
2992 cx.notify();
2993 },
2994 ))
2995 .into_any_element()
2996 }),
2997 ),
2998 ),
2999 )
3000 })
3001 .into_any()
3002 }
3003
3004 fn render_auth_required_state(
3005 &self,
3006 connection: &Rc<dyn AgentConnection>,
3007 description: Option<&Entity<Markdown>>,
3008 configuration_view: Option<&AnyView>,
3009 pending_auth_method: Option<&acp::AuthMethodId>,
3010 window: &mut Window,
3011 cx: &Context<Self>,
3012 ) -> Div {
3013 let show_description =
3014 configuration_view.is_none() && description.is_none() && pending_auth_method.is_none();
3015
3016 let auth_methods = connection.auth_methods();
3017
3018 v_flex().flex_1().size_full().justify_end().child(
3019 v_flex()
3020 .p_2()
3021 .pr_3()
3022 .w_full()
3023 .gap_1()
3024 .border_t_1()
3025 .border_color(cx.theme().colors().border)
3026 .bg(cx.theme().status().warning.opacity(0.04))
3027 .child(
3028 h_flex()
3029 .gap_1p5()
3030 .child(
3031 Icon::new(IconName::Warning)
3032 .color(Color::Warning)
3033 .size(IconSize::Small),
3034 )
3035 .child(Label::new("Authentication Required").size(LabelSize::Small)),
3036 )
3037 .children(description.map(|desc| {
3038 div().text_ui(cx).child(self.render_markdown(
3039 desc.clone(),
3040 default_markdown_style(false, false, window, cx),
3041 ))
3042 }))
3043 .children(
3044 configuration_view
3045 .cloned()
3046 .map(|view| div().w_full().child(view)),
3047 )
3048 .when(show_description, |el| {
3049 el.child(
3050 Label::new(format!(
3051 "You are not currently authenticated with {}.{}",
3052 self.agent.name(),
3053 if auth_methods.len() > 1 {
3054 " Please choose one of the following options:"
3055 } else {
3056 ""
3057 }
3058 ))
3059 .size(LabelSize::Small)
3060 .color(Color::Muted)
3061 .mb_1()
3062 .ml_5(),
3063 )
3064 })
3065 .when_some(pending_auth_method, |el, _| {
3066 el.child(
3067 h_flex()
3068 .py_4()
3069 .w_full()
3070 .justify_center()
3071 .gap_1()
3072 .child(
3073 Icon::new(IconName::ArrowCircle)
3074 .size(IconSize::Small)
3075 .color(Color::Muted)
3076 .with_rotate_animation(2),
3077 )
3078 .child(Label::new("Authenticating…").size(LabelSize::Small)),
3079 )
3080 })
3081 .when(!auth_methods.is_empty(), |this| {
3082 this.child(
3083 h_flex()
3084 .justify_end()
3085 .flex_wrap()
3086 .gap_1()
3087 .when(!show_description, |this| {
3088 this.border_t_1()
3089 .mt_1()
3090 .pt_2()
3091 .border_color(cx.theme().colors().border.opacity(0.8))
3092 })
3093 .children(connection.auth_methods().iter().enumerate().rev().map(
3094 |(ix, method)| {
3095 Button::new(
3096 SharedString::from(method.id.0.clone()),
3097 method.name.clone(),
3098 )
3099 .when(ix == 0, |el| {
3100 el.style(ButtonStyle::Tinted(ui::TintColor::Warning))
3101 })
3102 .label_size(LabelSize::Small)
3103 .on_click({
3104 let method_id = method.id.clone();
3105 cx.listener(move |this, _, window, cx| {
3106 telemetry::event!(
3107 "Authenticate Agent Started",
3108 agent = this.agent.telemetry_id(),
3109 method = method_id
3110 );
3111
3112 this.authenticate(method_id.clone(), window, cx)
3113 })
3114 })
3115 },
3116 )),
3117 )
3118 }),
3119 )
3120 }
3121
3122 fn render_load_error(
3123 &self,
3124 e: &LoadError,
3125 window: &mut Window,
3126 cx: &mut Context<Self>,
3127 ) -> AnyElement {
3128 let (title, message, action_slot): (_, SharedString, _) = match e {
3129 LoadError::Unsupported {
3130 command: path,
3131 current_version,
3132 minimum_version,
3133 } => {
3134 return self.render_unsupported(path, current_version, minimum_version, window, cx);
3135 }
3136 LoadError::FailedToInstall(msg) => (
3137 "Failed to Install",
3138 msg.into(),
3139 Some(self.create_copy_button(msg.to_string()).into_any_element()),
3140 ),
3141 LoadError::Exited { status } => (
3142 "Failed to Launch",
3143 format!("Server exited with status {status}").into(),
3144 None,
3145 ),
3146 LoadError::Other(msg) => (
3147 "Failed to Launch",
3148 msg.into(),
3149 Some(self.create_copy_button(msg.to_string()).into_any_element()),
3150 ),
3151 };
3152
3153 Callout::new()
3154 .severity(Severity::Error)
3155 .icon(IconName::XCircleFilled)
3156 .title(title)
3157 .description(message)
3158 .actions_slot(div().children(action_slot))
3159 .into_any_element()
3160 }
3161
3162 fn render_unsupported(
3163 &self,
3164 path: &SharedString,
3165 version: &SharedString,
3166 minimum_version: &SharedString,
3167 _window: &mut Window,
3168 cx: &mut Context<Self>,
3169 ) -> AnyElement {
3170 let (heading_label, description_label) = (
3171 format!("Upgrade {} to work with Zed", self.agent.name()),
3172 if version.is_empty() {
3173 format!(
3174 "Currently using {}, which does not report a valid --version",
3175 path,
3176 )
3177 } else {
3178 format!(
3179 "Currently using {}, which is only version {} (need at least {minimum_version})",
3180 path, version
3181 )
3182 },
3183 );
3184
3185 v_flex()
3186 .w_full()
3187 .p_3p5()
3188 .gap_2p5()
3189 .border_t_1()
3190 .border_color(cx.theme().colors().border)
3191 .bg(linear_gradient(
3192 180.,
3193 linear_color_stop(cx.theme().colors().editor_background.opacity(0.4), 4.),
3194 linear_color_stop(cx.theme().status().info_background.opacity(0.), 0.),
3195 ))
3196 .child(
3197 v_flex().gap_0p5().child(Label::new(heading_label)).child(
3198 Label::new(description_label)
3199 .size(LabelSize::Small)
3200 .color(Color::Muted),
3201 ),
3202 )
3203 .into_any_element()
3204 }
3205
3206 fn render_activity_bar(
3207 &self,
3208 thread_entity: &Entity<AcpThread>,
3209 window: &mut Window,
3210 cx: &Context<Self>,
3211 ) -> Option<AnyElement> {
3212 let thread = thread_entity.read(cx);
3213 let action_log = thread.action_log();
3214 let changed_buffers = action_log.read(cx).changed_buffers(cx);
3215 let plan = thread.plan();
3216
3217 if changed_buffers.is_empty() && plan.is_empty() {
3218 return None;
3219 }
3220
3221 let editor_bg_color = cx.theme().colors().editor_background;
3222 let active_color = cx.theme().colors().element_selected;
3223 let bg_edit_files_disclosure = editor_bg_color.blend(active_color.opacity(0.3));
3224
3225 // Temporarily always enable ACP edit controls. This is temporary, to lessen the
3226 // impact of a nasty bug that causes them to sometimes be disabled when they shouldn't
3227 // be, which blocks you from being able to accept or reject edits. This switches the
3228 // bug to be that sometimes it's enabled when it shouldn't be, which at least doesn't
3229 // block you from using the panel.
3230 let pending_edits = false;
3231
3232 v_flex()
3233 .mt_1()
3234 .mx_2()
3235 .bg(bg_edit_files_disclosure)
3236 .border_1()
3237 .border_b_0()
3238 .border_color(cx.theme().colors().border)
3239 .rounded_t_md()
3240 .shadow(vec![gpui::BoxShadow {
3241 color: gpui::black().opacity(0.15),
3242 offset: point(px(1.), px(-1.)),
3243 blur_radius: px(3.),
3244 spread_radius: px(0.),
3245 }])
3246 .when(!plan.is_empty(), |this| {
3247 this.child(self.render_plan_summary(plan, window, cx))
3248 .when(self.plan_expanded, |parent| {
3249 parent.child(self.render_plan_entries(plan, window, cx))
3250 })
3251 })
3252 .when(!plan.is_empty() && !changed_buffers.is_empty(), |this| {
3253 this.child(Divider::horizontal().color(DividerColor::Border))
3254 })
3255 .when(!changed_buffers.is_empty(), |this| {
3256 this.child(self.render_edits_summary(
3257 &changed_buffers,
3258 self.edits_expanded,
3259 pending_edits,
3260 window,
3261 cx,
3262 ))
3263 .when(self.edits_expanded, |parent| {
3264 parent.child(self.render_edited_files(
3265 action_log,
3266 &changed_buffers,
3267 pending_edits,
3268 cx,
3269 ))
3270 })
3271 })
3272 .into_any()
3273 .into()
3274 }
3275
3276 fn render_plan_summary(&self, plan: &Plan, window: &mut Window, cx: &Context<Self>) -> Div {
3277 let stats = plan.stats();
3278
3279 let title = if let Some(entry) = stats.in_progress_entry
3280 && !self.plan_expanded
3281 {
3282 h_flex()
3283 .w_full()
3284 .cursor_default()
3285 .gap_1()
3286 .text_xs()
3287 .text_color(cx.theme().colors().text_muted)
3288 .justify_between()
3289 .child(
3290 h_flex()
3291 .gap_1()
3292 .child(
3293 Label::new("Current:")
3294 .size(LabelSize::Small)
3295 .color(Color::Muted),
3296 )
3297 .child(MarkdownElement::new(
3298 entry.content.clone(),
3299 plan_label_markdown_style(&entry.status, window, cx),
3300 )),
3301 )
3302 .when(stats.pending > 0, |this| {
3303 this.child(
3304 Label::new(format!("{} left", stats.pending))
3305 .size(LabelSize::Small)
3306 .color(Color::Muted)
3307 .mr_1(),
3308 )
3309 })
3310 } else {
3311 let status_label = if stats.pending == 0 {
3312 "All Done".to_string()
3313 } else if stats.completed == 0 {
3314 format!("{} Tasks", plan.entries.len())
3315 } else {
3316 format!("{}/{}", stats.completed, plan.entries.len())
3317 };
3318
3319 h_flex()
3320 .w_full()
3321 .gap_1()
3322 .justify_between()
3323 .child(
3324 Label::new("Plan")
3325 .size(LabelSize::Small)
3326 .color(Color::Muted),
3327 )
3328 .child(
3329 Label::new(status_label)
3330 .size(LabelSize::Small)
3331 .color(Color::Muted)
3332 .mr_1(),
3333 )
3334 };
3335
3336 h_flex()
3337 .p_1()
3338 .justify_between()
3339 .when(self.plan_expanded, |this| {
3340 this.border_b_1().border_color(cx.theme().colors().border)
3341 })
3342 .child(
3343 h_flex()
3344 .id("plan_summary")
3345 .w_full()
3346 .gap_1()
3347 .child(Disclosure::new("plan_disclosure", self.plan_expanded))
3348 .child(title)
3349 .on_click(cx.listener(|this, _, _, cx| {
3350 this.plan_expanded = !this.plan_expanded;
3351 cx.notify();
3352 })),
3353 )
3354 }
3355
3356 fn render_plan_entries(&self, plan: &Plan, window: &mut Window, cx: &Context<Self>) -> Div {
3357 v_flex().children(plan.entries.iter().enumerate().flat_map(|(index, entry)| {
3358 let element = h_flex()
3359 .py_1()
3360 .px_2()
3361 .gap_2()
3362 .justify_between()
3363 .bg(cx.theme().colors().editor_background)
3364 .when(index < plan.entries.len() - 1, |parent| {
3365 parent.border_color(cx.theme().colors().border).border_b_1()
3366 })
3367 .child(
3368 h_flex()
3369 .id(("plan_entry", index))
3370 .gap_1p5()
3371 .max_w_full()
3372 .overflow_x_scroll()
3373 .text_xs()
3374 .text_color(cx.theme().colors().text_muted)
3375 .child(match entry.status {
3376 acp::PlanEntryStatus::Pending => Icon::new(IconName::TodoPending)
3377 .size(IconSize::Small)
3378 .color(Color::Muted)
3379 .into_any_element(),
3380 acp::PlanEntryStatus::InProgress => Icon::new(IconName::TodoProgress)
3381 .size(IconSize::Small)
3382 .color(Color::Accent)
3383 .with_rotate_animation(2)
3384 .into_any_element(),
3385 acp::PlanEntryStatus::Completed => Icon::new(IconName::TodoComplete)
3386 .size(IconSize::Small)
3387 .color(Color::Success)
3388 .into_any_element(),
3389 })
3390 .child(MarkdownElement::new(
3391 entry.content.clone(),
3392 plan_label_markdown_style(&entry.status, window, cx),
3393 )),
3394 );
3395
3396 Some(element)
3397 }))
3398 }
3399
3400 fn render_edits_summary(
3401 &self,
3402 changed_buffers: &BTreeMap<Entity<Buffer>, Entity<BufferDiff>>,
3403 expanded: bool,
3404 pending_edits: bool,
3405 window: &mut Window,
3406 cx: &Context<Self>,
3407 ) -> Div {
3408 const EDIT_NOT_READY_TOOLTIP_LABEL: &str = "Wait until file edits are complete.";
3409
3410 let focus_handle = self.focus_handle(cx);
3411
3412 h_flex()
3413 .p_1()
3414 .justify_between()
3415 .flex_wrap()
3416 .when(expanded, |this| {
3417 this.border_b_1().border_color(cx.theme().colors().border)
3418 })
3419 .child(
3420 h_flex()
3421 .id("edits-container")
3422 .gap_1()
3423 .child(Disclosure::new("edits-disclosure", expanded))
3424 .map(|this| {
3425 if pending_edits {
3426 this.child(
3427 Label::new(format!(
3428 "Editing {} {}…",
3429 changed_buffers.len(),
3430 if changed_buffers.len() == 1 {
3431 "file"
3432 } else {
3433 "files"
3434 }
3435 ))
3436 .color(Color::Muted)
3437 .size(LabelSize::Small)
3438 .with_animation(
3439 "edit-label",
3440 Animation::new(Duration::from_secs(2))
3441 .repeat()
3442 .with_easing(pulsating_between(0.3, 0.7)),
3443 |label, delta| label.alpha(delta),
3444 ),
3445 )
3446 } else {
3447 this.child(
3448 Label::new("Edits")
3449 .size(LabelSize::Small)
3450 .color(Color::Muted),
3451 )
3452 .child(Label::new("•").size(LabelSize::XSmall).color(Color::Muted))
3453 .child(
3454 Label::new(format!(
3455 "{} {}",
3456 changed_buffers.len(),
3457 if changed_buffers.len() == 1 {
3458 "file"
3459 } else {
3460 "files"
3461 }
3462 ))
3463 .size(LabelSize::Small)
3464 .color(Color::Muted),
3465 )
3466 }
3467 })
3468 .on_click(cx.listener(|this, _, _, cx| {
3469 this.edits_expanded = !this.edits_expanded;
3470 cx.notify();
3471 })),
3472 )
3473 .child(
3474 h_flex()
3475 .gap_1()
3476 .child(
3477 IconButton::new("review-changes", IconName::ListTodo)
3478 .icon_size(IconSize::Small)
3479 .tooltip({
3480 let focus_handle = focus_handle.clone();
3481 move |window, cx| {
3482 Tooltip::for_action_in(
3483 "Review Changes",
3484 &OpenAgentDiff,
3485 &focus_handle,
3486 window,
3487 cx,
3488 )
3489 }
3490 })
3491 .on_click(cx.listener(|_, _, window, cx| {
3492 window.dispatch_action(OpenAgentDiff.boxed_clone(), cx);
3493 })),
3494 )
3495 .child(Divider::vertical().color(DividerColor::Border))
3496 .child(
3497 Button::new("reject-all-changes", "Reject All")
3498 .label_size(LabelSize::Small)
3499 .disabled(pending_edits)
3500 .when(pending_edits, |this| {
3501 this.tooltip(Tooltip::text(EDIT_NOT_READY_TOOLTIP_LABEL))
3502 })
3503 .key_binding(
3504 KeyBinding::for_action_in(
3505 &RejectAll,
3506 &focus_handle.clone(),
3507 window,
3508 cx,
3509 )
3510 .map(|kb| kb.size(rems_from_px(10.))),
3511 )
3512 .on_click(cx.listener(move |this, _, window, cx| {
3513 this.reject_all(&RejectAll, window, cx);
3514 })),
3515 )
3516 .child(
3517 Button::new("keep-all-changes", "Keep All")
3518 .label_size(LabelSize::Small)
3519 .disabled(pending_edits)
3520 .when(pending_edits, |this| {
3521 this.tooltip(Tooltip::text(EDIT_NOT_READY_TOOLTIP_LABEL))
3522 })
3523 .key_binding(
3524 KeyBinding::for_action_in(&KeepAll, &focus_handle, window, cx)
3525 .map(|kb| kb.size(rems_from_px(10.))),
3526 )
3527 .on_click(cx.listener(move |this, _, window, cx| {
3528 this.keep_all(&KeepAll, window, cx);
3529 })),
3530 ),
3531 )
3532 }
3533
3534 fn render_edited_files(
3535 &self,
3536 action_log: &Entity<ActionLog>,
3537 changed_buffers: &BTreeMap<Entity<Buffer>, Entity<BufferDiff>>,
3538 pending_edits: bool,
3539 cx: &Context<Self>,
3540 ) -> Div {
3541 let editor_bg_color = cx.theme().colors().editor_background;
3542
3543 v_flex().children(changed_buffers.iter().enumerate().flat_map(
3544 |(index, (buffer, _diff))| {
3545 let file = buffer.read(cx).file()?;
3546 let path = file.path();
3547
3548 let file_path = path.parent().and_then(|parent| {
3549 let parent_str = parent.to_string_lossy();
3550
3551 if parent_str.is_empty() {
3552 None
3553 } else {
3554 Some(
3555 Label::new(format!("/{}{}", parent_str, std::path::MAIN_SEPARATOR_STR))
3556 .color(Color::Muted)
3557 .size(LabelSize::XSmall)
3558 .buffer_font(cx),
3559 )
3560 }
3561 });
3562
3563 let file_name = path.file_name().map(|name| {
3564 Label::new(name.to_string_lossy().to_string())
3565 .size(LabelSize::XSmall)
3566 .buffer_font(cx)
3567 });
3568
3569 let file_icon = FileIcons::get_icon(path, cx)
3570 .map(Icon::from_path)
3571 .map(|icon| icon.color(Color::Muted).size(IconSize::Small))
3572 .unwrap_or_else(|| {
3573 Icon::new(IconName::File)
3574 .color(Color::Muted)
3575 .size(IconSize::Small)
3576 });
3577
3578 let overlay_gradient = linear_gradient(
3579 90.,
3580 linear_color_stop(editor_bg_color, 1.),
3581 linear_color_stop(editor_bg_color.opacity(0.2), 0.),
3582 );
3583
3584 let element = h_flex()
3585 .group("edited-code")
3586 .id(("file-container", index))
3587 .py_1()
3588 .pl_2()
3589 .pr_1()
3590 .gap_2()
3591 .justify_between()
3592 .bg(editor_bg_color)
3593 .when(index < changed_buffers.len() - 1, |parent| {
3594 parent.border_color(cx.theme().colors().border).border_b_1()
3595 })
3596 .child(
3597 h_flex()
3598 .relative()
3599 .id(("file-name", index))
3600 .pr_8()
3601 .gap_1p5()
3602 .max_w_full()
3603 .overflow_x_scroll()
3604 .child(file_icon)
3605 .child(h_flex().gap_0p5().children(file_name).children(file_path))
3606 .child(
3607 div()
3608 .absolute()
3609 .h_full()
3610 .w_12()
3611 .top_0()
3612 .bottom_0()
3613 .right_0()
3614 .bg(overlay_gradient),
3615 )
3616 .on_click({
3617 let buffer = buffer.clone();
3618 cx.listener(move |this, _, window, cx| {
3619 this.open_edited_buffer(&buffer, window, cx);
3620 })
3621 }),
3622 )
3623 .child(
3624 h_flex()
3625 .gap_1()
3626 .visible_on_hover("edited-code")
3627 .child(
3628 Button::new("review", "Review")
3629 .label_size(LabelSize::Small)
3630 .on_click({
3631 let buffer = buffer.clone();
3632 cx.listener(move |this, _, window, cx| {
3633 this.open_edited_buffer(&buffer, window, cx);
3634 })
3635 }),
3636 )
3637 .child(Divider::vertical().color(DividerColor::BorderVariant))
3638 .child(
3639 Button::new("reject-file", "Reject")
3640 .label_size(LabelSize::Small)
3641 .disabled(pending_edits)
3642 .on_click({
3643 let buffer = buffer.clone();
3644 let action_log = action_log.clone();
3645 move |_, _, cx| {
3646 action_log.update(cx, |action_log, cx| {
3647 action_log
3648 .reject_edits_in_ranges(
3649 buffer.clone(),
3650 vec![Anchor::MIN..Anchor::MAX],
3651 cx,
3652 )
3653 .detach_and_log_err(cx);
3654 })
3655 }
3656 }),
3657 )
3658 .child(
3659 Button::new("keep-file", "Keep")
3660 .label_size(LabelSize::Small)
3661 .disabled(pending_edits)
3662 .on_click({
3663 let buffer = buffer.clone();
3664 let action_log = action_log.clone();
3665 move |_, _, cx| {
3666 action_log.update(cx, |action_log, cx| {
3667 action_log.keep_edits_in_range(
3668 buffer.clone(),
3669 Anchor::MIN..Anchor::MAX,
3670 cx,
3671 );
3672 })
3673 }
3674 }),
3675 ),
3676 );
3677
3678 Some(element)
3679 },
3680 ))
3681 }
3682
3683 fn render_message_editor(&mut self, window: &mut Window, cx: &mut Context<Self>) -> AnyElement {
3684 let focus_handle = self.message_editor.focus_handle(cx);
3685 let editor_bg_color = cx.theme().colors().editor_background;
3686 let (expand_icon, expand_tooltip) = if self.editor_expanded {
3687 (IconName::Minimize, "Minimize Message Editor")
3688 } else {
3689 (IconName::Maximize, "Expand Message Editor")
3690 };
3691
3692 let backdrop = div()
3693 .size_full()
3694 .absolute()
3695 .inset_0()
3696 .bg(cx.theme().colors().panel_background)
3697 .opacity(0.8)
3698 .block_mouse_except_scroll();
3699
3700 let enable_editor = match self.thread_state {
3701 ThreadState::Loading { .. } | ThreadState::Ready { .. } => true,
3702 ThreadState::Unauthenticated { .. } | ThreadState::LoadError(..) => false,
3703 };
3704
3705 v_flex()
3706 .on_action(cx.listener(Self::expand_message_editor))
3707 .on_action(cx.listener(|this, _: &ToggleProfileSelector, window, cx| {
3708 if let Some(profile_selector) = this.profile_selector.as_ref() {
3709 profile_selector.read(cx).menu_handle().toggle(window, cx);
3710 }
3711 }))
3712 .on_action(cx.listener(|this, _: &ToggleModelSelector, window, cx| {
3713 if let Some(model_selector) = this.model_selector.as_ref() {
3714 model_selector
3715 .update(cx, |model_selector, cx| model_selector.toggle(window, cx));
3716 }
3717 }))
3718 .p_2()
3719 .gap_2()
3720 .border_t_1()
3721 .border_color(cx.theme().colors().border)
3722 .bg(editor_bg_color)
3723 .when(self.editor_expanded, |this| {
3724 this.h(vh(0.8, window)).size_full().justify_between()
3725 })
3726 .child(
3727 v_flex()
3728 .relative()
3729 .size_full()
3730 .pt_1()
3731 .pr_2p5()
3732 .child(self.message_editor.clone())
3733 .child(
3734 h_flex()
3735 .absolute()
3736 .top_0()
3737 .right_0()
3738 .opacity(0.5)
3739 .hover(|this| this.opacity(1.0))
3740 .child(
3741 IconButton::new("toggle-height", expand_icon)
3742 .icon_size(IconSize::Small)
3743 .icon_color(Color::Muted)
3744 .tooltip({
3745 move |window, cx| {
3746 Tooltip::for_action_in(
3747 expand_tooltip,
3748 &ExpandMessageEditor,
3749 &focus_handle,
3750 window,
3751 cx,
3752 )
3753 }
3754 })
3755 .on_click(cx.listener(|_, _, window, cx| {
3756 window.dispatch_action(Box::new(ExpandMessageEditor), cx);
3757 })),
3758 ),
3759 ),
3760 )
3761 .child(
3762 h_flex()
3763 .flex_none()
3764 .flex_wrap()
3765 .justify_between()
3766 .child(
3767 h_flex()
3768 .child(self.render_follow_toggle(cx))
3769 .children(self.render_burn_mode_toggle(cx)),
3770 )
3771 .child(
3772 h_flex()
3773 .gap_1()
3774 .children(self.render_token_usage(cx))
3775 .children(self.profile_selector.clone())
3776 .children(self.model_selector.clone())
3777 .child(self.render_send_button(cx)),
3778 ),
3779 )
3780 .when(!enable_editor, |this| this.child(backdrop))
3781 .into_any()
3782 }
3783
3784 pub(crate) fn as_native_connection(
3785 &self,
3786 cx: &App,
3787 ) -> Option<Rc<agent2::NativeAgentConnection>> {
3788 let acp_thread = self.thread()?.read(cx);
3789 acp_thread.connection().clone().downcast()
3790 }
3791
3792 pub(crate) fn as_native_thread(&self, cx: &App) -> Option<Entity<agent2::Thread>> {
3793 let acp_thread = self.thread()?.read(cx);
3794 self.as_native_connection(cx)?
3795 .thread(acp_thread.session_id(), cx)
3796 }
3797
3798 fn is_using_zed_ai_models(&self, cx: &App) -> bool {
3799 self.as_native_thread(cx)
3800 .and_then(|thread| thread.read(cx).model())
3801 .is_some_and(|model| model.provider_id() == language_model::ZED_CLOUD_PROVIDER_ID)
3802 }
3803
3804 fn render_token_usage(&self, cx: &mut Context<Self>) -> Option<Div> {
3805 let thread = self.thread()?.read(cx);
3806 let usage = thread.token_usage()?;
3807 let is_generating = thread.status() != ThreadStatus::Idle;
3808
3809 let used = crate::text_thread_editor::humanize_token_count(usage.used_tokens);
3810 let max = crate::text_thread_editor::humanize_token_count(usage.max_tokens);
3811
3812 Some(
3813 h_flex()
3814 .flex_shrink_0()
3815 .gap_0p5()
3816 .mr_1p5()
3817 .child(
3818 Label::new(used)
3819 .size(LabelSize::Small)
3820 .color(Color::Muted)
3821 .map(|label| {
3822 if is_generating {
3823 label
3824 .with_animation(
3825 "used-tokens-label",
3826 Animation::new(Duration::from_secs(2))
3827 .repeat()
3828 .with_easing(pulsating_between(0.3, 0.8)),
3829 |label, delta| label.alpha(delta),
3830 )
3831 .into_any()
3832 } else {
3833 label.into_any_element()
3834 }
3835 }),
3836 )
3837 .child(
3838 Label::new("/")
3839 .size(LabelSize::Small)
3840 .color(Color::Custom(cx.theme().colors().text_muted.opacity(0.5))),
3841 )
3842 .child(Label::new(max).size(LabelSize::Small).color(Color::Muted)),
3843 )
3844 }
3845
3846 fn toggle_burn_mode(
3847 &mut self,
3848 _: &ToggleBurnMode,
3849 _window: &mut Window,
3850 cx: &mut Context<Self>,
3851 ) {
3852 let Some(thread) = self.as_native_thread(cx) else {
3853 return;
3854 };
3855
3856 thread.update(cx, |thread, cx| {
3857 let current_mode = thread.completion_mode();
3858 thread.set_completion_mode(
3859 match current_mode {
3860 CompletionMode::Burn => CompletionMode::Normal,
3861 CompletionMode::Normal => CompletionMode::Burn,
3862 },
3863 cx,
3864 );
3865 });
3866 }
3867
3868 fn keep_all(&mut self, _: &KeepAll, _window: &mut Window, cx: &mut Context<Self>) {
3869 let Some(thread) = self.thread() else {
3870 return;
3871 };
3872 let action_log = thread.read(cx).action_log().clone();
3873 action_log.update(cx, |action_log, cx| action_log.keep_all_edits(cx));
3874 }
3875
3876 fn reject_all(&mut self, _: &RejectAll, _window: &mut Window, cx: &mut Context<Self>) {
3877 let Some(thread) = self.thread() else {
3878 return;
3879 };
3880 let action_log = thread.read(cx).action_log().clone();
3881 action_log
3882 .update(cx, |action_log, cx| action_log.reject_all_edits(cx))
3883 .detach();
3884 }
3885
3886 fn render_burn_mode_toggle(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
3887 let thread = self.as_native_thread(cx)?.read(cx);
3888
3889 if thread
3890 .model()
3891 .is_none_or(|model| !model.supports_burn_mode())
3892 {
3893 return None;
3894 }
3895
3896 let active_completion_mode = thread.completion_mode();
3897 let burn_mode_enabled = active_completion_mode == CompletionMode::Burn;
3898 let icon = if burn_mode_enabled {
3899 IconName::ZedBurnModeOn
3900 } else {
3901 IconName::ZedBurnMode
3902 };
3903
3904 Some(
3905 IconButton::new("burn-mode", icon)
3906 .icon_size(IconSize::Small)
3907 .icon_color(Color::Muted)
3908 .toggle_state(burn_mode_enabled)
3909 .selected_icon_color(Color::Error)
3910 .on_click(cx.listener(|this, _event, window, cx| {
3911 this.toggle_burn_mode(&ToggleBurnMode, window, cx);
3912 }))
3913 .tooltip(move |_window, cx| {
3914 cx.new(|_| BurnModeTooltip::new().selected(burn_mode_enabled))
3915 .into()
3916 })
3917 .into_any_element(),
3918 )
3919 }
3920
3921 fn render_send_button(&self, cx: &mut Context<Self>) -> AnyElement {
3922 let is_editor_empty = self.message_editor.read(cx).is_empty(cx);
3923 let is_generating = self
3924 .thread()
3925 .is_some_and(|thread| thread.read(cx).status() != ThreadStatus::Idle);
3926
3927 if self.is_loading_contents {
3928 div()
3929 .id("loading-message-content")
3930 .px_1()
3931 .tooltip(Tooltip::text("Loading Added Context…"))
3932 .child(loading_contents_spinner(IconSize::default()))
3933 .into_any_element()
3934 } else if is_generating && is_editor_empty {
3935 IconButton::new("stop-generation", IconName::Stop)
3936 .icon_color(Color::Error)
3937 .style(ButtonStyle::Tinted(ui::TintColor::Error))
3938 .tooltip(move |window, cx| {
3939 Tooltip::for_action("Stop Generation", &editor::actions::Cancel, window, cx)
3940 })
3941 .on_click(cx.listener(|this, _event, _, cx| this.cancel_generation(cx)))
3942 .into_any_element()
3943 } else {
3944 let send_btn_tooltip = if is_editor_empty && !is_generating {
3945 "Type to Send"
3946 } else if is_generating {
3947 "Stop and Send Message"
3948 } else {
3949 "Send"
3950 };
3951
3952 IconButton::new("send-message", IconName::Send)
3953 .style(ButtonStyle::Filled)
3954 .map(|this| {
3955 if is_editor_empty && !is_generating {
3956 this.disabled(true).icon_color(Color::Muted)
3957 } else {
3958 this.icon_color(Color::Accent)
3959 }
3960 })
3961 .tooltip(move |window, cx| Tooltip::for_action(send_btn_tooltip, &Chat, window, cx))
3962 .on_click(cx.listener(|this, _, window, cx| {
3963 this.send(window, cx);
3964 }))
3965 .into_any_element()
3966 }
3967 }
3968
3969 fn is_following(&self, cx: &App) -> bool {
3970 match self.thread().map(|thread| thread.read(cx).status()) {
3971 Some(ThreadStatus::Generating) => self
3972 .workspace
3973 .read_with(cx, |workspace, _| {
3974 workspace.is_being_followed(CollaboratorId::Agent)
3975 })
3976 .unwrap_or(false),
3977 _ => self.should_be_following,
3978 }
3979 }
3980
3981 fn toggle_following(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3982 let following = self.is_following(cx);
3983
3984 self.should_be_following = !following;
3985 if self.thread().map(|thread| thread.read(cx).status()) == Some(ThreadStatus::Generating) {
3986 self.workspace
3987 .update(cx, |workspace, cx| {
3988 if following {
3989 workspace.unfollow(CollaboratorId::Agent, window, cx);
3990 } else {
3991 workspace.follow(CollaboratorId::Agent, window, cx);
3992 }
3993 })
3994 .ok();
3995 }
3996
3997 telemetry::event!("Follow Agent Selected", following = !following);
3998 }
3999
4000 fn render_follow_toggle(&self, cx: &mut Context<Self>) -> impl IntoElement {
4001 let following = self.is_following(cx);
4002
4003 let tooltip_label = if following {
4004 if self.agent.name() == "Zed Agent" {
4005 format!("Stop Following the {}", self.agent.name())
4006 } else {
4007 format!("Stop Following {}", self.agent.name())
4008 }
4009 } else {
4010 if self.agent.name() == "Zed Agent" {
4011 format!("Follow the {}", self.agent.name())
4012 } else {
4013 format!("Follow {}", self.agent.name())
4014 }
4015 };
4016
4017 IconButton::new("follow-agent", IconName::Crosshair)
4018 .icon_size(IconSize::Small)
4019 .icon_color(Color::Muted)
4020 .toggle_state(following)
4021 .selected_icon_color(Some(Color::Custom(cx.theme().players().agent().cursor)))
4022 .tooltip(move |window, cx| {
4023 if following {
4024 Tooltip::for_action(tooltip_label.clone(), &Follow, window, cx)
4025 } else {
4026 Tooltip::with_meta(
4027 tooltip_label.clone(),
4028 Some(&Follow),
4029 "Track the agent's location as it reads and edits files.",
4030 window,
4031 cx,
4032 )
4033 }
4034 })
4035 .on_click(cx.listener(move |this, _, window, cx| {
4036 this.toggle_following(window, cx);
4037 }))
4038 }
4039
4040 fn render_markdown(&self, markdown: Entity<Markdown>, style: MarkdownStyle) -> MarkdownElement {
4041 let workspace = self.workspace.clone();
4042 MarkdownElement::new(markdown, style).on_url_click(move |text, window, cx| {
4043 Self::open_link(text, &workspace, window, cx);
4044 })
4045 }
4046
4047 fn open_link(
4048 url: SharedString,
4049 workspace: &WeakEntity<Workspace>,
4050 window: &mut Window,
4051 cx: &mut App,
4052 ) {
4053 let Some(workspace) = workspace.upgrade() else {
4054 cx.open_url(&url);
4055 return;
4056 };
4057
4058 if let Some(mention) = MentionUri::parse(&url).log_err() {
4059 workspace.update(cx, |workspace, cx| match mention {
4060 MentionUri::File { abs_path } => {
4061 let project = workspace.project();
4062 let Some(path) =
4063 project.update(cx, |project, cx| project.find_project_path(abs_path, cx))
4064 else {
4065 return;
4066 };
4067
4068 workspace
4069 .open_path(path, None, true, window, cx)
4070 .detach_and_log_err(cx);
4071 }
4072 MentionUri::PastedImage => {}
4073 MentionUri::Directory { abs_path } => {
4074 let project = workspace.project();
4075 let Some(entry_id) = project.update(cx, |project, cx| {
4076 let path = project.find_project_path(abs_path, cx)?;
4077 project.entry_for_path(&path, cx).map(|entry| entry.id)
4078 }) else {
4079 return;
4080 };
4081
4082 project.update(cx, |_, cx| {
4083 cx.emit(project::Event::RevealInProjectPanel(entry_id));
4084 });
4085 }
4086 MentionUri::Symbol {
4087 abs_path: path,
4088 line_range,
4089 ..
4090 }
4091 | MentionUri::Selection {
4092 abs_path: Some(path),
4093 line_range,
4094 } => {
4095 let project = workspace.project();
4096 let Some(path) =
4097 project.update(cx, |project, cx| project.find_project_path(path, cx))
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}