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 .h_full()
2727 .children(terminal_view.map(|terminal_view| {
2728 if terminal_view
2729 .read(cx)
2730 .content_mode(window, cx)
2731 .is_scrollable()
2732 {
2733 div().h_72().child(terminal_view).into_any_element()
2734 } else {
2735 terminal_view.into_any_element()
2736 }
2737 })),
2738 )
2739 })
2740 .into_any()
2741 }
2742
2743 fn render_rules_item(&self, cx: &Context<Self>) -> Option<AnyElement> {
2744 let project_context = self
2745 .as_native_thread(cx)?
2746 .read(cx)
2747 .project_context()
2748 .read(cx);
2749
2750 let user_rules_text = if project_context.user_rules.is_empty() {
2751 None
2752 } else if project_context.user_rules.len() == 1 {
2753 let user_rules = &project_context.user_rules[0];
2754
2755 match user_rules.title.as_ref() {
2756 Some(title) => Some(format!("Using \"{title}\" user rule")),
2757 None => Some("Using user rule".into()),
2758 }
2759 } else {
2760 Some(format!(
2761 "Using {} user rules",
2762 project_context.user_rules.len()
2763 ))
2764 };
2765
2766 let first_user_rules_id = project_context
2767 .user_rules
2768 .first()
2769 .map(|user_rules| user_rules.uuid.0);
2770
2771 let rules_files = project_context
2772 .worktrees
2773 .iter()
2774 .filter_map(|worktree| worktree.rules_file.as_ref())
2775 .collect::<Vec<_>>();
2776
2777 let rules_file_text = match rules_files.as_slice() {
2778 &[] => None,
2779 &[rules_file] => Some(format!(
2780 "Using project {:?} file",
2781 rules_file.path_in_worktree
2782 )),
2783 rules_files => Some(format!("Using {} project rules files", rules_files.len())),
2784 };
2785
2786 if user_rules_text.is_none() && rules_file_text.is_none() {
2787 return None;
2788 }
2789
2790 let has_both = user_rules_text.is_some() && rules_file_text.is_some();
2791
2792 Some(
2793 h_flex()
2794 .px_2p5()
2795 .child(
2796 Icon::new(IconName::Attach)
2797 .size(IconSize::XSmall)
2798 .color(Color::Disabled),
2799 )
2800 .when_some(user_rules_text, |parent, user_rules_text| {
2801 parent.child(
2802 h_flex()
2803 .id("user-rules")
2804 .ml_1()
2805 .mr_1p5()
2806 .child(
2807 Label::new(user_rules_text)
2808 .size(LabelSize::XSmall)
2809 .color(Color::Muted)
2810 .truncate(),
2811 )
2812 .hover(|s| s.bg(cx.theme().colors().element_hover))
2813 .tooltip(Tooltip::text("View User Rules"))
2814 .on_click(move |_event, window, cx| {
2815 window.dispatch_action(
2816 Box::new(OpenRulesLibrary {
2817 prompt_to_select: first_user_rules_id,
2818 }),
2819 cx,
2820 )
2821 }),
2822 )
2823 })
2824 .when(has_both, |this| {
2825 this.child(
2826 Label::new("•")
2827 .size(LabelSize::XSmall)
2828 .color(Color::Disabled),
2829 )
2830 })
2831 .when_some(rules_file_text, |parent, rules_file_text| {
2832 parent.child(
2833 h_flex()
2834 .id("project-rules")
2835 .ml_1p5()
2836 .child(
2837 Label::new(rules_file_text)
2838 .size(LabelSize::XSmall)
2839 .color(Color::Muted),
2840 )
2841 .hover(|s| s.bg(cx.theme().colors().element_hover))
2842 .tooltip(Tooltip::text("View Project Rules"))
2843 .on_click(cx.listener(Self::handle_open_rules)),
2844 )
2845 })
2846 .into_any(),
2847 )
2848 }
2849
2850 fn render_empty_state_section_header(
2851 &self,
2852 label: impl Into<SharedString>,
2853 action_slot: Option<AnyElement>,
2854 cx: &mut Context<Self>,
2855 ) -> impl IntoElement {
2856 div().pl_1().pr_1p5().child(
2857 h_flex()
2858 .mt_2()
2859 .pl_1p5()
2860 .pb_1()
2861 .w_full()
2862 .justify_between()
2863 .border_b_1()
2864 .border_color(cx.theme().colors().border_variant)
2865 .child(
2866 Label::new(label.into())
2867 .size(LabelSize::Small)
2868 .color(Color::Muted),
2869 )
2870 .children(action_slot),
2871 )
2872 }
2873
2874 fn render_recent_history(&self, window: &mut Window, cx: &mut Context<Self>) -> AnyElement {
2875 let render_history = self
2876 .agent
2877 .clone()
2878 .downcast::<agent2::NativeAgentServer>()
2879 .is_some()
2880 && self
2881 .history_store
2882 .update(cx, |history_store, cx| !history_store.is_empty(cx));
2883
2884 v_flex()
2885 .size_full()
2886 .when(render_history, |this| {
2887 let recent_history: Vec<_> = self.history_store.update(cx, |history_store, _| {
2888 history_store.entries().take(3).collect()
2889 });
2890 this.justify_end().child(
2891 v_flex()
2892 .child(
2893 self.render_empty_state_section_header(
2894 "Recent",
2895 Some(
2896 Button::new("view-history", "View All")
2897 .style(ButtonStyle::Subtle)
2898 .label_size(LabelSize::Small)
2899 .key_binding(
2900 KeyBinding::for_action_in(
2901 &OpenHistory,
2902 &self.focus_handle(cx),
2903 window,
2904 cx,
2905 )
2906 .map(|kb| kb.size(rems_from_px(12.))),
2907 )
2908 .on_click(move |_event, window, cx| {
2909 window.dispatch_action(OpenHistory.boxed_clone(), cx);
2910 })
2911 .into_any_element(),
2912 ),
2913 cx,
2914 ),
2915 )
2916 .child(
2917 v_flex().p_1().pr_1p5().gap_1().children(
2918 recent_history
2919 .into_iter()
2920 .enumerate()
2921 .map(|(index, entry)| {
2922 // TODO: Add keyboard navigation.
2923 let is_hovered =
2924 self.hovered_recent_history_item == Some(index);
2925 crate::acp::thread_history::AcpHistoryEntryElement::new(
2926 entry,
2927 cx.entity().downgrade(),
2928 )
2929 .hovered(is_hovered)
2930 .on_hover(cx.listener(
2931 move |this, is_hovered, _window, cx| {
2932 if *is_hovered {
2933 this.hovered_recent_history_item = Some(index);
2934 } else if this.hovered_recent_history_item
2935 == Some(index)
2936 {
2937 this.hovered_recent_history_item = None;
2938 }
2939 cx.notify();
2940 },
2941 ))
2942 .into_any_element()
2943 }),
2944 ),
2945 ),
2946 )
2947 })
2948 .into_any()
2949 }
2950
2951 fn render_auth_required_state(
2952 &self,
2953 connection: &Rc<dyn AgentConnection>,
2954 description: Option<&Entity<Markdown>>,
2955 configuration_view: Option<&AnyView>,
2956 pending_auth_method: Option<&acp::AuthMethodId>,
2957 window: &mut Window,
2958 cx: &Context<Self>,
2959 ) -> Div {
2960 let show_description =
2961 configuration_view.is_none() && description.is_none() && pending_auth_method.is_none();
2962
2963 v_flex().flex_1().size_full().justify_end().child(
2964 v_flex()
2965 .p_2()
2966 .pr_3()
2967 .w_full()
2968 .gap_1()
2969 .border_t_1()
2970 .border_color(cx.theme().colors().border)
2971 .bg(cx.theme().status().warning.opacity(0.04))
2972 .child(
2973 h_flex()
2974 .gap_1p5()
2975 .child(
2976 Icon::new(IconName::Warning)
2977 .color(Color::Warning)
2978 .size(IconSize::Small),
2979 )
2980 .child(Label::new("Authentication Required").size(LabelSize::Small)),
2981 )
2982 .children(description.map(|desc| {
2983 div().text_ui(cx).child(self.render_markdown(
2984 desc.clone(),
2985 default_markdown_style(false, false, window, cx),
2986 ))
2987 }))
2988 .children(
2989 configuration_view
2990 .cloned()
2991 .map(|view| div().w_full().child(view)),
2992 )
2993 .when(
2994 show_description,
2995 |el| {
2996 el.child(
2997 Label::new(format!(
2998 "You are not currently authenticated with {}. Please choose one of the following options:",
2999 self.agent.name()
3000 ))
3001 .size(LabelSize::Small)
3002 .color(Color::Muted)
3003 .mb_1()
3004 .ml_5(),
3005 )
3006 },
3007 )
3008 .when_some(pending_auth_method, |el, _| {
3009 el.child(
3010 h_flex()
3011 .py_4()
3012 .w_full()
3013 .justify_center()
3014 .gap_1()
3015 .child(
3016 Icon::new(IconName::ArrowCircle)
3017 .size(IconSize::Small)
3018 .color(Color::Muted)
3019 .with_animation(
3020 "arrow-circle",
3021 Animation::new(Duration::from_secs(2)).repeat(),
3022 |icon, delta| {
3023 icon.transform(Transformation::rotate(percentage(
3024 delta,
3025 )))
3026 },
3027 )
3028 .into_any_element(),
3029 )
3030 .child(Label::new("Authenticating…").size(LabelSize::Small)),
3031 )
3032 })
3033 .when(!connection.auth_methods().is_empty(), |this| {
3034 this.child(
3035 h_flex()
3036 .justify_end()
3037 .flex_wrap()
3038 .gap_1()
3039 .when(!show_description, |this| {
3040 this.border_t_1()
3041 .mt_1()
3042 .pt_2()
3043 .border_color(cx.theme().colors().border.opacity(0.8))
3044 })
3045 .children(
3046 connection
3047 .auth_methods()
3048 .iter()
3049 .enumerate()
3050 .rev()
3051 .map(|(ix, method)| {
3052 Button::new(
3053 SharedString::from(method.id.0.clone()),
3054 method.name.clone(),
3055 )
3056 .when(ix == 0, |el| {
3057 el.style(ButtonStyle::Tinted(ui::TintColor::Warning))
3058 })
3059 .label_size(LabelSize::Small)
3060 .on_click({
3061 let method_id = method.id.clone();
3062 cx.listener(move |this, _, window, cx| {
3063 telemetry::event!(
3064 "Authenticate Agent Started",
3065 agent = this.agent.telemetry_id(),
3066 method = method_id
3067 );
3068
3069 this.authenticate(method_id.clone(), window, cx)
3070 })
3071 })
3072 }),
3073 ),
3074 )
3075 })
3076
3077 )
3078 }
3079
3080 fn render_load_error(
3081 &self,
3082 e: &LoadError,
3083 window: &mut Window,
3084 cx: &mut Context<Self>,
3085 ) -> AnyElement {
3086 let (title, message, action_slot): (_, SharedString, _) = match e {
3087 LoadError::Unsupported {
3088 command: path,
3089 current_version,
3090 minimum_version,
3091 } => {
3092 return self.render_unsupported(path, current_version, minimum_version, window, cx);
3093 }
3094 LoadError::FailedToInstall(msg) => (
3095 "Failed to Install",
3096 msg.into(),
3097 Some(self.create_copy_button(msg.to_string()).into_any_element()),
3098 ),
3099 LoadError::Exited { status } => (
3100 "Failed to Launch",
3101 format!("Server exited with status {status}").into(),
3102 None,
3103 ),
3104 LoadError::Other(msg) => (
3105 "Failed to Launch",
3106 msg.into(),
3107 Some(self.create_copy_button(msg.to_string()).into_any_element()),
3108 ),
3109 };
3110
3111 Callout::new()
3112 .severity(Severity::Error)
3113 .icon(IconName::XCircleFilled)
3114 .title(title)
3115 .description(message)
3116 .actions_slot(div().children(action_slot))
3117 .into_any_element()
3118 }
3119
3120 fn render_unsupported(
3121 &self,
3122 path: &SharedString,
3123 version: &SharedString,
3124 minimum_version: &SharedString,
3125 _window: &mut Window,
3126 cx: &mut Context<Self>,
3127 ) -> AnyElement {
3128 let (heading_label, description_label) = (
3129 format!("Upgrade {} to work with Zed", self.agent.name()),
3130 if version.is_empty() {
3131 format!(
3132 "Currently using {}, which does not report a valid --version",
3133 path,
3134 )
3135 } else {
3136 format!(
3137 "Currently using {}, which is only version {} (need at least {minimum_version})",
3138 path, version
3139 )
3140 },
3141 );
3142
3143 v_flex()
3144 .w_full()
3145 .p_3p5()
3146 .gap_2p5()
3147 .border_t_1()
3148 .border_color(cx.theme().colors().border)
3149 .bg(linear_gradient(
3150 180.,
3151 linear_color_stop(cx.theme().colors().editor_background.opacity(0.4), 4.),
3152 linear_color_stop(cx.theme().status().info_background.opacity(0.), 0.),
3153 ))
3154 .child(
3155 v_flex().gap_0p5().child(Label::new(heading_label)).child(
3156 Label::new(description_label)
3157 .size(LabelSize::Small)
3158 .color(Color::Muted),
3159 ),
3160 )
3161 .into_any_element()
3162 }
3163
3164 fn render_activity_bar(
3165 &self,
3166 thread_entity: &Entity<AcpThread>,
3167 window: &mut Window,
3168 cx: &Context<Self>,
3169 ) -> Option<AnyElement> {
3170 let thread = thread_entity.read(cx);
3171 let action_log = thread.action_log();
3172 let changed_buffers = action_log.read(cx).changed_buffers(cx);
3173 let plan = thread.plan();
3174
3175 if changed_buffers.is_empty() && plan.is_empty() {
3176 return None;
3177 }
3178
3179 let editor_bg_color = cx.theme().colors().editor_background;
3180 let active_color = cx.theme().colors().element_selected;
3181 let bg_edit_files_disclosure = editor_bg_color.blend(active_color.opacity(0.3));
3182
3183 // Temporarily always enable ACP edit controls. This is temporary, to lessen the
3184 // impact of a nasty bug that causes them to sometimes be disabled when they shouldn't
3185 // be, which blocks you from being able to accept or reject edits. This switches the
3186 // bug to be that sometimes it's enabled when it shouldn't be, which at least doesn't
3187 // block you from using the panel.
3188 let pending_edits = false;
3189
3190 v_flex()
3191 .mt_1()
3192 .mx_2()
3193 .bg(bg_edit_files_disclosure)
3194 .border_1()
3195 .border_b_0()
3196 .border_color(cx.theme().colors().border)
3197 .rounded_t_md()
3198 .shadow(vec![gpui::BoxShadow {
3199 color: gpui::black().opacity(0.15),
3200 offset: point(px(1.), px(-1.)),
3201 blur_radius: px(3.),
3202 spread_radius: px(0.),
3203 }])
3204 .when(!plan.is_empty(), |this| {
3205 this.child(self.render_plan_summary(plan, window, cx))
3206 .when(self.plan_expanded, |parent| {
3207 parent.child(self.render_plan_entries(plan, window, cx))
3208 })
3209 })
3210 .when(!plan.is_empty() && !changed_buffers.is_empty(), |this| {
3211 this.child(Divider::horizontal().color(DividerColor::Border))
3212 })
3213 .when(!changed_buffers.is_empty(), |this| {
3214 this.child(self.render_edits_summary(
3215 &changed_buffers,
3216 self.edits_expanded,
3217 pending_edits,
3218 window,
3219 cx,
3220 ))
3221 .when(self.edits_expanded, |parent| {
3222 parent.child(self.render_edited_files(
3223 action_log,
3224 &changed_buffers,
3225 pending_edits,
3226 cx,
3227 ))
3228 })
3229 })
3230 .into_any()
3231 .into()
3232 }
3233
3234 fn render_plan_summary(&self, plan: &Plan, window: &mut Window, cx: &Context<Self>) -> Div {
3235 let stats = plan.stats();
3236
3237 let title = if let Some(entry) = stats.in_progress_entry
3238 && !self.plan_expanded
3239 {
3240 h_flex()
3241 .w_full()
3242 .cursor_default()
3243 .gap_1()
3244 .text_xs()
3245 .text_color(cx.theme().colors().text_muted)
3246 .justify_between()
3247 .child(
3248 h_flex()
3249 .gap_1()
3250 .child(
3251 Label::new("Current:")
3252 .size(LabelSize::Small)
3253 .color(Color::Muted),
3254 )
3255 .child(MarkdownElement::new(
3256 entry.content.clone(),
3257 plan_label_markdown_style(&entry.status, window, cx),
3258 )),
3259 )
3260 .when(stats.pending > 0, |this| {
3261 this.child(
3262 Label::new(format!("{} left", stats.pending))
3263 .size(LabelSize::Small)
3264 .color(Color::Muted)
3265 .mr_1(),
3266 )
3267 })
3268 } else {
3269 let status_label = if stats.pending == 0 {
3270 "All Done".to_string()
3271 } else if stats.completed == 0 {
3272 format!("{} Tasks", plan.entries.len())
3273 } else {
3274 format!("{}/{}", stats.completed, plan.entries.len())
3275 };
3276
3277 h_flex()
3278 .w_full()
3279 .gap_1()
3280 .justify_between()
3281 .child(
3282 Label::new("Plan")
3283 .size(LabelSize::Small)
3284 .color(Color::Muted),
3285 )
3286 .child(
3287 Label::new(status_label)
3288 .size(LabelSize::Small)
3289 .color(Color::Muted)
3290 .mr_1(),
3291 )
3292 };
3293
3294 h_flex()
3295 .p_1()
3296 .justify_between()
3297 .when(self.plan_expanded, |this| {
3298 this.border_b_1().border_color(cx.theme().colors().border)
3299 })
3300 .child(
3301 h_flex()
3302 .id("plan_summary")
3303 .w_full()
3304 .gap_1()
3305 .child(Disclosure::new("plan_disclosure", self.plan_expanded))
3306 .child(title)
3307 .on_click(cx.listener(|this, _, _, cx| {
3308 this.plan_expanded = !this.plan_expanded;
3309 cx.notify();
3310 })),
3311 )
3312 }
3313
3314 fn render_plan_entries(&self, plan: &Plan, window: &mut Window, cx: &Context<Self>) -> Div {
3315 v_flex().children(plan.entries.iter().enumerate().flat_map(|(index, entry)| {
3316 let element = h_flex()
3317 .py_1()
3318 .px_2()
3319 .gap_2()
3320 .justify_between()
3321 .bg(cx.theme().colors().editor_background)
3322 .when(index < plan.entries.len() - 1, |parent| {
3323 parent.border_color(cx.theme().colors().border).border_b_1()
3324 })
3325 .child(
3326 h_flex()
3327 .id(("plan_entry", index))
3328 .gap_1p5()
3329 .max_w_full()
3330 .overflow_x_scroll()
3331 .text_xs()
3332 .text_color(cx.theme().colors().text_muted)
3333 .child(match entry.status {
3334 acp::PlanEntryStatus::Pending => Icon::new(IconName::TodoPending)
3335 .size(IconSize::Small)
3336 .color(Color::Muted)
3337 .into_any_element(),
3338 acp::PlanEntryStatus::InProgress => Icon::new(IconName::TodoProgress)
3339 .size(IconSize::Small)
3340 .color(Color::Accent)
3341 .with_animation(
3342 "running",
3343 Animation::new(Duration::from_secs(2)).repeat(),
3344 |icon, delta| {
3345 icon.transform(Transformation::rotate(percentage(delta)))
3346 },
3347 )
3348 .into_any_element(),
3349 acp::PlanEntryStatus::Completed => Icon::new(IconName::TodoComplete)
3350 .size(IconSize::Small)
3351 .color(Color::Success)
3352 .into_any_element(),
3353 })
3354 .child(MarkdownElement::new(
3355 entry.content.clone(),
3356 plan_label_markdown_style(&entry.status, window, cx),
3357 )),
3358 );
3359
3360 Some(element)
3361 }))
3362 }
3363
3364 fn render_edits_summary(
3365 &self,
3366 changed_buffers: &BTreeMap<Entity<Buffer>, Entity<BufferDiff>>,
3367 expanded: bool,
3368 pending_edits: bool,
3369 window: &mut Window,
3370 cx: &Context<Self>,
3371 ) -> Div {
3372 const EDIT_NOT_READY_TOOLTIP_LABEL: &str = "Wait until file edits are complete.";
3373
3374 let focus_handle = self.focus_handle(cx);
3375
3376 h_flex()
3377 .p_1()
3378 .justify_between()
3379 .flex_wrap()
3380 .when(expanded, |this| {
3381 this.border_b_1().border_color(cx.theme().colors().border)
3382 })
3383 .child(
3384 h_flex()
3385 .id("edits-container")
3386 .gap_1()
3387 .child(Disclosure::new("edits-disclosure", expanded))
3388 .map(|this| {
3389 if pending_edits {
3390 this.child(
3391 Label::new(format!(
3392 "Editing {} {}…",
3393 changed_buffers.len(),
3394 if changed_buffers.len() == 1 {
3395 "file"
3396 } else {
3397 "files"
3398 }
3399 ))
3400 .color(Color::Muted)
3401 .size(LabelSize::Small)
3402 .with_animation(
3403 "edit-label",
3404 Animation::new(Duration::from_secs(2))
3405 .repeat()
3406 .with_easing(pulsating_between(0.3, 0.7)),
3407 |label, delta| label.alpha(delta),
3408 ),
3409 )
3410 } else {
3411 this.child(
3412 Label::new("Edits")
3413 .size(LabelSize::Small)
3414 .color(Color::Muted),
3415 )
3416 .child(Label::new("•").size(LabelSize::XSmall).color(Color::Muted))
3417 .child(
3418 Label::new(format!(
3419 "{} {}",
3420 changed_buffers.len(),
3421 if changed_buffers.len() == 1 {
3422 "file"
3423 } else {
3424 "files"
3425 }
3426 ))
3427 .size(LabelSize::Small)
3428 .color(Color::Muted),
3429 )
3430 }
3431 })
3432 .on_click(cx.listener(|this, _, _, cx| {
3433 this.edits_expanded = !this.edits_expanded;
3434 cx.notify();
3435 })),
3436 )
3437 .child(
3438 h_flex()
3439 .gap_1()
3440 .child(
3441 IconButton::new("review-changes", IconName::ListTodo)
3442 .icon_size(IconSize::Small)
3443 .tooltip({
3444 let focus_handle = focus_handle.clone();
3445 move |window, cx| {
3446 Tooltip::for_action_in(
3447 "Review Changes",
3448 &OpenAgentDiff,
3449 &focus_handle,
3450 window,
3451 cx,
3452 )
3453 }
3454 })
3455 .on_click(cx.listener(|_, _, window, cx| {
3456 window.dispatch_action(OpenAgentDiff.boxed_clone(), cx);
3457 })),
3458 )
3459 .child(Divider::vertical().color(DividerColor::Border))
3460 .child(
3461 Button::new("reject-all-changes", "Reject All")
3462 .label_size(LabelSize::Small)
3463 .disabled(pending_edits)
3464 .when(pending_edits, |this| {
3465 this.tooltip(Tooltip::text(EDIT_NOT_READY_TOOLTIP_LABEL))
3466 })
3467 .key_binding(
3468 KeyBinding::for_action_in(
3469 &RejectAll,
3470 &focus_handle.clone(),
3471 window,
3472 cx,
3473 )
3474 .map(|kb| kb.size(rems_from_px(10.))),
3475 )
3476 .on_click(cx.listener(move |this, _, window, cx| {
3477 this.reject_all(&RejectAll, window, cx);
3478 })),
3479 )
3480 .child(
3481 Button::new("keep-all-changes", "Keep All")
3482 .label_size(LabelSize::Small)
3483 .disabled(pending_edits)
3484 .when(pending_edits, |this| {
3485 this.tooltip(Tooltip::text(EDIT_NOT_READY_TOOLTIP_LABEL))
3486 })
3487 .key_binding(
3488 KeyBinding::for_action_in(&KeepAll, &focus_handle, window, cx)
3489 .map(|kb| kb.size(rems_from_px(10.))),
3490 )
3491 .on_click(cx.listener(move |this, _, window, cx| {
3492 this.keep_all(&KeepAll, window, cx);
3493 })),
3494 ),
3495 )
3496 }
3497
3498 fn render_edited_files(
3499 &self,
3500 action_log: &Entity<ActionLog>,
3501 changed_buffers: &BTreeMap<Entity<Buffer>, Entity<BufferDiff>>,
3502 pending_edits: bool,
3503 cx: &Context<Self>,
3504 ) -> Div {
3505 let editor_bg_color = cx.theme().colors().editor_background;
3506
3507 v_flex().children(changed_buffers.iter().enumerate().flat_map(
3508 |(index, (buffer, _diff))| {
3509 let file = buffer.read(cx).file()?;
3510 let path = file.path();
3511
3512 let file_path = path.parent().and_then(|parent| {
3513 let parent_str = parent.to_string_lossy();
3514
3515 if parent_str.is_empty() {
3516 None
3517 } else {
3518 Some(
3519 Label::new(format!("/{}{}", parent_str, std::path::MAIN_SEPARATOR_STR))
3520 .color(Color::Muted)
3521 .size(LabelSize::XSmall)
3522 .buffer_font(cx),
3523 )
3524 }
3525 });
3526
3527 let file_name = path.file_name().map(|name| {
3528 Label::new(name.to_string_lossy().to_string())
3529 .size(LabelSize::XSmall)
3530 .buffer_font(cx)
3531 });
3532
3533 let file_icon = FileIcons::get_icon(path, cx)
3534 .map(Icon::from_path)
3535 .map(|icon| icon.color(Color::Muted).size(IconSize::Small))
3536 .unwrap_or_else(|| {
3537 Icon::new(IconName::File)
3538 .color(Color::Muted)
3539 .size(IconSize::Small)
3540 });
3541
3542 let overlay_gradient = linear_gradient(
3543 90.,
3544 linear_color_stop(editor_bg_color, 1.),
3545 linear_color_stop(editor_bg_color.opacity(0.2), 0.),
3546 );
3547
3548 let element = h_flex()
3549 .group("edited-code")
3550 .id(("file-container", index))
3551 .py_1()
3552 .pl_2()
3553 .pr_1()
3554 .gap_2()
3555 .justify_between()
3556 .bg(editor_bg_color)
3557 .when(index < changed_buffers.len() - 1, |parent| {
3558 parent.border_color(cx.theme().colors().border).border_b_1()
3559 })
3560 .child(
3561 h_flex()
3562 .relative()
3563 .id(("file-name", index))
3564 .pr_8()
3565 .gap_1p5()
3566 .max_w_full()
3567 .overflow_x_scroll()
3568 .child(file_icon)
3569 .child(h_flex().gap_0p5().children(file_name).children(file_path))
3570 .child(
3571 div()
3572 .absolute()
3573 .h_full()
3574 .w_12()
3575 .top_0()
3576 .bottom_0()
3577 .right_0()
3578 .bg(overlay_gradient),
3579 )
3580 .on_click({
3581 let buffer = buffer.clone();
3582 cx.listener(move |this, _, window, cx| {
3583 this.open_edited_buffer(&buffer, window, cx);
3584 })
3585 }),
3586 )
3587 .child(
3588 h_flex()
3589 .gap_1()
3590 .visible_on_hover("edited-code")
3591 .child(
3592 Button::new("review", "Review")
3593 .label_size(LabelSize::Small)
3594 .on_click({
3595 let buffer = buffer.clone();
3596 cx.listener(move |this, _, window, cx| {
3597 this.open_edited_buffer(&buffer, window, cx);
3598 })
3599 }),
3600 )
3601 .child(Divider::vertical().color(DividerColor::BorderVariant))
3602 .child(
3603 Button::new("reject-file", "Reject")
3604 .label_size(LabelSize::Small)
3605 .disabled(pending_edits)
3606 .on_click({
3607 let buffer = buffer.clone();
3608 let action_log = action_log.clone();
3609 move |_, _, cx| {
3610 action_log.update(cx, |action_log, cx| {
3611 action_log
3612 .reject_edits_in_ranges(
3613 buffer.clone(),
3614 vec![Anchor::MIN..Anchor::MAX],
3615 cx,
3616 )
3617 .detach_and_log_err(cx);
3618 })
3619 }
3620 }),
3621 )
3622 .child(
3623 Button::new("keep-file", "Keep")
3624 .label_size(LabelSize::Small)
3625 .disabled(pending_edits)
3626 .on_click({
3627 let buffer = buffer.clone();
3628 let action_log = action_log.clone();
3629 move |_, _, cx| {
3630 action_log.update(cx, |action_log, cx| {
3631 action_log.keep_edits_in_range(
3632 buffer.clone(),
3633 Anchor::MIN..Anchor::MAX,
3634 cx,
3635 );
3636 })
3637 }
3638 }),
3639 ),
3640 );
3641
3642 Some(element)
3643 },
3644 ))
3645 }
3646
3647 fn render_message_editor(&mut self, window: &mut Window, cx: &mut Context<Self>) -> AnyElement {
3648 let focus_handle = self.message_editor.focus_handle(cx);
3649 let editor_bg_color = cx.theme().colors().editor_background;
3650 let (expand_icon, expand_tooltip) = if self.editor_expanded {
3651 (IconName::Minimize, "Minimize Message Editor")
3652 } else {
3653 (IconName::Maximize, "Expand Message Editor")
3654 };
3655
3656 let backdrop = div()
3657 .size_full()
3658 .absolute()
3659 .inset_0()
3660 .bg(cx.theme().colors().panel_background)
3661 .opacity(0.8)
3662 .block_mouse_except_scroll();
3663
3664 let enable_editor = match self.thread_state {
3665 ThreadState::Loading { .. } | ThreadState::Ready { .. } => true,
3666 ThreadState::Unauthenticated { .. } | ThreadState::LoadError(..) => false,
3667 };
3668
3669 v_flex()
3670 .on_action(cx.listener(Self::expand_message_editor))
3671 .on_action(cx.listener(|this, _: &ToggleProfileSelector, window, cx| {
3672 if let Some(profile_selector) = this.profile_selector.as_ref() {
3673 profile_selector.read(cx).menu_handle().toggle(window, cx);
3674 }
3675 }))
3676 .on_action(cx.listener(|this, _: &ToggleModelSelector, window, cx| {
3677 if let Some(model_selector) = this.model_selector.as_ref() {
3678 model_selector
3679 .update(cx, |model_selector, cx| model_selector.toggle(window, cx));
3680 }
3681 }))
3682 .p_2()
3683 .gap_2()
3684 .border_t_1()
3685 .border_color(cx.theme().colors().border)
3686 .bg(editor_bg_color)
3687 .when(self.editor_expanded, |this| {
3688 this.h(vh(0.8, window)).size_full().justify_between()
3689 })
3690 .child(
3691 v_flex()
3692 .relative()
3693 .size_full()
3694 .pt_1()
3695 .pr_2p5()
3696 .child(self.message_editor.clone())
3697 .child(
3698 h_flex()
3699 .absolute()
3700 .top_0()
3701 .right_0()
3702 .opacity(0.5)
3703 .hover(|this| this.opacity(1.0))
3704 .child(
3705 IconButton::new("toggle-height", expand_icon)
3706 .icon_size(IconSize::Small)
3707 .icon_color(Color::Muted)
3708 .tooltip({
3709 move |window, cx| {
3710 Tooltip::for_action_in(
3711 expand_tooltip,
3712 &ExpandMessageEditor,
3713 &focus_handle,
3714 window,
3715 cx,
3716 )
3717 }
3718 })
3719 .on_click(cx.listener(|_, _, window, cx| {
3720 window.dispatch_action(Box::new(ExpandMessageEditor), cx);
3721 })),
3722 ),
3723 ),
3724 )
3725 .child(
3726 h_flex()
3727 .flex_none()
3728 .flex_wrap()
3729 .justify_between()
3730 .child(
3731 h_flex()
3732 .child(self.render_follow_toggle(cx))
3733 .children(self.render_burn_mode_toggle(cx)),
3734 )
3735 .child(
3736 h_flex()
3737 .gap_1()
3738 .children(self.render_token_usage(cx))
3739 .children(self.profile_selector.clone())
3740 .children(self.model_selector.clone())
3741 .child(self.render_send_button(cx)),
3742 ),
3743 )
3744 .when(!enable_editor, |this| this.child(backdrop))
3745 .into_any()
3746 }
3747
3748 pub(crate) fn as_native_connection(
3749 &self,
3750 cx: &App,
3751 ) -> Option<Rc<agent2::NativeAgentConnection>> {
3752 let acp_thread = self.thread()?.read(cx);
3753 acp_thread.connection().clone().downcast()
3754 }
3755
3756 pub(crate) fn as_native_thread(&self, cx: &App) -> Option<Entity<agent2::Thread>> {
3757 let acp_thread = self.thread()?.read(cx);
3758 self.as_native_connection(cx)?
3759 .thread(acp_thread.session_id(), cx)
3760 }
3761
3762 fn is_using_zed_ai_models(&self, cx: &App) -> bool {
3763 self.as_native_thread(cx)
3764 .and_then(|thread| thread.read(cx).model())
3765 .is_some_and(|model| model.provider_id() == language_model::ZED_CLOUD_PROVIDER_ID)
3766 }
3767
3768 fn render_token_usage(&self, cx: &mut Context<Self>) -> Option<Div> {
3769 let thread = self.thread()?.read(cx);
3770 let usage = thread.token_usage()?;
3771 let is_generating = thread.status() != ThreadStatus::Idle;
3772
3773 let used = crate::text_thread_editor::humanize_token_count(usage.used_tokens);
3774 let max = crate::text_thread_editor::humanize_token_count(usage.max_tokens);
3775
3776 Some(
3777 h_flex()
3778 .flex_shrink_0()
3779 .gap_0p5()
3780 .mr_1p5()
3781 .child(
3782 Label::new(used)
3783 .size(LabelSize::Small)
3784 .color(Color::Muted)
3785 .map(|label| {
3786 if is_generating {
3787 label
3788 .with_animation(
3789 "used-tokens-label",
3790 Animation::new(Duration::from_secs(2))
3791 .repeat()
3792 .with_easing(pulsating_between(0.3, 0.8)),
3793 |label, delta| label.alpha(delta),
3794 )
3795 .into_any()
3796 } else {
3797 label.into_any_element()
3798 }
3799 }),
3800 )
3801 .child(
3802 Label::new("/")
3803 .size(LabelSize::Small)
3804 .color(Color::Custom(cx.theme().colors().text_muted.opacity(0.5))),
3805 )
3806 .child(Label::new(max).size(LabelSize::Small).color(Color::Muted)),
3807 )
3808 }
3809
3810 fn toggle_burn_mode(
3811 &mut self,
3812 _: &ToggleBurnMode,
3813 _window: &mut Window,
3814 cx: &mut Context<Self>,
3815 ) {
3816 let Some(thread) = self.as_native_thread(cx) else {
3817 return;
3818 };
3819
3820 thread.update(cx, |thread, cx| {
3821 let current_mode = thread.completion_mode();
3822 thread.set_completion_mode(
3823 match current_mode {
3824 CompletionMode::Burn => CompletionMode::Normal,
3825 CompletionMode::Normal => CompletionMode::Burn,
3826 },
3827 cx,
3828 );
3829 });
3830 }
3831
3832 fn keep_all(&mut self, _: &KeepAll, _window: &mut Window, cx: &mut Context<Self>) {
3833 let Some(thread) = self.thread() else {
3834 return;
3835 };
3836 let action_log = thread.read(cx).action_log().clone();
3837 action_log.update(cx, |action_log, cx| action_log.keep_all_edits(cx));
3838 }
3839
3840 fn reject_all(&mut self, _: &RejectAll, _window: &mut Window, cx: &mut Context<Self>) {
3841 let Some(thread) = self.thread() else {
3842 return;
3843 };
3844 let action_log = thread.read(cx).action_log().clone();
3845 action_log
3846 .update(cx, |action_log, cx| action_log.reject_all_edits(cx))
3847 .detach();
3848 }
3849
3850 fn render_burn_mode_toggle(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
3851 let thread = self.as_native_thread(cx)?.read(cx);
3852
3853 if thread
3854 .model()
3855 .is_none_or(|model| !model.supports_burn_mode())
3856 {
3857 return None;
3858 }
3859
3860 let active_completion_mode = thread.completion_mode();
3861 let burn_mode_enabled = active_completion_mode == CompletionMode::Burn;
3862 let icon = if burn_mode_enabled {
3863 IconName::ZedBurnModeOn
3864 } else {
3865 IconName::ZedBurnMode
3866 };
3867
3868 Some(
3869 IconButton::new("burn-mode", icon)
3870 .icon_size(IconSize::Small)
3871 .icon_color(Color::Muted)
3872 .toggle_state(burn_mode_enabled)
3873 .selected_icon_color(Color::Error)
3874 .on_click(cx.listener(|this, _event, window, cx| {
3875 this.toggle_burn_mode(&ToggleBurnMode, window, cx);
3876 }))
3877 .tooltip(move |_window, cx| {
3878 cx.new(|_| BurnModeTooltip::new().selected(burn_mode_enabled))
3879 .into()
3880 })
3881 .into_any_element(),
3882 )
3883 }
3884
3885 fn render_send_button(&self, cx: &mut Context<Self>) -> AnyElement {
3886 let is_editor_empty = self.message_editor.read(cx).is_empty(cx);
3887 let is_generating = self
3888 .thread()
3889 .is_some_and(|thread| thread.read(cx).status() != ThreadStatus::Idle);
3890
3891 if self.is_loading_contents {
3892 div()
3893 .id("loading-message-content")
3894 .px_1()
3895 .tooltip(Tooltip::text("Loading Added Context…"))
3896 .child(loading_contents_spinner(IconSize::default()))
3897 .into_any_element()
3898 } else if is_generating && is_editor_empty {
3899 IconButton::new("stop-generation", IconName::Stop)
3900 .icon_color(Color::Error)
3901 .style(ButtonStyle::Tinted(ui::TintColor::Error))
3902 .tooltip(move |window, cx| {
3903 Tooltip::for_action("Stop Generation", &editor::actions::Cancel, window, cx)
3904 })
3905 .on_click(cx.listener(|this, _event, _, cx| this.cancel_generation(cx)))
3906 .into_any_element()
3907 } else {
3908 let send_btn_tooltip = if is_editor_empty && !is_generating {
3909 "Type to Send"
3910 } else if is_generating {
3911 "Stop and Send Message"
3912 } else {
3913 "Send"
3914 };
3915
3916 IconButton::new("send-message", IconName::Send)
3917 .style(ButtonStyle::Filled)
3918 .map(|this| {
3919 if is_editor_empty && !is_generating {
3920 this.disabled(true).icon_color(Color::Muted)
3921 } else {
3922 this.icon_color(Color::Accent)
3923 }
3924 })
3925 .tooltip(move |window, cx| Tooltip::for_action(send_btn_tooltip, &Chat, window, cx))
3926 .on_click(cx.listener(|this, _, window, cx| {
3927 this.send(window, cx);
3928 }))
3929 .into_any_element()
3930 }
3931 }
3932
3933 fn is_following(&self, cx: &App) -> bool {
3934 match self.thread().map(|thread| thread.read(cx).status()) {
3935 Some(ThreadStatus::Generating) => self
3936 .workspace
3937 .read_with(cx, |workspace, _| {
3938 workspace.is_being_followed(CollaboratorId::Agent)
3939 })
3940 .unwrap_or(false),
3941 _ => self.should_be_following,
3942 }
3943 }
3944
3945 fn toggle_following(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3946 let following = self.is_following(cx);
3947
3948 self.should_be_following = !following;
3949 if self.thread().map(|thread| thread.read(cx).status()) == Some(ThreadStatus::Generating) {
3950 self.workspace
3951 .update(cx, |workspace, cx| {
3952 if following {
3953 workspace.unfollow(CollaboratorId::Agent, window, cx);
3954 } else {
3955 workspace.follow(CollaboratorId::Agent, window, cx);
3956 }
3957 })
3958 .ok();
3959 }
3960
3961 telemetry::event!("Follow Agent Selected", following = !following);
3962 }
3963
3964 fn render_follow_toggle(&self, cx: &mut Context<Self>) -> impl IntoElement {
3965 let following = self.is_following(cx);
3966
3967 let tooltip_label = if following {
3968 if self.agent.name() == "Zed Agent" {
3969 format!("Stop Following the {}", self.agent.name())
3970 } else {
3971 format!("Stop Following {}", self.agent.name())
3972 }
3973 } else {
3974 if self.agent.name() == "Zed Agent" {
3975 format!("Follow the {}", self.agent.name())
3976 } else {
3977 format!("Follow {}", self.agent.name())
3978 }
3979 };
3980
3981 IconButton::new("follow-agent", IconName::Crosshair)
3982 .icon_size(IconSize::Small)
3983 .icon_color(Color::Muted)
3984 .toggle_state(following)
3985 .selected_icon_color(Some(Color::Custom(cx.theme().players().agent().cursor)))
3986 .tooltip(move |window, cx| {
3987 if following {
3988 Tooltip::for_action(tooltip_label.clone(), &Follow, window, cx)
3989 } else {
3990 Tooltip::with_meta(
3991 tooltip_label.clone(),
3992 Some(&Follow),
3993 "Track the agent's location as it reads and edits files.",
3994 window,
3995 cx,
3996 )
3997 }
3998 })
3999 .on_click(cx.listener(move |this, _, window, cx| {
4000 this.toggle_following(window, cx);
4001 }))
4002 }
4003
4004 fn render_markdown(&self, markdown: Entity<Markdown>, style: MarkdownStyle) -> MarkdownElement {
4005 let workspace = self.workspace.clone();
4006 MarkdownElement::new(markdown, style).on_url_click(move |text, window, cx| {
4007 Self::open_link(text, &workspace, window, cx);
4008 })
4009 }
4010
4011 fn open_link(
4012 url: SharedString,
4013 workspace: &WeakEntity<Workspace>,
4014 window: &mut Window,
4015 cx: &mut App,
4016 ) {
4017 let Some(workspace) = workspace.upgrade() else {
4018 cx.open_url(&url);
4019 return;
4020 };
4021
4022 if let Some(mention) = MentionUri::parse(&url).log_err() {
4023 workspace.update(cx, |workspace, cx| match mention {
4024 MentionUri::File { abs_path } => {
4025 let project = workspace.project();
4026 let Some(path) =
4027 project.update(cx, |project, cx| project.find_project_path(abs_path, cx))
4028 else {
4029 return;
4030 };
4031
4032 workspace
4033 .open_path(path, None, true, window, cx)
4034 .detach_and_log_err(cx);
4035 }
4036 MentionUri::PastedImage => {}
4037 MentionUri::Directory { abs_path } => {
4038 let project = workspace.project();
4039 let Some(entry) = project.update(cx, |project, cx| {
4040 let path = project.find_project_path(abs_path, cx)?;
4041 project.entry_for_path(&path, cx)
4042 }) else {
4043 return;
4044 };
4045
4046 project.update(cx, |_, cx| {
4047 cx.emit(project::Event::RevealInProjectPanel(entry.id));
4048 });
4049 }
4050 MentionUri::Symbol {
4051 abs_path: path,
4052 line_range,
4053 ..
4054 }
4055 | MentionUri::Selection {
4056 abs_path: Some(path),
4057 line_range,
4058 } => {
4059 let project = workspace.project();
4060 let Some((path, _)) = project.update(cx, |project, cx| {
4061 let path = project.find_project_path(path, cx)?;
4062 let entry = project.entry_for_path(&path, cx)?;
4063 Some((path, entry))
4064 }) else {
4065 return;
4066 };
4067
4068 let item = workspace.open_path(path, None, true, window, cx);
4069 window
4070 .spawn(cx, async move |cx| {
4071 let Some(editor) = item.await?.downcast::<Editor>() else {
4072 return Ok(());
4073 };
4074 let range = Point::new(*line_range.start(), 0)
4075 ..Point::new(*line_range.start(), 0);
4076 editor
4077 .update_in(cx, |editor, window, cx| {
4078 editor.change_selections(
4079 SelectionEffects::scroll(Autoscroll::center()),
4080 window,
4081 cx,
4082 |s| s.select_ranges(vec![range]),
4083 );
4084 })
4085 .ok();
4086 anyhow::Ok(())
4087 })
4088 .detach_and_log_err(cx);
4089 }
4090 MentionUri::Selection { abs_path: None, .. } => {}
4091 MentionUri::Thread { id, name } => {
4092 if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
4093 panel.update(cx, |panel, cx| {
4094 panel.load_agent_thread(
4095 DbThreadMetadata {
4096 id,
4097 title: name.into(),
4098 updated_at: Default::default(),
4099 },
4100 window,
4101 cx,
4102 )
4103 });
4104 }
4105 }
4106 MentionUri::TextThread { path, .. } => {
4107 if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
4108 panel.update(cx, |panel, cx| {
4109 panel
4110 .open_saved_prompt_editor(path.as_path().into(), window, cx)
4111 .detach_and_log_err(cx);
4112 });
4113 }
4114 }
4115 MentionUri::Rule { id, .. } => {
4116 let PromptId::User { uuid } = id else {
4117 return;
4118 };
4119 window.dispatch_action(
4120 Box::new(OpenRulesLibrary {
4121 prompt_to_select: Some(uuid.0),
4122 }),
4123 cx,
4124 )
4125 }
4126 MentionUri::Fetch { url } => {
4127 cx.open_url(url.as_str());
4128 }
4129 })
4130 } else {
4131 cx.open_url(&url);
4132 }
4133 }
4134
4135 fn open_tool_call_location(
4136 &self,
4137 entry_ix: usize,
4138 location_ix: usize,
4139 window: &mut Window,
4140 cx: &mut Context<Self>,
4141 ) -> Option<()> {
4142 let (tool_call_location, agent_location) = self
4143 .thread()?
4144 .read(cx)
4145 .entries()
4146 .get(entry_ix)?
4147 .location(location_ix)?;
4148
4149 let project_path = self
4150 .project
4151 .read(cx)
4152 .find_project_path(&tool_call_location.path, cx)?;
4153
4154 let open_task = self
4155 .workspace
4156 .update(cx, |workspace, cx| {
4157 workspace.open_path(project_path, None, true, window, cx)
4158 })
4159 .log_err()?;
4160 window
4161 .spawn(cx, async move |cx| {
4162 let item = open_task.await?;
4163
4164 let Some(active_editor) = item.downcast::<Editor>() else {
4165 return anyhow::Ok(());
4166 };
4167
4168 active_editor.update_in(cx, |editor, window, cx| {
4169 let multibuffer = editor.buffer().read(cx);
4170 let buffer = multibuffer.as_singleton();
4171 if agent_location.buffer.upgrade() == buffer {
4172 let excerpt_id = multibuffer.excerpt_ids().first().cloned();
4173 let anchor = editor::Anchor::in_buffer(
4174 excerpt_id.unwrap(),
4175 buffer.unwrap().read(cx).remote_id(),
4176 agent_location.position,
4177 );
4178 editor.change_selections(Default::default(), window, cx, |selections| {
4179 selections.select_anchor_ranges([anchor..anchor]);
4180 })
4181 } else {
4182 let row = tool_call_location.line.unwrap_or_default();
4183 editor.change_selections(Default::default(), window, cx, |selections| {
4184 selections.select_ranges([Point::new(row, 0)..Point::new(row, 0)]);
4185 })
4186 }
4187 })?;
4188
4189 anyhow::Ok(())
4190 })
4191 .detach_and_log_err(cx);
4192
4193 None
4194 }
4195
4196 pub fn open_thread_as_markdown(
4197 &self,
4198 workspace: Entity<Workspace>,
4199 window: &mut Window,
4200 cx: &mut App,
4201 ) -> Task<Result<()>> {
4202 let markdown_language_task = workspace
4203 .read(cx)
4204 .app_state()
4205 .languages
4206 .language_for_name("Markdown");
4207
4208 let (thread_summary, markdown) = if let Some(thread) = self.thread() {
4209 let thread = thread.read(cx);
4210 (thread.title().to_string(), thread.to_markdown(cx))
4211 } else {
4212 return Task::ready(Ok(()));
4213 };
4214
4215 window.spawn(cx, async move |cx| {
4216 let markdown_language = markdown_language_task.await?;
4217
4218 workspace.update_in(cx, |workspace, window, cx| {
4219 let project = workspace.project().clone();
4220
4221 if !project.read(cx).is_local() {
4222 bail!("failed to open active thread as markdown in remote project");
4223 }
4224
4225 let buffer = project.update(cx, |project, cx| {
4226 project.create_local_buffer(&markdown, Some(markdown_language), cx)
4227 });
4228 let buffer = cx.new(|cx| {
4229 MultiBuffer::singleton(buffer, cx).with_title(thread_summary.clone())
4230 });
4231
4232 workspace.add_item_to_active_pane(
4233 Box::new(cx.new(|cx| {
4234 let mut editor =
4235 Editor::for_multibuffer(buffer, Some(project.clone()), window, cx);
4236 editor.set_breadcrumb_header(thread_summary);
4237 editor
4238 })),
4239 None,
4240 true,
4241 window,
4242 cx,
4243 );
4244
4245 anyhow::Ok(())
4246 })??;
4247 anyhow::Ok(())
4248 })
4249 }
4250
4251 fn scroll_to_top(&mut self, cx: &mut Context<Self>) {
4252 self.list_state.scroll_to(ListOffset::default());
4253 cx.notify();
4254 }
4255
4256 pub fn scroll_to_bottom(&mut self, cx: &mut Context<Self>) {
4257 if let Some(thread) = self.thread() {
4258 let entry_count = thread.read(cx).entries().len();
4259 self.list_state.reset(entry_count);
4260 cx.notify();
4261 }
4262 }
4263
4264 fn notify_with_sound(
4265 &mut self,
4266 caption: impl Into<SharedString>,
4267 icon: IconName,
4268 window: &mut Window,
4269 cx: &mut Context<Self>,
4270 ) {
4271 self.play_notification_sound(window, cx);
4272 self.show_notification(caption, icon, window, cx);
4273 }
4274
4275 fn play_notification_sound(&self, window: &Window, cx: &mut App) {
4276 let settings = AgentSettings::get_global(cx);
4277 if settings.play_sound_when_agent_done && !window.is_window_active() {
4278 Audio::play_sound(Sound::AgentDone, cx);
4279 }
4280 }
4281
4282 fn show_notification(
4283 &mut self,
4284 caption: impl Into<SharedString>,
4285 icon: IconName,
4286 window: &mut Window,
4287 cx: &mut Context<Self>,
4288 ) {
4289 if window.is_window_active() || !self.notifications.is_empty() {
4290 return;
4291 }
4292
4293 // TODO: Change this once we have title summarization for external agents.
4294 let title = self.agent.name();
4295
4296 match AgentSettings::get_global(cx).notify_when_agent_waiting {
4297 NotifyWhenAgentWaiting::PrimaryScreen => {
4298 if let Some(primary) = cx.primary_display() {
4299 self.pop_up(icon, caption.into(), title, window, primary, cx);
4300 }
4301 }
4302 NotifyWhenAgentWaiting::AllScreens => {
4303 let caption = caption.into();
4304 for screen in cx.displays() {
4305 self.pop_up(icon, caption.clone(), title.clone(), window, screen, cx);
4306 }
4307 }
4308 NotifyWhenAgentWaiting::Never => {
4309 // Don't show anything
4310 }
4311 }
4312 }
4313
4314 fn pop_up(
4315 &mut self,
4316 icon: IconName,
4317 caption: SharedString,
4318 title: SharedString,
4319 window: &mut Window,
4320 screen: Rc<dyn PlatformDisplay>,
4321 cx: &mut Context<Self>,
4322 ) {
4323 let options = AgentNotification::window_options(screen, cx);
4324
4325 let project_name = self.workspace.upgrade().and_then(|workspace| {
4326 workspace
4327 .read(cx)
4328 .project()
4329 .read(cx)
4330 .visible_worktrees(cx)
4331 .next()
4332 .map(|worktree| worktree.read(cx).root_name().to_string())
4333 });
4334
4335 if let Some(screen_window) = cx
4336 .open_window(options, |_, cx| {
4337 cx.new(|_| {
4338 AgentNotification::new(title.clone(), caption.clone(), icon, project_name)
4339 })
4340 })
4341 .log_err()
4342 && let Some(pop_up) = screen_window.entity(cx).log_err()
4343 {
4344 self.notification_subscriptions
4345 .entry(screen_window)
4346 .or_insert_with(Vec::new)
4347 .push(cx.subscribe_in(&pop_up, window, {
4348 |this, _, event, window, cx| match event {
4349 AgentNotificationEvent::Accepted => {
4350 let handle = window.window_handle();
4351 cx.activate(true);
4352
4353 let workspace_handle = this.workspace.clone();
4354
4355 // If there are multiple Zed windows, activate the correct one.
4356 cx.defer(move |cx| {
4357 handle
4358 .update(cx, |_view, window, _cx| {
4359 window.activate_window();
4360
4361 if let Some(workspace) = workspace_handle.upgrade() {
4362 workspace.update(_cx, |workspace, cx| {
4363 workspace.focus_panel::<AgentPanel>(window, cx);
4364 });
4365 }
4366 })
4367 .log_err();
4368 });
4369
4370 this.dismiss_notifications(cx);
4371 }
4372 AgentNotificationEvent::Dismissed => {
4373 this.dismiss_notifications(cx);
4374 }
4375 }
4376 }));
4377
4378 self.notifications.push(screen_window);
4379
4380 // If the user manually refocuses the original window, dismiss the popup.
4381 self.notification_subscriptions
4382 .entry(screen_window)
4383 .or_insert_with(Vec::new)
4384 .push({
4385 let pop_up_weak = pop_up.downgrade();
4386
4387 cx.observe_window_activation(window, move |_, window, cx| {
4388 if window.is_window_active()
4389 && let Some(pop_up) = pop_up_weak.upgrade()
4390 {
4391 pop_up.update(cx, |_, cx| {
4392 cx.emit(AgentNotificationEvent::Dismissed);
4393 });
4394 }
4395 })
4396 });
4397 }
4398 }
4399
4400 fn dismiss_notifications(&mut self, cx: &mut Context<Self>) {
4401 for window in self.notifications.drain(..) {
4402 window
4403 .update(cx, |_, window, _| {
4404 window.remove_window();
4405 })
4406 .ok();
4407
4408 self.notification_subscriptions.remove(&window);
4409 }
4410 }
4411
4412 fn render_thread_controls(
4413 &self,
4414 thread: &Entity<AcpThread>,
4415 cx: &Context<Self>,
4416 ) -> impl IntoElement {
4417 let is_generating = matches!(thread.read(cx).status(), ThreadStatus::Generating);
4418 if is_generating {
4419 return h_flex().id("thread-controls-container").child(
4420 div()
4421 .py_2()
4422 .px(rems_from_px(22.))
4423 .child(SpinnerLabel::new().size(LabelSize::Small)),
4424 );
4425 }
4426
4427 let open_as_markdown = IconButton::new("open-as-markdown", IconName::FileMarkdown)
4428 .shape(ui::IconButtonShape::Square)
4429 .icon_size(IconSize::Small)
4430 .icon_color(Color::Ignored)
4431 .tooltip(Tooltip::text("Open Thread as Markdown"))
4432 .on_click(cx.listener(move |this, _, window, cx| {
4433 if let Some(workspace) = this.workspace.upgrade() {
4434 this.open_thread_as_markdown(workspace, window, cx)
4435 .detach_and_log_err(cx);
4436 }
4437 }));
4438
4439 let scroll_to_top = IconButton::new("scroll_to_top", IconName::ArrowUp)
4440 .shape(ui::IconButtonShape::Square)
4441 .icon_size(IconSize::Small)
4442 .icon_color(Color::Ignored)
4443 .tooltip(Tooltip::text("Scroll To Top"))
4444 .on_click(cx.listener(move |this, _, _, cx| {
4445 this.scroll_to_top(cx);
4446 }));
4447
4448 let mut container = h_flex()
4449 .id("thread-controls-container")
4450 .group("thread-controls-container")
4451 .w_full()
4452 .py_2()
4453 .px_5()
4454 .gap_px()
4455 .opacity(0.6)
4456 .hover(|style| style.opacity(1.))
4457 .flex_wrap()
4458 .justify_end();
4459
4460 if AgentSettings::get_global(cx).enable_feedback
4461 && self
4462 .thread()
4463 .is_some_and(|thread| thread.read(cx).connection().telemetry().is_some())
4464 {
4465 let feedback = self.thread_feedback.feedback;
4466
4467 container = container
4468 .child(
4469 div().visible_on_hover("thread-controls-container").child(
4470 Label::new(match feedback {
4471 Some(ThreadFeedback::Positive) => "Thanks for your feedback!",
4472 Some(ThreadFeedback::Negative) => {
4473 "We appreciate your feedback and will use it to improve."
4474 }
4475 None => {
4476 "Rating the thread sends all of your current conversation to the Zed team."
4477 }
4478 })
4479 .color(Color::Muted)
4480 .size(LabelSize::XSmall)
4481 .truncate(),
4482 ),
4483 )
4484 .child(
4485 IconButton::new("feedback-thumbs-up", IconName::ThumbsUp)
4486 .shape(ui::IconButtonShape::Square)
4487 .icon_size(IconSize::Small)
4488 .icon_color(match feedback {
4489 Some(ThreadFeedback::Positive) => Color::Accent,
4490 _ => Color::Ignored,
4491 })
4492 .tooltip(Tooltip::text("Helpful Response"))
4493 .on_click(cx.listener(move |this, _, window, cx| {
4494 this.handle_feedback_click(ThreadFeedback::Positive, window, cx);
4495 })),
4496 )
4497 .child(
4498 IconButton::new("feedback-thumbs-down", IconName::ThumbsDown)
4499 .shape(ui::IconButtonShape::Square)
4500 .icon_size(IconSize::Small)
4501 .icon_color(match feedback {
4502 Some(ThreadFeedback::Negative) => Color::Accent,
4503 _ => Color::Ignored,
4504 })
4505 .tooltip(Tooltip::text("Not Helpful"))
4506 .on_click(cx.listener(move |this, _, window, cx| {
4507 this.handle_feedback_click(ThreadFeedback::Negative, window, cx);
4508 })),
4509 );
4510 }
4511
4512 container.child(open_as_markdown).child(scroll_to_top)
4513 }
4514
4515 fn render_feedback_feedback_editor(editor: Entity<Editor>, cx: &Context<Self>) -> Div {
4516 h_flex()
4517 .key_context("AgentFeedbackMessageEditor")
4518 .on_action(cx.listener(move |this, _: &menu::Cancel, _, cx| {
4519 this.thread_feedback.dismiss_comments();
4520 cx.notify();
4521 }))
4522 .on_action(cx.listener(move |this, _: &menu::Confirm, _window, cx| {
4523 this.submit_feedback_message(cx);
4524 }))
4525 .p_2()
4526 .mb_2()
4527 .mx_5()
4528 .gap_1()
4529 .rounded_md()
4530 .border_1()
4531 .border_color(cx.theme().colors().border)
4532 .bg(cx.theme().colors().editor_background)
4533 .child(div().w_full().child(editor))
4534 .child(
4535 h_flex()
4536 .child(
4537 IconButton::new("dismiss-feedback-message", IconName::Close)
4538 .icon_color(Color::Error)
4539 .icon_size(IconSize::XSmall)
4540 .shape(ui::IconButtonShape::Square)
4541 .on_click(cx.listener(move |this, _, _window, cx| {
4542 this.thread_feedback.dismiss_comments();
4543 cx.notify();
4544 })),
4545 )
4546 .child(
4547 IconButton::new("submit-feedback-message", IconName::Return)
4548 .icon_size(IconSize::XSmall)
4549 .shape(ui::IconButtonShape::Square)
4550 .on_click(cx.listener(move |this, _, _window, cx| {
4551 this.submit_feedback_message(cx);
4552 })),
4553 ),
4554 )
4555 }
4556
4557 fn handle_feedback_click(
4558 &mut self,
4559 feedback: ThreadFeedback,
4560 window: &mut Window,
4561 cx: &mut Context<Self>,
4562 ) {
4563 let Some(thread) = self.thread().cloned() else {
4564 return;
4565 };
4566
4567 self.thread_feedback.submit(thread, feedback, window, cx);
4568 cx.notify();
4569 }
4570
4571 fn submit_feedback_message(&mut self, cx: &mut Context<Self>) {
4572 let Some(thread) = self.thread().cloned() else {
4573 return;
4574 };
4575
4576 self.thread_feedback.submit_comments(thread, cx);
4577 cx.notify();
4578 }
4579
4580 fn render_vertical_scrollbar(&self, cx: &mut Context<Self>) -> Stateful<Div> {
4581 div()
4582 .id("acp-thread-scrollbar")
4583 .occlude()
4584 .on_mouse_move(cx.listener(|_, _, _, cx| {
4585 cx.notify();
4586 cx.stop_propagation()
4587 }))
4588 .on_hover(|_, _, cx| {
4589 cx.stop_propagation();
4590 })
4591 .on_any_mouse_down(|_, _, cx| {
4592 cx.stop_propagation();
4593 })
4594 .on_mouse_up(
4595 MouseButton::Left,
4596 cx.listener(|_, _, _, cx| {
4597 cx.stop_propagation();
4598 }),
4599 )
4600 .on_scroll_wheel(cx.listener(|_, _, _, cx| {
4601 cx.notify();
4602 }))
4603 .h_full()
4604 .absolute()
4605 .right_1()
4606 .top_1()
4607 .bottom_0()
4608 .w(px(12.))
4609 .cursor_default()
4610 .children(Scrollbar::vertical(self.scrollbar_state.clone()).map(|s| s.auto_hide(cx)))
4611 }
4612
4613 fn render_token_limit_callout(
4614 &self,
4615 line_height: Pixels,
4616 cx: &mut Context<Self>,
4617 ) -> Option<Callout> {
4618 let token_usage = self.thread()?.read(cx).token_usage()?;
4619 let ratio = token_usage.ratio();
4620
4621 let (severity, title) = match ratio {
4622 acp_thread::TokenUsageRatio::Normal => return None,
4623 acp_thread::TokenUsageRatio::Warning => {
4624 (Severity::Warning, "Thread reaching the token limit soon")
4625 }
4626 acp_thread::TokenUsageRatio::Exceeded => {
4627 (Severity::Error, "Thread reached the token limit")
4628 }
4629 };
4630
4631 let burn_mode_available = self.as_native_thread(cx).is_some_and(|thread| {
4632 thread.read(cx).completion_mode() == CompletionMode::Normal
4633 && thread
4634 .read(cx)
4635 .model()
4636 .is_some_and(|model| model.supports_burn_mode())
4637 });
4638
4639 let description = if burn_mode_available {
4640 "To continue, start a new thread from a summary or turn Burn Mode on."
4641 } else {
4642 "To continue, start a new thread from a summary."
4643 };
4644
4645 Some(
4646 Callout::new()
4647 .severity(severity)
4648 .line_height(line_height)
4649 .title(title)
4650 .description(description)
4651 .actions_slot(
4652 h_flex()
4653 .gap_0p5()
4654 .child(
4655 Button::new("start-new-thread", "Start New Thread")
4656 .label_size(LabelSize::Small)
4657 .on_click(cx.listener(|this, _, window, cx| {
4658 let Some(thread) = this.thread() else {
4659 return;
4660 };
4661 let session_id = thread.read(cx).session_id().clone();
4662 window.dispatch_action(
4663 crate::NewNativeAgentThreadFromSummary {
4664 from_session_id: session_id,
4665 }
4666 .boxed_clone(),
4667 cx,
4668 );
4669 })),
4670 )
4671 .when(burn_mode_available, |this| {
4672 this.child(
4673 IconButton::new("burn-mode-callout", IconName::ZedBurnMode)
4674 .icon_size(IconSize::XSmall)
4675 .on_click(cx.listener(|this, _event, window, cx| {
4676 this.toggle_burn_mode(&ToggleBurnMode, window, cx);
4677 })),
4678 )
4679 }),
4680 ),
4681 )
4682 }
4683
4684 fn render_usage_callout(&self, line_height: Pixels, cx: &mut Context<Self>) -> Option<Div> {
4685 if !self.is_using_zed_ai_models(cx) {
4686 return None;
4687 }
4688
4689 let user_store = self.project.read(cx).user_store().read(cx);
4690 if user_store.is_usage_based_billing_enabled() {
4691 return None;
4692 }
4693
4694 let plan = user_store.plan().unwrap_or(cloud_llm_client::Plan::ZedFree);
4695
4696 let usage = user_store.model_request_usage()?;
4697
4698 Some(
4699 div()
4700 .child(UsageCallout::new(plan, usage))
4701 .line_height(line_height),
4702 )
4703 }
4704
4705 fn settings_changed(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
4706 self.entry_view_state.update(cx, |entry_view_state, cx| {
4707 entry_view_state.settings_changed(cx);
4708 });
4709 }
4710
4711 pub(crate) fn insert_dragged_files(
4712 &self,
4713 paths: Vec<project::ProjectPath>,
4714 added_worktrees: Vec<Entity<project::Worktree>>,
4715 window: &mut Window,
4716 cx: &mut Context<Self>,
4717 ) {
4718 self.message_editor.update(cx, |message_editor, cx| {
4719 message_editor.insert_dragged_files(paths, added_worktrees, window, cx);
4720 })
4721 }
4722
4723 pub(crate) fn insert_selections(&self, window: &mut Window, cx: &mut Context<Self>) {
4724 self.message_editor.update(cx, |message_editor, cx| {
4725 message_editor.insert_selections(window, cx);
4726 })
4727 }
4728
4729 fn render_thread_retry_status_callout(
4730 &self,
4731 _window: &mut Window,
4732 _cx: &mut Context<Self>,
4733 ) -> Option<Callout> {
4734 let state = self.thread_retry_status.as_ref()?;
4735
4736 let next_attempt_in = state
4737 .duration
4738 .saturating_sub(Instant::now().saturating_duration_since(state.started_at));
4739 if next_attempt_in.is_zero() {
4740 return None;
4741 }
4742
4743 let next_attempt_in_secs = next_attempt_in.as_secs() + 1;
4744
4745 let retry_message = if state.max_attempts == 1 {
4746 if next_attempt_in_secs == 1 {
4747 "Retrying. Next attempt in 1 second.".to_string()
4748 } else {
4749 format!("Retrying. Next attempt in {next_attempt_in_secs} seconds.")
4750 }
4751 } else if next_attempt_in_secs == 1 {
4752 format!(
4753 "Retrying. Next attempt in 1 second (Attempt {} of {}).",
4754 state.attempt, state.max_attempts,
4755 )
4756 } else {
4757 format!(
4758 "Retrying. Next attempt in {next_attempt_in_secs} seconds (Attempt {} of {}).",
4759 state.attempt, state.max_attempts,
4760 )
4761 };
4762
4763 Some(
4764 Callout::new()
4765 .severity(Severity::Warning)
4766 .title(state.last_error.clone())
4767 .description(retry_message),
4768 )
4769 }
4770
4771 fn render_thread_error(&self, window: &mut Window, cx: &mut Context<Self>) -> Option<Div> {
4772 let content = match self.thread_error.as_ref()? {
4773 ThreadError::Other(error) => self.render_any_thread_error(error.clone(), cx),
4774 ThreadError::Refusal => self.render_refusal_error(cx),
4775 ThreadError::AuthenticationRequired(error) => {
4776 self.render_authentication_required_error(error.clone(), cx)
4777 }
4778 ThreadError::PaymentRequired => self.render_payment_required_error(cx),
4779 ThreadError::ModelRequestLimitReached(plan) => {
4780 self.render_model_request_limit_reached_error(*plan, cx)
4781 }
4782 ThreadError::ToolUseLimitReached => {
4783 self.render_tool_use_limit_reached_error(window, cx)?
4784 }
4785 };
4786
4787 Some(div().child(content))
4788 }
4789
4790 fn get_current_model_name(&self, cx: &App) -> SharedString {
4791 // For native agent (Zed Agent), use the specific model name (e.g., "Claude 3.5 Sonnet")
4792 // For ACP agents, use the agent name (e.g., "Claude Code", "Gemini CLI")
4793 // This provides better clarity about what refused the request
4794 if self
4795 .agent
4796 .clone()
4797 .downcast::<agent2::NativeAgentServer>()
4798 .is_some()
4799 {
4800 // Native agent - use the model name
4801 self.model_selector
4802 .as_ref()
4803 .and_then(|selector| selector.read(cx).active_model_name(cx))
4804 .unwrap_or_else(|| SharedString::from("The model"))
4805 } else {
4806 // ACP agent - use the agent name (e.g., "Claude Code", "Gemini CLI")
4807 self.agent.name()
4808 }
4809 }
4810
4811 fn render_refusal_error(&self, cx: &mut Context<'_, Self>) -> Callout {
4812 let model_or_agent_name = self.get_current_model_name(cx);
4813 let refusal_message = format!(
4814 "{} 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.",
4815 model_or_agent_name
4816 );
4817
4818 Callout::new()
4819 .severity(Severity::Error)
4820 .title("Request Refused")
4821 .icon(IconName::XCircle)
4822 .description(refusal_message.clone())
4823 .actions_slot(self.create_copy_button(&refusal_message))
4824 .dismiss_action(self.dismiss_error_button(cx))
4825 }
4826
4827 fn render_any_thread_error(&self, error: SharedString, cx: &mut Context<'_, Self>) -> Callout {
4828 let can_resume = self
4829 .thread()
4830 .map_or(false, |thread| thread.read(cx).can_resume(cx));
4831
4832 let can_enable_burn_mode = self.as_native_thread(cx).map_or(false, |thread| {
4833 let thread = thread.read(cx);
4834 let supports_burn_mode = thread
4835 .model()
4836 .map_or(false, |model| model.supports_burn_mode());
4837 supports_burn_mode && thread.completion_mode() == CompletionMode::Normal
4838 });
4839
4840 Callout::new()
4841 .severity(Severity::Error)
4842 .title("Error")
4843 .icon(IconName::XCircle)
4844 .description(error.clone())
4845 .actions_slot(
4846 h_flex()
4847 .gap_0p5()
4848 .when(can_resume && can_enable_burn_mode, |this| {
4849 this.child(
4850 Button::new("enable-burn-mode-and-retry", "Enable Burn Mode and Retry")
4851 .icon(IconName::ZedBurnMode)
4852 .icon_position(IconPosition::Start)
4853 .icon_size(IconSize::Small)
4854 .label_size(LabelSize::Small)
4855 .on_click(cx.listener(|this, _, window, cx| {
4856 this.toggle_burn_mode(&ToggleBurnMode, window, cx);
4857 this.resume_chat(cx);
4858 })),
4859 )
4860 })
4861 .when(can_resume, |this| {
4862 this.child(
4863 Button::new("retry", "Retry")
4864 .icon(IconName::RotateCw)
4865 .icon_position(IconPosition::Start)
4866 .icon_size(IconSize::Small)
4867 .label_size(LabelSize::Small)
4868 .on_click(cx.listener(|this, _, _window, cx| {
4869 this.resume_chat(cx);
4870 })),
4871 )
4872 })
4873 .child(self.create_copy_button(error.to_string())),
4874 )
4875 .dismiss_action(self.dismiss_error_button(cx))
4876 }
4877
4878 fn render_payment_required_error(&self, cx: &mut Context<Self>) -> Callout {
4879 const ERROR_MESSAGE: &str =
4880 "You reached your free usage limit. Upgrade to Zed Pro for more prompts.";
4881
4882 Callout::new()
4883 .severity(Severity::Error)
4884 .icon(IconName::XCircle)
4885 .title("Free Usage Exceeded")
4886 .description(ERROR_MESSAGE)
4887 .actions_slot(
4888 h_flex()
4889 .gap_0p5()
4890 .child(self.upgrade_button(cx))
4891 .child(self.create_copy_button(ERROR_MESSAGE)),
4892 )
4893 .dismiss_action(self.dismiss_error_button(cx))
4894 }
4895
4896 fn render_authentication_required_error(
4897 &self,
4898 error: SharedString,
4899 cx: &mut Context<Self>,
4900 ) -> Callout {
4901 Callout::new()
4902 .severity(Severity::Error)
4903 .title("Authentication Required")
4904 .icon(IconName::XCircle)
4905 .description(error.clone())
4906 .actions_slot(
4907 h_flex()
4908 .gap_0p5()
4909 .child(self.authenticate_button(cx))
4910 .child(self.create_copy_button(error)),
4911 )
4912 .dismiss_action(self.dismiss_error_button(cx))
4913 }
4914
4915 fn render_model_request_limit_reached_error(
4916 &self,
4917 plan: cloud_llm_client::Plan,
4918 cx: &mut Context<Self>,
4919 ) -> Callout {
4920 let error_message = match plan {
4921 cloud_llm_client::Plan::ZedPro => "Upgrade to usage-based billing for more prompts.",
4922 cloud_llm_client::Plan::ZedProTrial | cloud_llm_client::Plan::ZedFree => {
4923 "Upgrade to Zed Pro for more prompts."
4924 }
4925 };
4926
4927 Callout::new()
4928 .severity(Severity::Error)
4929 .title("Model Prompt Limit Reached")
4930 .icon(IconName::XCircle)
4931 .description(error_message)
4932 .actions_slot(
4933 h_flex()
4934 .gap_0p5()
4935 .child(self.upgrade_button(cx))
4936 .child(self.create_copy_button(error_message)),
4937 )
4938 .dismiss_action(self.dismiss_error_button(cx))
4939 }
4940
4941 fn render_tool_use_limit_reached_error(
4942 &self,
4943 window: &mut Window,
4944 cx: &mut Context<Self>,
4945 ) -> Option<Callout> {
4946 let thread = self.as_native_thread(cx)?;
4947 let supports_burn_mode = thread
4948 .read(cx)
4949 .model()
4950 .is_some_and(|model| model.supports_burn_mode());
4951
4952 let focus_handle = self.focus_handle(cx);
4953
4954 Some(
4955 Callout::new()
4956 .icon(IconName::Info)
4957 .title("Consecutive tool use limit reached.")
4958 .actions_slot(
4959 h_flex()
4960 .gap_0p5()
4961 .when(supports_burn_mode, |this| {
4962 this.child(
4963 Button::new("continue-burn-mode", "Continue with Burn Mode")
4964 .style(ButtonStyle::Filled)
4965 .style(ButtonStyle::Tinted(ui::TintColor::Accent))
4966 .layer(ElevationIndex::ModalSurface)
4967 .label_size(LabelSize::Small)
4968 .key_binding(
4969 KeyBinding::for_action_in(
4970 &ContinueWithBurnMode,
4971 &focus_handle,
4972 window,
4973 cx,
4974 )
4975 .map(|kb| kb.size(rems_from_px(10.))),
4976 )
4977 .tooltip(Tooltip::text(
4978 "Enable Burn Mode for unlimited tool use.",
4979 ))
4980 .on_click({
4981 cx.listener(move |this, _, _window, cx| {
4982 thread.update(cx, |thread, cx| {
4983 thread
4984 .set_completion_mode(CompletionMode::Burn, cx);
4985 });
4986 this.resume_chat(cx);
4987 })
4988 }),
4989 )
4990 })
4991 .child(
4992 Button::new("continue-conversation", "Continue")
4993 .layer(ElevationIndex::ModalSurface)
4994 .label_size(LabelSize::Small)
4995 .key_binding(
4996 KeyBinding::for_action_in(
4997 &ContinueThread,
4998 &focus_handle,
4999 window,
5000 cx,
5001 )
5002 .map(|kb| kb.size(rems_from_px(10.))),
5003 )
5004 .on_click(cx.listener(|this, _, _window, cx| {
5005 this.resume_chat(cx);
5006 })),
5007 ),
5008 ),
5009 )
5010 }
5011
5012 fn create_copy_button(&self, message: impl Into<String>) -> impl IntoElement {
5013 let message = message.into();
5014
5015 IconButton::new("copy", IconName::Copy)
5016 .icon_size(IconSize::Small)
5017 .icon_color(Color::Muted)
5018 .tooltip(Tooltip::text("Copy Error Message"))
5019 .on_click(move |_, _, cx| {
5020 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
5021 })
5022 }
5023
5024 fn dismiss_error_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
5025 IconButton::new("dismiss", IconName::Close)
5026 .icon_size(IconSize::Small)
5027 .icon_color(Color::Muted)
5028 .tooltip(Tooltip::text("Dismiss Error"))
5029 .on_click(cx.listener({
5030 move |this, _, _, cx| {
5031 this.clear_thread_error(cx);
5032 cx.notify();
5033 }
5034 }))
5035 }
5036
5037 fn authenticate_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
5038 Button::new("authenticate", "Authenticate")
5039 .label_size(LabelSize::Small)
5040 .style(ButtonStyle::Filled)
5041 .on_click(cx.listener({
5042 move |this, _, window, cx| {
5043 let agent = this.agent.clone();
5044 let ThreadState::Ready { thread, .. } = &this.thread_state else {
5045 return;
5046 };
5047
5048 let connection = thread.read(cx).connection().clone();
5049 let err = AuthRequired {
5050 description: None,
5051 provider_id: None,
5052 };
5053 this.clear_thread_error(cx);
5054 let this = cx.weak_entity();
5055 window.defer(cx, |window, cx| {
5056 Self::handle_auth_required(this, err, agent, connection, window, cx);
5057 })
5058 }
5059 }))
5060 }
5061
5062 pub(crate) fn reauthenticate(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5063 let agent = self.agent.clone();
5064 let ThreadState::Ready { thread, .. } = &self.thread_state else {
5065 return;
5066 };
5067
5068 let connection = thread.read(cx).connection().clone();
5069 let err = AuthRequired {
5070 description: None,
5071 provider_id: None,
5072 };
5073 self.clear_thread_error(cx);
5074 let this = cx.weak_entity();
5075 window.defer(cx, |window, cx| {
5076 Self::handle_auth_required(this, err, agent, connection, window, cx);
5077 })
5078 }
5079
5080 fn upgrade_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
5081 Button::new("upgrade", "Upgrade")
5082 .label_size(LabelSize::Small)
5083 .style(ButtonStyle::Tinted(ui::TintColor::Accent))
5084 .on_click(cx.listener({
5085 move |this, _, _, cx| {
5086 this.clear_thread_error(cx);
5087 cx.open_url(&zed_urls::upgrade_to_zed_pro_url(cx));
5088 }
5089 }))
5090 }
5091
5092 pub fn delete_history_entry(&mut self, entry: HistoryEntry, cx: &mut Context<Self>) {
5093 let task = match entry {
5094 HistoryEntry::AcpThread(thread) => self.history_store.update(cx, |history, cx| {
5095 history.delete_thread(thread.id.clone(), cx)
5096 }),
5097 HistoryEntry::TextThread(context) => self.history_store.update(cx, |history, cx| {
5098 history.delete_text_thread(context.path.clone(), cx)
5099 }),
5100 };
5101 task.detach_and_log_err(cx);
5102 }
5103}
5104
5105fn loading_contents_spinner(size: IconSize) -> AnyElement {
5106 Icon::new(IconName::LoadCircle)
5107 .size(size)
5108 .color(Color::Accent)
5109 .with_animation(
5110 "load_context_circle",
5111 Animation::new(Duration::from_secs(3)).repeat(),
5112 |icon, delta| icon.transform(Transformation::rotate(percentage(delta))),
5113 )
5114 .into_any_element()
5115}
5116
5117impl Focusable for AcpThreadView {
5118 fn focus_handle(&self, cx: &App) -> FocusHandle {
5119 match self.thread_state {
5120 ThreadState::Loading { .. } | ThreadState::Ready { .. } => {
5121 self.message_editor.focus_handle(cx)
5122 }
5123 ThreadState::LoadError(_) | ThreadState::Unauthenticated { .. } => {
5124 self.focus_handle.clone()
5125 }
5126 }
5127 }
5128}
5129
5130impl Render for AcpThreadView {
5131 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
5132 let has_messages = self.list_state.item_count() > 0;
5133 let line_height = TextSize::Small.rems(cx).to_pixels(window.rem_size()) * 1.5;
5134
5135 v_flex()
5136 .size_full()
5137 .key_context("AcpThread")
5138 .on_action(cx.listener(Self::open_agent_diff))
5139 .on_action(cx.listener(Self::toggle_burn_mode))
5140 .on_action(cx.listener(Self::keep_all))
5141 .on_action(cx.listener(Self::reject_all))
5142 .track_focus(&self.focus_handle)
5143 .bg(cx.theme().colors().panel_background)
5144 .child(match &self.thread_state {
5145 ThreadState::Unauthenticated {
5146 connection,
5147 description,
5148 configuration_view,
5149 pending_auth_method,
5150 ..
5151 } => self.render_auth_required_state(
5152 connection,
5153 description.as_ref(),
5154 configuration_view.as_ref(),
5155 pending_auth_method.as_ref(),
5156 window,
5157 cx,
5158 ),
5159 ThreadState::Loading { .. } => v_flex()
5160 .flex_1()
5161 .child(self.render_recent_history(window, cx)),
5162 ThreadState::LoadError(e) => v_flex()
5163 .flex_1()
5164 .size_full()
5165 .items_center()
5166 .justify_end()
5167 .child(self.render_load_error(e, window, cx)),
5168 ThreadState::Ready { .. } => v_flex().flex_1().map(|this| {
5169 if has_messages {
5170 this.child(
5171 list(
5172 self.list_state.clone(),
5173 cx.processor(|this, index: usize, window, cx| {
5174 let Some((entry, len)) = this.thread().and_then(|thread| {
5175 let entries = &thread.read(cx).entries();
5176 Some((entries.get(index)?, entries.len()))
5177 }) else {
5178 return Empty.into_any();
5179 };
5180 this.render_entry(index, len, entry, window, cx)
5181 }),
5182 )
5183 .with_sizing_behavior(gpui::ListSizingBehavior::Auto)
5184 .flex_grow()
5185 .into_any(),
5186 )
5187 .child(self.render_vertical_scrollbar(cx))
5188 } else {
5189 this.child(self.render_recent_history(window, cx))
5190 }
5191 }),
5192 })
5193 // The activity bar is intentionally rendered outside of the ThreadState::Ready match
5194 // above so that the scrollbar doesn't render behind it. The current setup allows
5195 // the scrollbar to stop exactly at the activity bar start.
5196 .when(has_messages, |this| match &self.thread_state {
5197 ThreadState::Ready { thread, .. } => {
5198 this.children(self.render_activity_bar(thread, window, cx))
5199 }
5200 _ => this,
5201 })
5202 .children(self.render_thread_retry_status_callout(window, cx))
5203 .children(self.render_thread_error(window, cx))
5204 .children(
5205 if let Some(usage_callout) = self.render_usage_callout(line_height, cx) {
5206 Some(usage_callout.into_any_element())
5207 } else {
5208 self.render_token_limit_callout(line_height, cx)
5209 .map(|token_limit_callout| token_limit_callout.into_any_element())
5210 },
5211 )
5212 .child(self.render_message_editor(window, cx))
5213 }
5214}
5215
5216fn default_markdown_style(
5217 buffer_font: bool,
5218 muted_text: bool,
5219 window: &Window,
5220 cx: &App,
5221) -> MarkdownStyle {
5222 let theme_settings = ThemeSettings::get_global(cx);
5223 let colors = cx.theme().colors();
5224
5225 let buffer_font_size = TextSize::Small.rems(cx);
5226
5227 let mut text_style = window.text_style();
5228 let line_height = buffer_font_size * 1.75;
5229
5230 let font_family = if buffer_font {
5231 theme_settings.buffer_font.family.clone()
5232 } else {
5233 theme_settings.ui_font.family.clone()
5234 };
5235
5236 let font_size = if buffer_font {
5237 TextSize::Small.rems(cx)
5238 } else {
5239 TextSize::Default.rems(cx)
5240 };
5241
5242 let text_color = if muted_text {
5243 colors.text_muted
5244 } else {
5245 colors.text
5246 };
5247
5248 text_style.refine(&TextStyleRefinement {
5249 font_family: Some(font_family),
5250 font_fallbacks: theme_settings.ui_font.fallbacks.clone(),
5251 font_features: Some(theme_settings.ui_font.features.clone()),
5252 font_size: Some(font_size.into()),
5253 line_height: Some(line_height.into()),
5254 color: Some(text_color),
5255 ..Default::default()
5256 });
5257
5258 MarkdownStyle {
5259 base_text_style: text_style.clone(),
5260 syntax: cx.theme().syntax().clone(),
5261 selection_background_color: colors.element_selection_background,
5262 code_block_overflow_x_scroll: true,
5263 table_overflow_x_scroll: true,
5264 heading_level_styles: Some(HeadingLevelStyles {
5265 h1: Some(TextStyleRefinement {
5266 font_size: Some(rems(1.15).into()),
5267 ..Default::default()
5268 }),
5269 h2: Some(TextStyleRefinement {
5270 font_size: Some(rems(1.1).into()),
5271 ..Default::default()
5272 }),
5273 h3: Some(TextStyleRefinement {
5274 font_size: Some(rems(1.05).into()),
5275 ..Default::default()
5276 }),
5277 h4: Some(TextStyleRefinement {
5278 font_size: Some(rems(1.).into()),
5279 ..Default::default()
5280 }),
5281 h5: Some(TextStyleRefinement {
5282 font_size: Some(rems(0.95).into()),
5283 ..Default::default()
5284 }),
5285 h6: Some(TextStyleRefinement {
5286 font_size: Some(rems(0.875).into()),
5287 ..Default::default()
5288 }),
5289 }),
5290 code_block: StyleRefinement {
5291 padding: EdgesRefinement {
5292 top: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
5293 left: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
5294 right: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
5295 bottom: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
5296 },
5297 margin: EdgesRefinement {
5298 top: Some(Length::Definite(Pixels(8.).into())),
5299 left: Some(Length::Definite(Pixels(0.).into())),
5300 right: Some(Length::Definite(Pixels(0.).into())),
5301 bottom: Some(Length::Definite(Pixels(12.).into())),
5302 },
5303 border_style: Some(BorderStyle::Solid),
5304 border_widths: EdgesRefinement {
5305 top: Some(AbsoluteLength::Pixels(Pixels(1.))),
5306 left: Some(AbsoluteLength::Pixels(Pixels(1.))),
5307 right: Some(AbsoluteLength::Pixels(Pixels(1.))),
5308 bottom: Some(AbsoluteLength::Pixels(Pixels(1.))),
5309 },
5310 border_color: Some(colors.border_variant),
5311 background: Some(colors.editor_background.into()),
5312 text: Some(TextStyleRefinement {
5313 font_family: Some(theme_settings.buffer_font.family.clone()),
5314 font_fallbacks: theme_settings.buffer_font.fallbacks.clone(),
5315 font_features: Some(theme_settings.buffer_font.features.clone()),
5316 font_size: Some(buffer_font_size.into()),
5317 ..Default::default()
5318 }),
5319 ..Default::default()
5320 },
5321 inline_code: TextStyleRefinement {
5322 font_family: Some(theme_settings.buffer_font.family.clone()),
5323 font_fallbacks: theme_settings.buffer_font.fallbacks.clone(),
5324 font_features: Some(theme_settings.buffer_font.features.clone()),
5325 font_size: Some(buffer_font_size.into()),
5326 background_color: Some(colors.editor_foreground.opacity(0.08)),
5327 ..Default::default()
5328 },
5329 link: TextStyleRefinement {
5330 background_color: Some(colors.editor_foreground.opacity(0.025)),
5331 underline: Some(UnderlineStyle {
5332 color: Some(colors.text_accent.opacity(0.5)),
5333 thickness: px(1.),
5334 ..Default::default()
5335 }),
5336 ..Default::default()
5337 },
5338 ..Default::default()
5339 }
5340}
5341
5342fn plan_label_markdown_style(
5343 status: &acp::PlanEntryStatus,
5344 window: &Window,
5345 cx: &App,
5346) -> MarkdownStyle {
5347 let default_md_style = default_markdown_style(false, false, window, cx);
5348
5349 MarkdownStyle {
5350 base_text_style: TextStyle {
5351 color: cx.theme().colors().text_muted,
5352 strikethrough: if matches!(status, acp::PlanEntryStatus::Completed) {
5353 Some(gpui::StrikethroughStyle {
5354 thickness: px(1.),
5355 color: Some(cx.theme().colors().text_muted.opacity(0.8)),
5356 })
5357 } else {
5358 None
5359 },
5360 ..default_md_style.base_text_style
5361 },
5362 ..default_md_style
5363 }
5364}
5365
5366fn terminal_command_markdown_style(window: &Window, cx: &App) -> MarkdownStyle {
5367 let default_md_style = default_markdown_style(true, false, window, cx);
5368
5369 MarkdownStyle {
5370 base_text_style: TextStyle {
5371 ..default_md_style.base_text_style
5372 },
5373 selection_background_color: cx.theme().colors().element_selection_background,
5374 ..Default::default()
5375 }
5376}
5377
5378#[cfg(test)]
5379pub(crate) mod tests {
5380 use acp_thread::StubAgentConnection;
5381 use agent_client_protocol::SessionId;
5382 use assistant_context::ContextStore;
5383 use editor::EditorSettings;
5384 use fs::FakeFs;
5385 use gpui::{EventEmitter, SemanticVersion, TestAppContext, VisualTestContext};
5386 use project::Project;
5387 use serde_json::json;
5388 use settings::SettingsStore;
5389 use std::any::Any;
5390 use std::path::Path;
5391 use workspace::Item;
5392
5393 use super::*;
5394
5395 #[gpui::test]
5396 async fn test_drop(cx: &mut TestAppContext) {
5397 init_test(cx);
5398
5399 let (thread_view, _cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
5400 let weak_view = thread_view.downgrade();
5401 drop(thread_view);
5402 assert!(!weak_view.is_upgradable());
5403 }
5404
5405 #[gpui::test]
5406 async fn test_notification_for_stop_event(cx: &mut TestAppContext) {
5407 init_test(cx);
5408
5409 let (thread_view, cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
5410
5411 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
5412 message_editor.update_in(cx, |editor, window, cx| {
5413 editor.set_text("Hello", window, cx);
5414 });
5415
5416 cx.deactivate_window();
5417
5418 thread_view.update_in(cx, |thread_view, window, cx| {
5419 thread_view.send(window, cx);
5420 });
5421
5422 cx.run_until_parked();
5423
5424 assert!(
5425 cx.windows()
5426 .iter()
5427 .any(|window| window.downcast::<AgentNotification>().is_some())
5428 );
5429 }
5430
5431 #[gpui::test]
5432 async fn test_notification_for_error(cx: &mut TestAppContext) {
5433 init_test(cx);
5434
5435 let (thread_view, cx) =
5436 setup_thread_view(StubAgentServer::new(SaboteurAgentConnection), cx).await;
5437
5438 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
5439 message_editor.update_in(cx, |editor, window, cx| {
5440 editor.set_text("Hello", window, cx);
5441 });
5442
5443 cx.deactivate_window();
5444
5445 thread_view.update_in(cx, |thread_view, window, cx| {
5446 thread_view.send(window, cx);
5447 });
5448
5449 cx.run_until_parked();
5450
5451 assert!(
5452 cx.windows()
5453 .iter()
5454 .any(|window| window.downcast::<AgentNotification>().is_some())
5455 );
5456 }
5457
5458 #[gpui::test]
5459 async fn test_refusal_handling(cx: &mut TestAppContext) {
5460 init_test(cx);
5461
5462 let (thread_view, cx) =
5463 setup_thread_view(StubAgentServer::new(RefusalAgentConnection), cx).await;
5464
5465 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
5466 message_editor.update_in(cx, |editor, window, cx| {
5467 editor.set_text("Do something harmful", window, cx);
5468 });
5469
5470 thread_view.update_in(cx, |thread_view, window, cx| {
5471 thread_view.send(window, cx);
5472 });
5473
5474 cx.run_until_parked();
5475
5476 // Check that the refusal error is set
5477 thread_view.read_with(cx, |thread_view, _cx| {
5478 assert!(
5479 matches!(thread_view.thread_error, Some(ThreadError::Refusal)),
5480 "Expected refusal error to be set"
5481 );
5482 });
5483 }
5484
5485 #[gpui::test]
5486 async fn test_notification_for_tool_authorization(cx: &mut TestAppContext) {
5487 init_test(cx);
5488
5489 let tool_call_id = acp::ToolCallId("1".into());
5490 let tool_call = acp::ToolCall {
5491 id: tool_call_id.clone(),
5492 title: "Label".into(),
5493 kind: acp::ToolKind::Edit,
5494 status: acp::ToolCallStatus::Pending,
5495 content: vec!["hi".into()],
5496 locations: vec![],
5497 raw_input: None,
5498 raw_output: None,
5499 };
5500 let connection =
5501 StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
5502 tool_call_id,
5503 vec![acp::PermissionOption {
5504 id: acp::PermissionOptionId("1".into()),
5505 name: "Allow".into(),
5506 kind: acp::PermissionOptionKind::AllowOnce,
5507 }],
5508 )]));
5509
5510 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
5511
5512 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
5513
5514 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
5515 message_editor.update_in(cx, |editor, window, cx| {
5516 editor.set_text("Hello", window, cx);
5517 });
5518
5519 cx.deactivate_window();
5520
5521 thread_view.update_in(cx, |thread_view, window, cx| {
5522 thread_view.send(window, cx);
5523 });
5524
5525 cx.run_until_parked();
5526
5527 assert!(
5528 cx.windows()
5529 .iter()
5530 .any(|window| window.downcast::<AgentNotification>().is_some())
5531 );
5532 }
5533
5534 async fn setup_thread_view(
5535 agent: impl AgentServer + 'static,
5536 cx: &mut TestAppContext,
5537 ) -> (Entity<AcpThreadView>, &mut VisualTestContext) {
5538 let fs = FakeFs::new(cx.executor());
5539 let project = Project::test(fs, [], cx).await;
5540 let (workspace, cx) =
5541 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5542
5543 let context_store =
5544 cx.update(|_window, cx| cx.new(|cx| ContextStore::fake(project.clone(), cx)));
5545 let history_store =
5546 cx.update(|_window, cx| cx.new(|cx| HistoryStore::new(context_store, cx)));
5547
5548 let thread_view = cx.update(|window, cx| {
5549 cx.new(|cx| {
5550 AcpThreadView::new(
5551 Rc::new(agent),
5552 None,
5553 None,
5554 workspace.downgrade(),
5555 project,
5556 history_store,
5557 None,
5558 window,
5559 cx,
5560 )
5561 })
5562 });
5563 cx.run_until_parked();
5564 (thread_view, cx)
5565 }
5566
5567 fn add_to_workspace(thread_view: Entity<AcpThreadView>, cx: &mut VisualTestContext) {
5568 let workspace = thread_view.read_with(cx, |thread_view, _cx| thread_view.workspace.clone());
5569
5570 workspace
5571 .update_in(cx, |workspace, window, cx| {
5572 workspace.add_item_to_active_pane(
5573 Box::new(cx.new(|_| ThreadViewItem(thread_view.clone()))),
5574 None,
5575 true,
5576 window,
5577 cx,
5578 );
5579 })
5580 .unwrap();
5581 }
5582
5583 struct ThreadViewItem(Entity<AcpThreadView>);
5584
5585 impl Item for ThreadViewItem {
5586 type Event = ();
5587
5588 fn include_in_nav_history() -> bool {
5589 false
5590 }
5591
5592 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
5593 "Test".into()
5594 }
5595 }
5596
5597 impl EventEmitter<()> for ThreadViewItem {}
5598
5599 impl Focusable for ThreadViewItem {
5600 fn focus_handle(&self, cx: &App) -> FocusHandle {
5601 self.0.read(cx).focus_handle(cx)
5602 }
5603 }
5604
5605 impl Render for ThreadViewItem {
5606 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
5607 self.0.clone().into_any_element()
5608 }
5609 }
5610
5611 struct StubAgentServer<C> {
5612 connection: C,
5613 }
5614
5615 impl<C> StubAgentServer<C> {
5616 fn new(connection: C) -> Self {
5617 Self { connection }
5618 }
5619 }
5620
5621 impl StubAgentServer<StubAgentConnection> {
5622 fn default_response() -> Self {
5623 let conn = StubAgentConnection::new();
5624 conn.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk {
5625 content: "Default response".into(),
5626 }]);
5627 Self::new(conn)
5628 }
5629 }
5630
5631 impl<C> AgentServer for StubAgentServer<C>
5632 where
5633 C: 'static + AgentConnection + Send + Clone,
5634 {
5635 fn telemetry_id(&self) -> &'static str {
5636 "test"
5637 }
5638
5639 fn logo(&self) -> ui::IconName {
5640 ui::IconName::Ai
5641 }
5642
5643 fn name(&self) -> SharedString {
5644 "Test".into()
5645 }
5646
5647 fn connect(
5648 &self,
5649 _root_dir: &Path,
5650 _delegate: AgentServerDelegate,
5651 _cx: &mut App,
5652 ) -> Task<gpui::Result<Rc<dyn AgentConnection>>> {
5653 Task::ready(Ok(Rc::new(self.connection.clone())))
5654 }
5655
5656 fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
5657 self
5658 }
5659 }
5660
5661 #[derive(Clone)]
5662 struct SaboteurAgentConnection;
5663
5664 impl AgentConnection for SaboteurAgentConnection {
5665 fn new_thread(
5666 self: Rc<Self>,
5667 project: Entity<Project>,
5668 _cwd: &Path,
5669 cx: &mut gpui::App,
5670 ) -> Task<gpui::Result<Entity<AcpThread>>> {
5671 Task::ready(Ok(cx.new(|cx| {
5672 let action_log = cx.new(|_| ActionLog::new(project.clone()));
5673 AcpThread::new(
5674 "SaboteurAgentConnection",
5675 self,
5676 project,
5677 action_log,
5678 SessionId("test".into()),
5679 watch::Receiver::constant(acp::PromptCapabilities {
5680 image: true,
5681 audio: true,
5682 embedded_context: true,
5683 }),
5684 vec![],
5685 cx,
5686 )
5687 })))
5688 }
5689
5690 fn auth_methods(&self) -> &[acp::AuthMethod] {
5691 &[]
5692 }
5693
5694 fn authenticate(
5695 &self,
5696 _method_id: acp::AuthMethodId,
5697 _cx: &mut App,
5698 ) -> Task<gpui::Result<()>> {
5699 unimplemented!()
5700 }
5701
5702 fn prompt(
5703 &self,
5704 _id: Option<acp_thread::UserMessageId>,
5705 _params: acp::PromptRequest,
5706 _cx: &mut App,
5707 ) -> Task<gpui::Result<acp::PromptResponse>> {
5708 Task::ready(Err(anyhow::anyhow!("Error prompting")))
5709 }
5710
5711 fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {
5712 unimplemented!()
5713 }
5714
5715 fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
5716 self
5717 }
5718 }
5719
5720 /// Simulates a model which always returns a refusal response
5721 #[derive(Clone)]
5722 struct RefusalAgentConnection;
5723
5724 impl AgentConnection for RefusalAgentConnection {
5725 fn new_thread(
5726 self: Rc<Self>,
5727 project: Entity<Project>,
5728 _cwd: &Path,
5729 cx: &mut gpui::App,
5730 ) -> Task<gpui::Result<Entity<AcpThread>>> {
5731 Task::ready(Ok(cx.new(|cx| {
5732 let action_log = cx.new(|_| ActionLog::new(project.clone()));
5733 AcpThread::new(
5734 "RefusalAgentConnection",
5735 self,
5736 project,
5737 action_log,
5738 SessionId("test".into()),
5739 watch::Receiver::constant(acp::PromptCapabilities {
5740 image: true,
5741 audio: true,
5742 embedded_context: true,
5743 }),
5744 Vec::new(),
5745 cx,
5746 )
5747 })))
5748 }
5749
5750 fn auth_methods(&self) -> &[acp::AuthMethod] {
5751 &[]
5752 }
5753
5754 fn authenticate(
5755 &self,
5756 _method_id: acp::AuthMethodId,
5757 _cx: &mut App,
5758 ) -> Task<gpui::Result<()>> {
5759 unimplemented!()
5760 }
5761
5762 fn prompt(
5763 &self,
5764 _id: Option<acp_thread::UserMessageId>,
5765 _params: acp::PromptRequest,
5766 _cx: &mut App,
5767 ) -> Task<gpui::Result<acp::PromptResponse>> {
5768 Task::ready(Ok(acp::PromptResponse {
5769 stop_reason: acp::StopReason::Refusal,
5770 }))
5771 }
5772
5773 fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {
5774 unimplemented!()
5775 }
5776
5777 fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
5778 self
5779 }
5780 }
5781
5782 pub(crate) fn init_test(cx: &mut TestAppContext) {
5783 cx.update(|cx| {
5784 let settings_store = SettingsStore::test(cx);
5785 cx.set_global(settings_store);
5786 language::init(cx);
5787 Project::init_settings(cx);
5788 AgentSettings::register(cx);
5789 workspace::init_settings(cx);
5790 ThemeSettings::register(cx);
5791 release_channel::init(SemanticVersion::default(), cx);
5792 EditorSettings::register(cx);
5793 prompt_store::init(cx)
5794 });
5795 }
5796
5797 #[gpui::test]
5798 async fn test_rewind_views(cx: &mut TestAppContext) {
5799 init_test(cx);
5800
5801 let fs = FakeFs::new(cx.executor());
5802 fs.insert_tree(
5803 "/project",
5804 json!({
5805 "test1.txt": "old content 1",
5806 "test2.txt": "old content 2"
5807 }),
5808 )
5809 .await;
5810 let project = Project::test(fs, [Path::new("/project")], cx).await;
5811 let (workspace, cx) =
5812 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5813
5814 let context_store =
5815 cx.update(|_window, cx| cx.new(|cx| ContextStore::fake(project.clone(), cx)));
5816 let history_store =
5817 cx.update(|_window, cx| cx.new(|cx| HistoryStore::new(context_store, cx)));
5818
5819 let connection = Rc::new(StubAgentConnection::new());
5820 let thread_view = cx.update(|window, cx| {
5821 cx.new(|cx| {
5822 AcpThreadView::new(
5823 Rc::new(StubAgentServer::new(connection.as_ref().clone())),
5824 None,
5825 None,
5826 workspace.downgrade(),
5827 project.clone(),
5828 history_store.clone(),
5829 None,
5830 window,
5831 cx,
5832 )
5833 })
5834 });
5835
5836 cx.run_until_parked();
5837
5838 let thread = thread_view
5839 .read_with(cx, |view, _| view.thread().cloned())
5840 .unwrap();
5841
5842 // First user message
5843 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(acp::ToolCall {
5844 id: acp::ToolCallId("tool1".into()),
5845 title: "Edit file 1".into(),
5846 kind: acp::ToolKind::Edit,
5847 status: acp::ToolCallStatus::Completed,
5848 content: vec![acp::ToolCallContent::Diff {
5849 diff: acp::Diff {
5850 path: "/project/test1.txt".into(),
5851 old_text: Some("old content 1".into()),
5852 new_text: "new content 1".into(),
5853 },
5854 }],
5855 locations: vec![],
5856 raw_input: None,
5857 raw_output: None,
5858 })]);
5859
5860 thread
5861 .update(cx, |thread, cx| thread.send_raw("Give me a diff", cx))
5862 .await
5863 .unwrap();
5864 cx.run_until_parked();
5865
5866 thread.read_with(cx, |thread, _| {
5867 assert_eq!(thread.entries().len(), 2);
5868 });
5869
5870 thread_view.read_with(cx, |view, cx| {
5871 view.entry_view_state.read_with(cx, |entry_view_state, _| {
5872 assert!(
5873 entry_view_state
5874 .entry(0)
5875 .unwrap()
5876 .message_editor()
5877 .is_some()
5878 );
5879 assert!(entry_view_state.entry(1).unwrap().has_content());
5880 });
5881 });
5882
5883 // Second user message
5884 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(acp::ToolCall {
5885 id: acp::ToolCallId("tool2".into()),
5886 title: "Edit file 2".into(),
5887 kind: acp::ToolKind::Edit,
5888 status: acp::ToolCallStatus::Completed,
5889 content: vec![acp::ToolCallContent::Diff {
5890 diff: acp::Diff {
5891 path: "/project/test2.txt".into(),
5892 old_text: Some("old content 2".into()),
5893 new_text: "new content 2".into(),
5894 },
5895 }],
5896 locations: vec![],
5897 raw_input: None,
5898 raw_output: None,
5899 })]);
5900
5901 thread
5902 .update(cx, |thread, cx| thread.send_raw("Another one", cx))
5903 .await
5904 .unwrap();
5905 cx.run_until_parked();
5906
5907 let second_user_message_id = thread.read_with(cx, |thread, _| {
5908 assert_eq!(thread.entries().len(), 4);
5909 let AgentThreadEntry::UserMessage(user_message) = &thread.entries()[2] else {
5910 panic!();
5911 };
5912 user_message.id.clone().unwrap()
5913 });
5914
5915 thread_view.read_with(cx, |view, cx| {
5916 view.entry_view_state.read_with(cx, |entry_view_state, _| {
5917 assert!(
5918 entry_view_state
5919 .entry(0)
5920 .unwrap()
5921 .message_editor()
5922 .is_some()
5923 );
5924 assert!(entry_view_state.entry(1).unwrap().has_content());
5925 assert!(
5926 entry_view_state
5927 .entry(2)
5928 .unwrap()
5929 .message_editor()
5930 .is_some()
5931 );
5932 assert!(entry_view_state.entry(3).unwrap().has_content());
5933 });
5934 });
5935
5936 // Rewind to first message
5937 thread
5938 .update(cx, |thread, cx| thread.rewind(second_user_message_id, cx))
5939 .await
5940 .unwrap();
5941
5942 cx.run_until_parked();
5943
5944 thread.read_with(cx, |thread, _| {
5945 assert_eq!(thread.entries().len(), 2);
5946 });
5947
5948 thread_view.read_with(cx, |view, cx| {
5949 view.entry_view_state.read_with(cx, |entry_view_state, _| {
5950 assert!(
5951 entry_view_state
5952 .entry(0)
5953 .unwrap()
5954 .message_editor()
5955 .is_some()
5956 );
5957 assert!(entry_view_state.entry(1).unwrap().has_content());
5958
5959 // Old views should be dropped
5960 assert!(entry_view_state.entry(2).is_none());
5961 assert!(entry_view_state.entry(3).is_none());
5962 });
5963 });
5964 }
5965
5966 #[gpui::test]
5967 async fn test_message_editing_cancel(cx: &mut TestAppContext) {
5968 init_test(cx);
5969
5970 let connection = StubAgentConnection::new();
5971
5972 connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk {
5973 content: acp::ContentBlock::Text(acp::TextContent {
5974 text: "Response".into(),
5975 annotations: None,
5976 }),
5977 }]);
5978
5979 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
5980 add_to_workspace(thread_view.clone(), cx);
5981
5982 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
5983 message_editor.update_in(cx, |editor, window, cx| {
5984 editor.set_text("Original message to edit", window, cx);
5985 });
5986 thread_view.update_in(cx, |thread_view, window, cx| {
5987 thread_view.send(window, cx);
5988 });
5989
5990 cx.run_until_parked();
5991
5992 let user_message_editor = thread_view.read_with(cx, |view, cx| {
5993 assert_eq!(view.editing_message, None);
5994
5995 view.entry_view_state
5996 .read(cx)
5997 .entry(0)
5998 .unwrap()
5999 .message_editor()
6000 .unwrap()
6001 .clone()
6002 });
6003
6004 // Focus
6005 cx.focus(&user_message_editor);
6006 thread_view.read_with(cx, |view, _cx| {
6007 assert_eq!(view.editing_message, Some(0));
6008 });
6009
6010 // Edit
6011 user_message_editor.update_in(cx, |editor, window, cx| {
6012 editor.set_text("Edited message content", window, cx);
6013 });
6014
6015 // Cancel
6016 user_message_editor.update_in(cx, |_editor, window, cx| {
6017 window.dispatch_action(Box::new(editor::actions::Cancel), cx);
6018 });
6019
6020 thread_view.read_with(cx, |view, _cx| {
6021 assert_eq!(view.editing_message, None);
6022 });
6023
6024 user_message_editor.read_with(cx, |editor, cx| {
6025 assert_eq!(editor.text(cx), "Original message to edit");
6026 });
6027 }
6028
6029 #[gpui::test]
6030 async fn test_message_doesnt_send_if_empty(cx: &mut TestAppContext) {
6031 init_test(cx);
6032
6033 let connection = StubAgentConnection::new();
6034
6035 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
6036 add_to_workspace(thread_view.clone(), cx);
6037
6038 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
6039 let mut events = cx.events(&message_editor);
6040 message_editor.update_in(cx, |editor, window, cx| {
6041 editor.set_text("", window, cx);
6042 });
6043
6044 message_editor.update_in(cx, |_editor, window, cx| {
6045 window.dispatch_action(Box::new(Chat), cx);
6046 });
6047 cx.run_until_parked();
6048 // We shouldn't have received any messages
6049 assert!(matches!(
6050 events.try_next(),
6051 Err(futures::channel::mpsc::TryRecvError { .. })
6052 ));
6053 }
6054
6055 #[gpui::test]
6056 async fn test_message_editing_regenerate(cx: &mut TestAppContext) {
6057 init_test(cx);
6058
6059 let connection = StubAgentConnection::new();
6060
6061 connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk {
6062 content: acp::ContentBlock::Text(acp::TextContent {
6063 text: "Response".into(),
6064 annotations: None,
6065 }),
6066 }]);
6067
6068 let (thread_view, cx) =
6069 setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
6070 add_to_workspace(thread_view.clone(), cx);
6071
6072 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
6073 message_editor.update_in(cx, |editor, window, cx| {
6074 editor.set_text("Original message to edit", window, cx);
6075 });
6076 thread_view.update_in(cx, |thread_view, window, cx| {
6077 thread_view.send(window, cx);
6078 });
6079
6080 cx.run_until_parked();
6081
6082 let user_message_editor = thread_view.read_with(cx, |view, cx| {
6083 assert_eq!(view.editing_message, None);
6084 assert_eq!(view.thread().unwrap().read(cx).entries().len(), 2);
6085
6086 view.entry_view_state
6087 .read(cx)
6088 .entry(0)
6089 .unwrap()
6090 .message_editor()
6091 .unwrap()
6092 .clone()
6093 });
6094
6095 // Focus
6096 cx.focus(&user_message_editor);
6097
6098 // Edit
6099 user_message_editor.update_in(cx, |editor, window, cx| {
6100 editor.set_text("Edited message content", window, cx);
6101 });
6102
6103 // Send
6104 connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk {
6105 content: acp::ContentBlock::Text(acp::TextContent {
6106 text: "New Response".into(),
6107 annotations: None,
6108 }),
6109 }]);
6110
6111 user_message_editor.update_in(cx, |_editor, window, cx| {
6112 window.dispatch_action(Box::new(Chat), cx);
6113 });
6114
6115 cx.run_until_parked();
6116
6117 thread_view.read_with(cx, |view, cx| {
6118 assert_eq!(view.editing_message, None);
6119
6120 let entries = view.thread().unwrap().read(cx).entries();
6121 assert_eq!(entries.len(), 2);
6122 assert_eq!(
6123 entries[0].to_markdown(cx),
6124 "## User\n\nEdited message content\n\n"
6125 );
6126 assert_eq!(
6127 entries[1].to_markdown(cx),
6128 "## Assistant\n\nNew Response\n\n"
6129 );
6130
6131 let new_editor = view.entry_view_state.read_with(cx, |state, _cx| {
6132 assert!(!state.entry(1).unwrap().has_content());
6133 state.entry(0).unwrap().message_editor().unwrap().clone()
6134 });
6135
6136 assert_eq!(new_editor.read(cx).text(cx), "Edited message content");
6137 })
6138 }
6139
6140 #[gpui::test]
6141 async fn test_message_editing_while_generating(cx: &mut TestAppContext) {
6142 init_test(cx);
6143
6144 let connection = StubAgentConnection::new();
6145
6146 let (thread_view, cx) =
6147 setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
6148 add_to_workspace(thread_view.clone(), cx);
6149
6150 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
6151 message_editor.update_in(cx, |editor, window, cx| {
6152 editor.set_text("Original message to edit", window, cx);
6153 });
6154 thread_view.update_in(cx, |thread_view, window, cx| {
6155 thread_view.send(window, cx);
6156 });
6157
6158 cx.run_until_parked();
6159
6160 let (user_message_editor, session_id) = thread_view.read_with(cx, |view, cx| {
6161 let thread = view.thread().unwrap().read(cx);
6162 assert_eq!(thread.entries().len(), 1);
6163
6164 let editor = view
6165 .entry_view_state
6166 .read(cx)
6167 .entry(0)
6168 .unwrap()
6169 .message_editor()
6170 .unwrap()
6171 .clone();
6172
6173 (editor, thread.session_id().clone())
6174 });
6175
6176 // Focus
6177 cx.focus(&user_message_editor);
6178
6179 thread_view.read_with(cx, |view, _cx| {
6180 assert_eq!(view.editing_message, Some(0));
6181 });
6182
6183 // Edit
6184 user_message_editor.update_in(cx, |editor, window, cx| {
6185 editor.set_text("Edited message content", window, cx);
6186 });
6187
6188 thread_view.read_with(cx, |view, _cx| {
6189 assert_eq!(view.editing_message, Some(0));
6190 });
6191
6192 // Finish streaming response
6193 cx.update(|_, cx| {
6194 connection.send_update(
6195 session_id.clone(),
6196 acp::SessionUpdate::AgentMessageChunk {
6197 content: acp::ContentBlock::Text(acp::TextContent {
6198 text: "Response".into(),
6199 annotations: None,
6200 }),
6201 },
6202 cx,
6203 );
6204 connection.end_turn(session_id, acp::StopReason::EndTurn);
6205 });
6206
6207 thread_view.read_with(cx, |view, _cx| {
6208 assert_eq!(view.editing_message, Some(0));
6209 });
6210
6211 cx.run_until_parked();
6212
6213 // Should still be editing
6214 cx.update(|window, cx| {
6215 assert!(user_message_editor.focus_handle(cx).is_focused(window));
6216 assert_eq!(thread_view.read(cx).editing_message, Some(0));
6217 assert_eq!(
6218 user_message_editor.read(cx).text(cx),
6219 "Edited message content"
6220 );
6221 });
6222 }
6223
6224 #[gpui::test]
6225 async fn test_interrupt(cx: &mut TestAppContext) {
6226 init_test(cx);
6227
6228 let connection = StubAgentConnection::new();
6229
6230 let (thread_view, cx) =
6231 setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
6232 add_to_workspace(thread_view.clone(), cx);
6233
6234 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
6235 message_editor.update_in(cx, |editor, window, cx| {
6236 editor.set_text("Message 1", window, cx);
6237 });
6238 thread_view.update_in(cx, |thread_view, window, cx| {
6239 thread_view.send(window, cx);
6240 });
6241
6242 let (thread, session_id) = thread_view.read_with(cx, |view, cx| {
6243 let thread = view.thread().unwrap();
6244
6245 (thread.clone(), thread.read(cx).session_id().clone())
6246 });
6247
6248 cx.run_until_parked();
6249
6250 cx.update(|_, cx| {
6251 connection.send_update(
6252 session_id.clone(),
6253 acp::SessionUpdate::AgentMessageChunk {
6254 content: "Message 1 resp".into(),
6255 },
6256 cx,
6257 );
6258 });
6259
6260 cx.run_until_parked();
6261
6262 thread.read_with(cx, |thread, cx| {
6263 assert_eq!(
6264 thread.to_markdown(cx),
6265 indoc::indoc! {"
6266 ## User
6267
6268 Message 1
6269
6270 ## Assistant
6271
6272 Message 1 resp
6273
6274 "}
6275 )
6276 });
6277
6278 message_editor.update_in(cx, |editor, window, cx| {
6279 editor.set_text("Message 2", window, cx);
6280 });
6281 thread_view.update_in(cx, |thread_view, window, cx| {
6282 thread_view.send(window, cx);
6283 });
6284
6285 cx.update(|_, cx| {
6286 // Simulate a response sent after beginning to cancel
6287 connection.send_update(
6288 session_id.clone(),
6289 acp::SessionUpdate::AgentMessageChunk {
6290 content: "onse".into(),
6291 },
6292 cx,
6293 );
6294 });
6295
6296 cx.run_until_parked();
6297
6298 // Last Message 1 response should appear before Message 2
6299 thread.read_with(cx, |thread, cx| {
6300 assert_eq!(
6301 thread.to_markdown(cx),
6302 indoc::indoc! {"
6303 ## User
6304
6305 Message 1
6306
6307 ## Assistant
6308
6309 Message 1 response
6310
6311 ## User
6312
6313 Message 2
6314
6315 "}
6316 )
6317 });
6318
6319 cx.update(|_, cx| {
6320 connection.send_update(
6321 session_id.clone(),
6322 acp::SessionUpdate::AgentMessageChunk {
6323 content: "Message 2 response".into(),
6324 },
6325 cx,
6326 );
6327 connection.end_turn(session_id.clone(), acp::StopReason::EndTurn);
6328 });
6329
6330 cx.run_until_parked();
6331
6332 thread.read_with(cx, |thread, cx| {
6333 assert_eq!(
6334 thread.to_markdown(cx),
6335 indoc::indoc! {"
6336 ## User
6337
6338 Message 1
6339
6340 ## Assistant
6341
6342 Message 1 response
6343
6344 ## User
6345
6346 Message 2
6347
6348 ## Assistant
6349
6350 Message 2 response
6351
6352 "}
6353 )
6354 });
6355 }
6356}