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