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