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