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