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