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