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