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 .w_full()
2060 .child(
2061 Icon::new(IconName::Reader)
2062 .size(IconSize::XSmall)
2063 .color(Color::Disabled),
2064 )
2065 .child(
2066 Label::new(user_rules_text)
2067 .size(LabelSize::XSmall)
2068 .color(Color::Muted)
2069 .truncate()
2070 .buffer_font(cx)
2071 .ml_1p5()
2072 .mr_0p5(),
2073 )
2074 .child(
2075 IconButton::new("open-prompt-library", IconName::ArrowUpRight)
2076 .shape(ui::IconButtonShape::Square)
2077 .icon_size(IconSize::XSmall)
2078 .icon_color(Color::Ignored)
2079 .visible_on_hover("user-rules")
2080 // TODO: Figure out a way to pass focus handle here so we can display the `OpenRulesLibrary` keybinding
2081 .tooltip(Tooltip::text("View User Rules"))
2082 .on_click(move |_event, window, cx| {
2083 window.dispatch_action(
2084 Box::new(OpenRulesLibrary {
2085 prompt_to_select: first_user_rules_id,
2086 }),
2087 cx,
2088 )
2089 }),
2090 ),
2091 )
2092 })
2093 .when_some(rules_file_text, |parent, rules_file_text| {
2094 parent.child(
2095 h_flex()
2096 .group("project-rules")
2097 .w_full()
2098 .child(
2099 Icon::new(IconName::File)
2100 .size(IconSize::XSmall)
2101 .color(Color::Disabled),
2102 )
2103 .child(
2104 Label::new(rules_file_text)
2105 .size(LabelSize::XSmall)
2106 .color(Color::Muted)
2107 .buffer_font(cx)
2108 .ml_1p5()
2109 .mr_0p5(),
2110 )
2111 .child(
2112 IconButton::new("open-rule", IconName::ArrowUpRight)
2113 .shape(ui::IconButtonShape::Square)
2114 .icon_size(IconSize::XSmall)
2115 .icon_color(Color::Ignored)
2116 .on_click(cx.listener(Self::handle_open_rules))
2117 .visible_on_hover("project-rules")
2118 .tooltip(Tooltip::text("View Project Rules")),
2119 ),
2120 )
2121 })
2122 .into_any(),
2123 )
2124 }
2125
2126 fn render_empty_state(&self, cx: &App) -> AnyElement {
2127 let loading = matches!(&self.thread_state, ThreadState::Loading { .. });
2128
2129 v_flex()
2130 .size_full()
2131 .items_center()
2132 .justify_center()
2133 .child(if loading {
2134 h_flex()
2135 .justify_center()
2136 .child(self.render_agent_logo())
2137 .with_animation(
2138 "pulsating_icon",
2139 Animation::new(Duration::from_secs(2))
2140 .repeat()
2141 .with_easing(pulsating_between(0.4, 1.0)),
2142 |icon, delta| icon.opacity(delta),
2143 )
2144 .into_any()
2145 } else {
2146 self.render_agent_logo().into_any_element()
2147 })
2148 .child(h_flex().mt_4().mb_1().justify_center().child(if loading {
2149 div()
2150 .child(LoadingLabel::new("").size(LabelSize::Large))
2151 .into_any_element()
2152 } else {
2153 Headline::new(self.agent.empty_state_headline())
2154 .size(HeadlineSize::Medium)
2155 .into_any_element()
2156 }))
2157 .child(
2158 div()
2159 .max_w_1_2()
2160 .text_sm()
2161 .text_center()
2162 .map(|this| {
2163 if loading {
2164 this.invisible()
2165 } else {
2166 this.text_color(cx.theme().colors().text_muted)
2167 }
2168 })
2169 .child(self.agent.empty_state_message()),
2170 )
2171 .into_any()
2172 }
2173
2174 fn render_auth_required_state(
2175 &self,
2176 connection: &Rc<dyn AgentConnection>,
2177 description: Option<&Entity<Markdown>>,
2178 configuration_view: Option<&AnyView>,
2179 window: &mut Window,
2180 cx: &Context<Self>,
2181 ) -> Div {
2182 v_flex()
2183 .p_2()
2184 .gap_2()
2185 .flex_1()
2186 .items_center()
2187 .justify_center()
2188 .child(
2189 v_flex()
2190 .items_center()
2191 .justify_center()
2192 .child(self.render_error_agent_logo())
2193 .child(h_flex().mt_4().mb_1().justify_center().child(
2194 Headline::new(self.agent.empty_state_headline()).size(HeadlineSize::Medium),
2195 ))
2196 .into_any(),
2197 )
2198 .children(description.map(|desc| {
2199 div().text_ui(cx).text_center().child(
2200 self.render_markdown(desc.clone(), default_markdown_style(false, window, cx)),
2201 )
2202 }))
2203 .children(
2204 configuration_view
2205 .cloned()
2206 .map(|view| div().px_4().w_full().max_w_128().child(view)),
2207 )
2208 .child(h_flex().mt_1p5().justify_center().children(
2209 connection.auth_methods().iter().map(|method| {
2210 Button::new(SharedString::from(method.id.0.clone()), method.name.clone())
2211 .on_click({
2212 let method_id = method.id.clone();
2213 cx.listener(move |this, _, window, cx| {
2214 this.authenticate(method_id.clone(), window, cx)
2215 })
2216 })
2217 }),
2218 ))
2219 }
2220
2221 fn render_load_error(&self, e: &LoadError, cx: &Context<Self>) -> AnyElement {
2222 let mut container = v_flex()
2223 .items_center()
2224 .justify_center()
2225 .child(self.render_error_agent_logo())
2226 .child(
2227 v_flex()
2228 .mt_4()
2229 .mb_2()
2230 .gap_0p5()
2231 .text_center()
2232 .items_center()
2233 .child(Headline::new("Failed to launch").size(HeadlineSize::Medium))
2234 .child(
2235 Label::new(e.to_string())
2236 .size(LabelSize::Small)
2237 .color(Color::Muted),
2238 ),
2239 );
2240
2241 if let LoadError::Unsupported {
2242 upgrade_message,
2243 upgrade_command,
2244 ..
2245 } = &e
2246 {
2247 let upgrade_message = upgrade_message.clone();
2248 let upgrade_command = upgrade_command.clone();
2249 container = container.child(
2250 Button::new("upgrade", upgrade_message)
2251 .tooltip(Tooltip::text(upgrade_command.clone()))
2252 .on_click(cx.listener(move |this, _, window, cx| {
2253 let task = this
2254 .workspace
2255 .update(cx, |workspace, cx| {
2256 let project = workspace.project().read(cx);
2257 let cwd = project.first_project_directory(cx);
2258 let shell = project.terminal_settings(&cwd, cx).shell.clone();
2259 let spawn_in_terminal = task::SpawnInTerminal {
2260 id: task::TaskId("upgrade".to_string()),
2261 full_label: upgrade_command.clone(),
2262 label: upgrade_command.clone(),
2263 command: Some(upgrade_command.clone()),
2264 args: Vec::new(),
2265 command_label: upgrade_command.clone(),
2266 cwd,
2267 env: Default::default(),
2268 use_new_terminal: true,
2269 allow_concurrent_runs: true,
2270 reveal: Default::default(),
2271 reveal_target: Default::default(),
2272 hide: Default::default(),
2273 shell,
2274 show_summary: true,
2275 show_command: true,
2276 show_rerun: false,
2277 };
2278 workspace.spawn_in_terminal(spawn_in_terminal, window, cx)
2279 })
2280 .ok();
2281 let Some(task) = task else { return };
2282 cx.spawn_in(window, async move |this, cx| {
2283 if let Some(Ok(_)) = task.await {
2284 this.update_in(cx, |this, window, cx| {
2285 this.reset(window, cx);
2286 })
2287 .ok();
2288 }
2289 })
2290 .detach()
2291 })),
2292 );
2293 } else if let LoadError::NotInstalled {
2294 install_message,
2295 install_command,
2296 ..
2297 } = e
2298 {
2299 let install_message = install_message.clone();
2300 let install_command = install_command.clone();
2301 container = container.child(
2302 Button::new("install", install_message)
2303 .tooltip(Tooltip::text(install_command.clone()))
2304 .on_click(cx.listener(move |this, _, window, cx| {
2305 let task = this
2306 .workspace
2307 .update(cx, |workspace, cx| {
2308 let project = workspace.project().read(cx);
2309 let cwd = project.first_project_directory(cx);
2310 let shell = project.terminal_settings(&cwd, cx).shell.clone();
2311 let spawn_in_terminal = task::SpawnInTerminal {
2312 id: task::TaskId("install".to_string()),
2313 full_label: install_command.clone(),
2314 label: install_command.clone(),
2315 command: Some(install_command.clone()),
2316 args: Vec::new(),
2317 command_label: install_command.clone(),
2318 cwd,
2319 env: Default::default(),
2320 use_new_terminal: true,
2321 allow_concurrent_runs: true,
2322 reveal: Default::default(),
2323 reveal_target: Default::default(),
2324 hide: Default::default(),
2325 shell,
2326 show_summary: true,
2327 show_command: true,
2328 show_rerun: false,
2329 };
2330 workspace.spawn_in_terminal(spawn_in_terminal, window, cx)
2331 })
2332 .ok();
2333 let Some(task) = task else { return };
2334 cx.spawn_in(window, async move |this, cx| {
2335 if let Some(Ok(_)) = task.await {
2336 this.update_in(cx, |this, window, cx| {
2337 this.reset(window, cx);
2338 })
2339 .ok();
2340 }
2341 })
2342 .detach()
2343 })),
2344 );
2345 }
2346
2347 container.into_any()
2348 }
2349
2350 fn render_activity_bar(
2351 &self,
2352 thread_entity: &Entity<AcpThread>,
2353 window: &mut Window,
2354 cx: &Context<Self>,
2355 ) -> Option<AnyElement> {
2356 let thread = thread_entity.read(cx);
2357 let action_log = thread.action_log();
2358 let changed_buffers = action_log.read(cx).changed_buffers(cx);
2359 let plan = thread.plan();
2360
2361 if changed_buffers.is_empty() && plan.is_empty() {
2362 return None;
2363 }
2364
2365 let editor_bg_color = cx.theme().colors().editor_background;
2366 let active_color = cx.theme().colors().element_selected;
2367 let bg_edit_files_disclosure = editor_bg_color.blend(active_color.opacity(0.3));
2368
2369 let pending_edits = thread.has_pending_edit_tool_calls();
2370
2371 v_flex()
2372 .mt_1()
2373 .mx_2()
2374 .bg(bg_edit_files_disclosure)
2375 .border_1()
2376 .border_b_0()
2377 .border_color(cx.theme().colors().border)
2378 .rounded_t_md()
2379 .shadow(vec![gpui::BoxShadow {
2380 color: gpui::black().opacity(0.15),
2381 offset: point(px(1.), px(-1.)),
2382 blur_radius: px(3.),
2383 spread_radius: px(0.),
2384 }])
2385 .when(!plan.is_empty(), |this| {
2386 this.child(self.render_plan_summary(plan, window, cx))
2387 .when(self.plan_expanded, |parent| {
2388 parent.child(self.render_plan_entries(plan, window, cx))
2389 })
2390 })
2391 .when(!plan.is_empty() && !changed_buffers.is_empty(), |this| {
2392 this.child(Divider::horizontal().color(DividerColor::Border))
2393 })
2394 .when(!changed_buffers.is_empty(), |this| {
2395 this.child(self.render_edits_summary(
2396 action_log,
2397 &changed_buffers,
2398 self.edits_expanded,
2399 pending_edits,
2400 window,
2401 cx,
2402 ))
2403 .when(self.edits_expanded, |parent| {
2404 parent.child(self.render_edited_files(
2405 action_log,
2406 &changed_buffers,
2407 pending_edits,
2408 cx,
2409 ))
2410 })
2411 })
2412 .into_any()
2413 .into()
2414 }
2415
2416 fn render_plan_summary(&self, plan: &Plan, window: &mut Window, cx: &Context<Self>) -> Div {
2417 let stats = plan.stats();
2418
2419 let title = if let Some(entry) = stats.in_progress_entry
2420 && !self.plan_expanded
2421 {
2422 h_flex()
2423 .w_full()
2424 .cursor_default()
2425 .gap_1()
2426 .text_xs()
2427 .text_color(cx.theme().colors().text_muted)
2428 .justify_between()
2429 .child(
2430 h_flex()
2431 .gap_1()
2432 .child(
2433 Label::new("Current:")
2434 .size(LabelSize::Small)
2435 .color(Color::Muted),
2436 )
2437 .child(MarkdownElement::new(
2438 entry.content.clone(),
2439 plan_label_markdown_style(&entry.status, window, cx),
2440 )),
2441 )
2442 .when(stats.pending > 0, |this| {
2443 this.child(
2444 Label::new(format!("{} left", stats.pending))
2445 .size(LabelSize::Small)
2446 .color(Color::Muted)
2447 .mr_1(),
2448 )
2449 })
2450 } else {
2451 let status_label = if stats.pending == 0 {
2452 "All Done".to_string()
2453 } else if stats.completed == 0 {
2454 format!("{} Tasks", plan.entries.len())
2455 } else {
2456 format!("{}/{}", stats.completed, plan.entries.len())
2457 };
2458
2459 h_flex()
2460 .w_full()
2461 .gap_1()
2462 .justify_between()
2463 .child(
2464 Label::new("Plan")
2465 .size(LabelSize::Small)
2466 .color(Color::Muted),
2467 )
2468 .child(
2469 Label::new(status_label)
2470 .size(LabelSize::Small)
2471 .color(Color::Muted)
2472 .mr_1(),
2473 )
2474 };
2475
2476 h_flex()
2477 .p_1()
2478 .justify_between()
2479 .when(self.plan_expanded, |this| {
2480 this.border_b_1().border_color(cx.theme().colors().border)
2481 })
2482 .child(
2483 h_flex()
2484 .id("plan_summary")
2485 .w_full()
2486 .gap_1()
2487 .child(Disclosure::new("plan_disclosure", self.plan_expanded))
2488 .child(title)
2489 .on_click(cx.listener(|this, _, _, cx| {
2490 this.plan_expanded = !this.plan_expanded;
2491 cx.notify();
2492 })),
2493 )
2494 }
2495
2496 fn render_plan_entries(&self, plan: &Plan, window: &mut Window, cx: &Context<Self>) -> Div {
2497 v_flex().children(plan.entries.iter().enumerate().flat_map(|(index, entry)| {
2498 let element = h_flex()
2499 .py_1()
2500 .px_2()
2501 .gap_2()
2502 .justify_between()
2503 .bg(cx.theme().colors().editor_background)
2504 .when(index < plan.entries.len() - 1, |parent| {
2505 parent.border_color(cx.theme().colors().border).border_b_1()
2506 })
2507 .child(
2508 h_flex()
2509 .id(("plan_entry", index))
2510 .gap_1p5()
2511 .max_w_full()
2512 .overflow_x_scroll()
2513 .text_xs()
2514 .text_color(cx.theme().colors().text_muted)
2515 .child(match entry.status {
2516 acp::PlanEntryStatus::Pending => Icon::new(IconName::TodoPending)
2517 .size(IconSize::Small)
2518 .color(Color::Muted)
2519 .into_any_element(),
2520 acp::PlanEntryStatus::InProgress => Icon::new(IconName::TodoProgress)
2521 .size(IconSize::Small)
2522 .color(Color::Accent)
2523 .with_animation(
2524 "running",
2525 Animation::new(Duration::from_secs(2)).repeat(),
2526 |icon, delta| {
2527 icon.transform(Transformation::rotate(percentage(delta)))
2528 },
2529 )
2530 .into_any_element(),
2531 acp::PlanEntryStatus::Completed => Icon::new(IconName::TodoComplete)
2532 .size(IconSize::Small)
2533 .color(Color::Success)
2534 .into_any_element(),
2535 })
2536 .child(MarkdownElement::new(
2537 entry.content.clone(),
2538 plan_label_markdown_style(&entry.status, window, cx),
2539 )),
2540 );
2541
2542 Some(element)
2543 }))
2544 }
2545
2546 fn render_edits_summary(
2547 &self,
2548 action_log: &Entity<ActionLog>,
2549 changed_buffers: &BTreeMap<Entity<Buffer>, Entity<BufferDiff>>,
2550 expanded: bool,
2551 pending_edits: bool,
2552 window: &mut Window,
2553 cx: &Context<Self>,
2554 ) -> Div {
2555 const EDIT_NOT_READY_TOOLTIP_LABEL: &str = "Wait until file edits are complete.";
2556
2557 let focus_handle = self.focus_handle(cx);
2558
2559 h_flex()
2560 .p_1()
2561 .justify_between()
2562 .when(expanded, |this| {
2563 this.border_b_1().border_color(cx.theme().colors().border)
2564 })
2565 .child(
2566 h_flex()
2567 .id("edits-container")
2568 .w_full()
2569 .gap_1()
2570 .child(Disclosure::new("edits-disclosure", expanded))
2571 .map(|this| {
2572 if pending_edits {
2573 this.child(
2574 Label::new(format!(
2575 "Editing {} {}…",
2576 changed_buffers.len(),
2577 if changed_buffers.len() == 1 {
2578 "file"
2579 } else {
2580 "files"
2581 }
2582 ))
2583 .color(Color::Muted)
2584 .size(LabelSize::Small)
2585 .with_animation(
2586 "edit-label",
2587 Animation::new(Duration::from_secs(2))
2588 .repeat()
2589 .with_easing(pulsating_between(0.3, 0.7)),
2590 |label, delta| label.alpha(delta),
2591 ),
2592 )
2593 } else {
2594 this.child(
2595 Label::new("Edits")
2596 .size(LabelSize::Small)
2597 .color(Color::Muted),
2598 )
2599 .child(Label::new("•").size(LabelSize::XSmall).color(Color::Muted))
2600 .child(
2601 Label::new(format!(
2602 "{} {}",
2603 changed_buffers.len(),
2604 if changed_buffers.len() == 1 {
2605 "file"
2606 } else {
2607 "files"
2608 }
2609 ))
2610 .size(LabelSize::Small)
2611 .color(Color::Muted),
2612 )
2613 }
2614 })
2615 .on_click(cx.listener(|this, _, _, cx| {
2616 this.edits_expanded = !this.edits_expanded;
2617 cx.notify();
2618 })),
2619 )
2620 .child(
2621 h_flex()
2622 .gap_1()
2623 .child(
2624 IconButton::new("review-changes", IconName::ListTodo)
2625 .icon_size(IconSize::Small)
2626 .tooltip({
2627 let focus_handle = focus_handle.clone();
2628 move |window, cx| {
2629 Tooltip::for_action_in(
2630 "Review Changes",
2631 &OpenAgentDiff,
2632 &focus_handle,
2633 window,
2634 cx,
2635 )
2636 }
2637 })
2638 .on_click(cx.listener(|_, _, window, cx| {
2639 window.dispatch_action(OpenAgentDiff.boxed_clone(), cx);
2640 })),
2641 )
2642 .child(Divider::vertical().color(DividerColor::Border))
2643 .child(
2644 Button::new("reject-all-changes", "Reject All")
2645 .label_size(LabelSize::Small)
2646 .disabled(pending_edits)
2647 .when(pending_edits, |this| {
2648 this.tooltip(Tooltip::text(EDIT_NOT_READY_TOOLTIP_LABEL))
2649 })
2650 .key_binding(
2651 KeyBinding::for_action_in(
2652 &RejectAll,
2653 &focus_handle.clone(),
2654 window,
2655 cx,
2656 )
2657 .map(|kb| kb.size(rems_from_px(10.))),
2658 )
2659 .on_click({
2660 let action_log = action_log.clone();
2661 cx.listener(move |_, _, _, cx| {
2662 action_log.update(cx, |action_log, cx| {
2663 action_log.reject_all_edits(cx).detach();
2664 })
2665 })
2666 }),
2667 )
2668 .child(
2669 Button::new("keep-all-changes", "Keep All")
2670 .label_size(LabelSize::Small)
2671 .disabled(pending_edits)
2672 .when(pending_edits, |this| {
2673 this.tooltip(Tooltip::text(EDIT_NOT_READY_TOOLTIP_LABEL))
2674 })
2675 .key_binding(
2676 KeyBinding::for_action_in(&KeepAll, &focus_handle, window, cx)
2677 .map(|kb| kb.size(rems_from_px(10.))),
2678 )
2679 .on_click({
2680 let action_log = action_log.clone();
2681 cx.listener(move |_, _, _, cx| {
2682 action_log.update(cx, |action_log, cx| {
2683 action_log.keep_all_edits(cx);
2684 })
2685 })
2686 }),
2687 ),
2688 )
2689 }
2690
2691 fn render_edited_files(
2692 &self,
2693 action_log: &Entity<ActionLog>,
2694 changed_buffers: &BTreeMap<Entity<Buffer>, Entity<BufferDiff>>,
2695 pending_edits: bool,
2696 cx: &Context<Self>,
2697 ) -> Div {
2698 let editor_bg_color = cx.theme().colors().editor_background;
2699
2700 v_flex().children(changed_buffers.iter().enumerate().flat_map(
2701 |(index, (buffer, _diff))| {
2702 let file = buffer.read(cx).file()?;
2703 let path = file.path();
2704
2705 let file_path = path.parent().and_then(|parent| {
2706 let parent_str = parent.to_string_lossy();
2707
2708 if parent_str.is_empty() {
2709 None
2710 } else {
2711 Some(
2712 Label::new(format!("/{}{}", parent_str, std::path::MAIN_SEPARATOR_STR))
2713 .color(Color::Muted)
2714 .size(LabelSize::XSmall)
2715 .buffer_font(cx),
2716 )
2717 }
2718 });
2719
2720 let file_name = path.file_name().map(|name| {
2721 Label::new(name.to_string_lossy().to_string())
2722 .size(LabelSize::XSmall)
2723 .buffer_font(cx)
2724 });
2725
2726 let file_icon = FileIcons::get_icon(path, cx)
2727 .map(Icon::from_path)
2728 .map(|icon| icon.color(Color::Muted).size(IconSize::Small))
2729 .unwrap_or_else(|| {
2730 Icon::new(IconName::File)
2731 .color(Color::Muted)
2732 .size(IconSize::Small)
2733 });
2734
2735 let overlay_gradient = linear_gradient(
2736 90.,
2737 linear_color_stop(editor_bg_color, 1.),
2738 linear_color_stop(editor_bg_color.opacity(0.2), 0.),
2739 );
2740
2741 let element = h_flex()
2742 .group("edited-code")
2743 .id(("file-container", index))
2744 .relative()
2745 .py_1()
2746 .pl_2()
2747 .pr_1()
2748 .gap_2()
2749 .justify_between()
2750 .bg(editor_bg_color)
2751 .when(index < changed_buffers.len() - 1, |parent| {
2752 parent.border_color(cx.theme().colors().border).border_b_1()
2753 })
2754 .child(
2755 h_flex()
2756 .id(("file-name", index))
2757 .pr_8()
2758 .gap_1p5()
2759 .max_w_full()
2760 .overflow_x_scroll()
2761 .child(file_icon)
2762 .child(h_flex().gap_0p5().children(file_name).children(file_path))
2763 .on_click({
2764 let buffer = buffer.clone();
2765 cx.listener(move |this, _, window, cx| {
2766 this.open_edited_buffer(&buffer, window, cx);
2767 })
2768 }),
2769 )
2770 .child(
2771 h_flex()
2772 .gap_1()
2773 .visible_on_hover("edited-code")
2774 .child(
2775 Button::new("review", "Review")
2776 .label_size(LabelSize::Small)
2777 .on_click({
2778 let buffer = buffer.clone();
2779 cx.listener(move |this, _, window, cx| {
2780 this.open_edited_buffer(&buffer, window, cx);
2781 })
2782 }),
2783 )
2784 .child(Divider::vertical().color(DividerColor::BorderVariant))
2785 .child(
2786 Button::new("reject-file", "Reject")
2787 .label_size(LabelSize::Small)
2788 .disabled(pending_edits)
2789 .on_click({
2790 let buffer = buffer.clone();
2791 let action_log = action_log.clone();
2792 move |_, _, cx| {
2793 action_log.update(cx, |action_log, cx| {
2794 action_log
2795 .reject_edits_in_ranges(
2796 buffer.clone(),
2797 vec![Anchor::MIN..Anchor::MAX],
2798 cx,
2799 )
2800 .detach_and_log_err(cx);
2801 })
2802 }
2803 }),
2804 )
2805 .child(
2806 Button::new("keep-file", "Keep")
2807 .label_size(LabelSize::Small)
2808 .disabled(pending_edits)
2809 .on_click({
2810 let buffer = buffer.clone();
2811 let action_log = action_log.clone();
2812 move |_, _, cx| {
2813 action_log.update(cx, |action_log, cx| {
2814 action_log.keep_edits_in_range(
2815 buffer.clone(),
2816 Anchor::MIN..Anchor::MAX,
2817 cx,
2818 );
2819 })
2820 }
2821 }),
2822 ),
2823 )
2824 .child(
2825 div()
2826 .id("gradient-overlay")
2827 .absolute()
2828 .h_full()
2829 .w_12()
2830 .top_0()
2831 .bottom_0()
2832 .right(px(152.))
2833 .bg(overlay_gradient),
2834 );
2835
2836 Some(element)
2837 },
2838 ))
2839 }
2840
2841 fn render_message_editor(&mut self, window: &mut Window, cx: &mut Context<Self>) -> AnyElement {
2842 let focus_handle = self.message_editor.focus_handle(cx);
2843 let editor_bg_color = cx.theme().colors().editor_background;
2844 let (expand_icon, expand_tooltip) = if self.editor_expanded {
2845 (IconName::Minimize, "Minimize Message Editor")
2846 } else {
2847 (IconName::Maximize, "Expand Message Editor")
2848 };
2849
2850 v_flex()
2851 .on_action(cx.listener(Self::expand_message_editor))
2852 .on_action(cx.listener(|this, _: &ToggleProfileSelector, window, cx| {
2853 if let Some(profile_selector) = this.profile_selector.as_ref() {
2854 profile_selector.read(cx).menu_handle().toggle(window, cx);
2855 }
2856 }))
2857 .on_action(cx.listener(|this, _: &ToggleModelSelector, window, cx| {
2858 if let Some(model_selector) = this.model_selector.as_ref() {
2859 model_selector
2860 .update(cx, |model_selector, cx| model_selector.toggle(window, cx));
2861 }
2862 }))
2863 .p_2()
2864 .gap_2()
2865 .border_t_1()
2866 .border_color(cx.theme().colors().border)
2867 .bg(editor_bg_color)
2868 .when(self.editor_expanded, |this| {
2869 this.h(vh(0.8, window)).size_full().justify_between()
2870 })
2871 .child(
2872 v_flex()
2873 .relative()
2874 .size_full()
2875 .pt_1()
2876 .pr_2p5()
2877 .child(self.message_editor.clone())
2878 .child(
2879 h_flex()
2880 .absolute()
2881 .top_0()
2882 .right_0()
2883 .opacity(0.5)
2884 .hover(|this| this.opacity(1.0))
2885 .child(
2886 IconButton::new("toggle-height", expand_icon)
2887 .icon_size(IconSize::Small)
2888 .icon_color(Color::Muted)
2889 .tooltip({
2890 let focus_handle = focus_handle.clone();
2891 move |window, cx| {
2892 Tooltip::for_action_in(
2893 expand_tooltip,
2894 &ExpandMessageEditor,
2895 &focus_handle,
2896 window,
2897 cx,
2898 )
2899 }
2900 })
2901 .on_click(cx.listener(|_, _, window, cx| {
2902 window.dispatch_action(Box::new(ExpandMessageEditor), cx);
2903 })),
2904 ),
2905 ),
2906 )
2907 .child(
2908 h_flex()
2909 .flex_none()
2910 .flex_wrap()
2911 .justify_between()
2912 .child(
2913 h_flex()
2914 .child(self.render_follow_toggle(cx))
2915 .children(self.render_burn_mode_toggle(cx)),
2916 )
2917 .child(
2918 h_flex()
2919 .gap_1()
2920 .children(self.render_token_usage(cx))
2921 .children(self.profile_selector.clone())
2922 .children(self.model_selector.clone())
2923 .child(self.render_send_button(cx)),
2924 ),
2925 )
2926 .into_any()
2927 }
2928
2929 pub(crate) fn as_native_connection(
2930 &self,
2931 cx: &App,
2932 ) -> Option<Rc<agent2::NativeAgentConnection>> {
2933 let acp_thread = self.thread()?.read(cx);
2934 acp_thread.connection().clone().downcast()
2935 }
2936
2937 pub(crate) fn as_native_thread(&self, cx: &App) -> Option<Entity<agent2::Thread>> {
2938 let acp_thread = self.thread()?.read(cx);
2939 self.as_native_connection(cx)?
2940 .thread(acp_thread.session_id(), cx)
2941 }
2942
2943 fn render_token_usage(&self, cx: &mut Context<Self>) -> Option<Div> {
2944 let thread = self.thread()?.read(cx);
2945 let usage = thread.token_usage()?;
2946 let is_generating = thread.status() != ThreadStatus::Idle;
2947
2948 let used = crate::text_thread_editor::humanize_token_count(usage.used_tokens);
2949 let max = crate::text_thread_editor::humanize_token_count(usage.max_tokens);
2950
2951 Some(
2952 h_flex()
2953 .flex_shrink_0()
2954 .gap_0p5()
2955 .mr_1p5()
2956 .child(
2957 Label::new(used)
2958 .size(LabelSize::Small)
2959 .color(Color::Muted)
2960 .map(|label| {
2961 if is_generating {
2962 label
2963 .with_animation(
2964 "used-tokens-label",
2965 Animation::new(Duration::from_secs(2))
2966 .repeat()
2967 .with_easing(pulsating_between(0.6, 1.)),
2968 |label, delta| label.alpha(delta),
2969 )
2970 .into_any()
2971 } else {
2972 label.into_any_element()
2973 }
2974 }),
2975 )
2976 .child(
2977 Label::new("/")
2978 .size(LabelSize::Small)
2979 .color(Color::Custom(cx.theme().colors().text_muted.opacity(0.5))),
2980 )
2981 .child(Label::new(max).size(LabelSize::Small).color(Color::Muted)),
2982 )
2983 }
2984
2985 fn toggle_burn_mode(
2986 &mut self,
2987 _: &ToggleBurnMode,
2988 _window: &mut Window,
2989 cx: &mut Context<Self>,
2990 ) {
2991 let Some(thread) = self.as_native_thread(cx) else {
2992 return;
2993 };
2994
2995 thread.update(cx, |thread, cx| {
2996 let current_mode = thread.completion_mode();
2997 thread.set_completion_mode(
2998 match current_mode {
2999 CompletionMode::Burn => CompletionMode::Normal,
3000 CompletionMode::Normal => CompletionMode::Burn,
3001 },
3002 cx,
3003 );
3004 });
3005 }
3006
3007 fn render_burn_mode_toggle(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
3008 let thread = self.as_native_thread(cx)?.read(cx);
3009
3010 if thread
3011 .model()
3012 .is_none_or(|model| !model.supports_burn_mode())
3013 {
3014 return None;
3015 }
3016
3017 let active_completion_mode = thread.completion_mode();
3018 let burn_mode_enabled = active_completion_mode == CompletionMode::Burn;
3019 let icon = if burn_mode_enabled {
3020 IconName::ZedBurnModeOn
3021 } else {
3022 IconName::ZedBurnMode
3023 };
3024
3025 Some(
3026 IconButton::new("burn-mode", icon)
3027 .icon_size(IconSize::Small)
3028 .icon_color(Color::Muted)
3029 .toggle_state(burn_mode_enabled)
3030 .selected_icon_color(Color::Error)
3031 .on_click(cx.listener(|this, _event, window, cx| {
3032 this.toggle_burn_mode(&ToggleBurnMode, window, cx);
3033 }))
3034 .tooltip(move |_window, cx| {
3035 cx.new(|_| BurnModeTooltip::new().selected(burn_mode_enabled))
3036 .into()
3037 })
3038 .into_any_element(),
3039 )
3040 }
3041
3042 fn render_send_button(&self, cx: &mut Context<Self>) -> AnyElement {
3043 let is_editor_empty = self.message_editor.read(cx).is_empty(cx);
3044 let is_generating = self
3045 .thread()
3046 .is_some_and(|thread| thread.read(cx).status() != ThreadStatus::Idle);
3047
3048 if is_generating && is_editor_empty {
3049 IconButton::new("stop-generation", IconName::Stop)
3050 .icon_color(Color::Error)
3051 .style(ButtonStyle::Tinted(ui::TintColor::Error))
3052 .tooltip(move |window, cx| {
3053 Tooltip::for_action("Stop Generation", &editor::actions::Cancel, window, cx)
3054 })
3055 .on_click(cx.listener(|this, _event, _, cx| this.cancel_generation(cx)))
3056 .into_any_element()
3057 } else {
3058 let send_btn_tooltip = if is_editor_empty && !is_generating {
3059 "Type to Send"
3060 } else if is_generating {
3061 "Stop and Send Message"
3062 } else {
3063 "Send"
3064 };
3065
3066 IconButton::new("send-message", IconName::Send)
3067 .style(ButtonStyle::Filled)
3068 .map(|this| {
3069 if is_editor_empty && !is_generating {
3070 this.disabled(true).icon_color(Color::Muted)
3071 } else {
3072 this.icon_color(Color::Accent)
3073 }
3074 })
3075 .tooltip(move |window, cx| Tooltip::for_action(send_btn_tooltip, &Chat, window, cx))
3076 .on_click(cx.listener(|this, _, window, cx| {
3077 this.send(window, cx);
3078 }))
3079 .into_any_element()
3080 }
3081 }
3082
3083 fn render_follow_toggle(&self, cx: &mut Context<Self>) -> impl IntoElement {
3084 let following = self
3085 .workspace
3086 .read_with(cx, |workspace, _| {
3087 workspace.is_being_followed(CollaboratorId::Agent)
3088 })
3089 .unwrap_or(false);
3090
3091 IconButton::new("follow-agent", IconName::Crosshair)
3092 .icon_size(IconSize::Small)
3093 .icon_color(Color::Muted)
3094 .toggle_state(following)
3095 .selected_icon_color(Some(Color::Custom(cx.theme().players().agent().cursor)))
3096 .tooltip(move |window, cx| {
3097 if following {
3098 Tooltip::for_action("Stop Following Agent", &Follow, window, cx)
3099 } else {
3100 Tooltip::with_meta(
3101 "Follow Agent",
3102 Some(&Follow),
3103 "Track the agent's location as it reads and edits files.",
3104 window,
3105 cx,
3106 )
3107 }
3108 })
3109 .on_click(cx.listener(move |this, _, window, cx| {
3110 this.workspace
3111 .update(cx, |workspace, cx| {
3112 if following {
3113 workspace.unfollow(CollaboratorId::Agent, window, cx);
3114 } else {
3115 workspace.follow(CollaboratorId::Agent, window, cx);
3116 }
3117 })
3118 .ok();
3119 }))
3120 }
3121
3122 fn render_markdown(&self, markdown: Entity<Markdown>, style: MarkdownStyle) -> MarkdownElement {
3123 let workspace = self.workspace.clone();
3124 MarkdownElement::new(markdown, style).on_url_click(move |text, window, cx| {
3125 Self::open_link(text, &workspace, window, cx);
3126 })
3127 }
3128
3129 fn open_link(
3130 url: SharedString,
3131 workspace: &WeakEntity<Workspace>,
3132 window: &mut Window,
3133 cx: &mut App,
3134 ) {
3135 let Some(workspace) = workspace.upgrade() else {
3136 cx.open_url(&url);
3137 return;
3138 };
3139
3140 if let Some(mention) = MentionUri::parse(&url).log_err() {
3141 workspace.update(cx, |workspace, cx| match mention {
3142 MentionUri::File { abs_path } => {
3143 let project = workspace.project();
3144 let Some(path) =
3145 project.update(cx, |project, cx| project.find_project_path(abs_path, cx))
3146 else {
3147 return;
3148 };
3149
3150 workspace
3151 .open_path(path, None, true, window, cx)
3152 .detach_and_log_err(cx);
3153 }
3154 MentionUri::Directory { abs_path } => {
3155 let project = workspace.project();
3156 let Some(entry) = project.update(cx, |project, cx| {
3157 let path = project.find_project_path(abs_path, cx)?;
3158 project.entry_for_path(&path, cx)
3159 }) else {
3160 return;
3161 };
3162
3163 project.update(cx, |_, cx| {
3164 cx.emit(project::Event::RevealInProjectPanel(entry.id));
3165 });
3166 }
3167 MentionUri::Symbol {
3168 path, line_range, ..
3169 }
3170 | MentionUri::Selection { path, line_range } => {
3171 let project = workspace.project();
3172 let Some((path, _)) = project.update(cx, |project, cx| {
3173 let path = project.find_project_path(path, cx)?;
3174 let entry = project.entry_for_path(&path, cx)?;
3175 Some((path, entry))
3176 }) else {
3177 return;
3178 };
3179
3180 let item = workspace.open_path(path, None, true, window, cx);
3181 window
3182 .spawn(cx, async move |cx| {
3183 let Some(editor) = item.await?.downcast::<Editor>() else {
3184 return Ok(());
3185 };
3186 let range =
3187 Point::new(line_range.start, 0)..Point::new(line_range.start, 0);
3188 editor
3189 .update_in(cx, |editor, window, cx| {
3190 editor.change_selections(
3191 SelectionEffects::scroll(Autoscroll::center()),
3192 window,
3193 cx,
3194 |s| s.select_ranges(vec![range]),
3195 );
3196 })
3197 .ok();
3198 anyhow::Ok(())
3199 })
3200 .detach_and_log_err(cx);
3201 }
3202 MentionUri::Thread { id, .. } => {
3203 if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
3204 panel.update(cx, |panel, cx| {
3205 panel
3206 .open_thread_by_id(&id, window, cx)
3207 .detach_and_log_err(cx)
3208 });
3209 }
3210 }
3211 MentionUri::TextThread { path, .. } => {
3212 if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
3213 panel.update(cx, |panel, cx| {
3214 panel
3215 .open_saved_prompt_editor(path.as_path().into(), window, cx)
3216 .detach_and_log_err(cx);
3217 });
3218 }
3219 }
3220 MentionUri::Rule { id, .. } => {
3221 let PromptId::User { uuid } = id else {
3222 return;
3223 };
3224 window.dispatch_action(
3225 Box::new(OpenRulesLibrary {
3226 prompt_to_select: Some(uuid.0),
3227 }),
3228 cx,
3229 )
3230 }
3231 MentionUri::Fetch { url } => {
3232 cx.open_url(url.as_str());
3233 }
3234 })
3235 } else {
3236 cx.open_url(&url);
3237 }
3238 }
3239
3240 fn open_tool_call_location(
3241 &self,
3242 entry_ix: usize,
3243 location_ix: usize,
3244 window: &mut Window,
3245 cx: &mut Context<Self>,
3246 ) -> Option<()> {
3247 let (tool_call_location, agent_location) = self
3248 .thread()?
3249 .read(cx)
3250 .entries()
3251 .get(entry_ix)?
3252 .location(location_ix)?;
3253
3254 let project_path = self
3255 .project
3256 .read(cx)
3257 .find_project_path(&tool_call_location.path, cx)?;
3258
3259 let open_task = self
3260 .workspace
3261 .update(cx, |workspace, cx| {
3262 workspace.open_path(project_path, None, true, window, cx)
3263 })
3264 .log_err()?;
3265 window
3266 .spawn(cx, async move |cx| {
3267 let item = open_task.await?;
3268
3269 let Some(active_editor) = item.downcast::<Editor>() else {
3270 return anyhow::Ok(());
3271 };
3272
3273 active_editor.update_in(cx, |editor, window, cx| {
3274 let multibuffer = editor.buffer().read(cx);
3275 let buffer = multibuffer.as_singleton();
3276 if agent_location.buffer.upgrade() == buffer {
3277 let excerpt_id = multibuffer.excerpt_ids().first().cloned();
3278 let anchor = editor::Anchor::in_buffer(
3279 excerpt_id.unwrap(),
3280 buffer.unwrap().read(cx).remote_id(),
3281 agent_location.position,
3282 );
3283 editor.change_selections(Default::default(), window, cx, |selections| {
3284 selections.select_anchor_ranges([anchor..anchor]);
3285 })
3286 } else {
3287 let row = tool_call_location.line.unwrap_or_default();
3288 editor.change_selections(Default::default(), window, cx, |selections| {
3289 selections.select_ranges([Point::new(row, 0)..Point::new(row, 0)]);
3290 })
3291 }
3292 })?;
3293
3294 anyhow::Ok(())
3295 })
3296 .detach_and_log_err(cx);
3297
3298 None
3299 }
3300
3301 pub fn open_thread_as_markdown(
3302 &self,
3303 workspace: Entity<Workspace>,
3304 window: &mut Window,
3305 cx: &mut App,
3306 ) -> Task<anyhow::Result<()>> {
3307 let markdown_language_task = workspace
3308 .read(cx)
3309 .app_state()
3310 .languages
3311 .language_for_name("Markdown");
3312
3313 let (thread_summary, markdown) = if let Some(thread) = self.thread() {
3314 let thread = thread.read(cx);
3315 (thread.title().to_string(), thread.to_markdown(cx))
3316 } else {
3317 return Task::ready(Ok(()));
3318 };
3319
3320 window.spawn(cx, async move |cx| {
3321 let markdown_language = markdown_language_task.await?;
3322
3323 workspace.update_in(cx, |workspace, window, cx| {
3324 let project = workspace.project().clone();
3325
3326 if !project.read(cx).is_local() {
3327 bail!("failed to open active thread as markdown in remote project");
3328 }
3329
3330 let buffer = project.update(cx, |project, cx| {
3331 project.create_local_buffer(&markdown, Some(markdown_language), cx)
3332 });
3333 let buffer = cx.new(|cx| {
3334 MultiBuffer::singleton(buffer, cx).with_title(thread_summary.clone())
3335 });
3336
3337 workspace.add_item_to_active_pane(
3338 Box::new(cx.new(|cx| {
3339 let mut editor =
3340 Editor::for_multibuffer(buffer, Some(project.clone()), window, cx);
3341 editor.set_breadcrumb_header(thread_summary);
3342 editor
3343 })),
3344 None,
3345 true,
3346 window,
3347 cx,
3348 );
3349
3350 anyhow::Ok(())
3351 })??;
3352 anyhow::Ok(())
3353 })
3354 }
3355
3356 fn scroll_to_top(&mut self, cx: &mut Context<Self>) {
3357 self.list_state.scroll_to(ListOffset::default());
3358 cx.notify();
3359 }
3360
3361 pub fn scroll_to_bottom(&mut self, cx: &mut Context<Self>) {
3362 if let Some(thread) = self.thread() {
3363 let entry_count = thread.read(cx).entries().len();
3364 self.list_state.reset(entry_count);
3365 cx.notify();
3366 }
3367 }
3368
3369 fn notify_with_sound(
3370 &mut self,
3371 caption: impl Into<SharedString>,
3372 icon: IconName,
3373 window: &mut Window,
3374 cx: &mut Context<Self>,
3375 ) {
3376 self.play_notification_sound(window, cx);
3377 self.show_notification(caption, icon, window, cx);
3378 }
3379
3380 fn play_notification_sound(&self, window: &Window, cx: &mut App) {
3381 let settings = AgentSettings::get_global(cx);
3382 if settings.play_sound_when_agent_done && !window.is_window_active() {
3383 Audio::play_sound(Sound::AgentDone, cx);
3384 }
3385 }
3386
3387 fn show_notification(
3388 &mut self,
3389 caption: impl Into<SharedString>,
3390 icon: IconName,
3391 window: &mut Window,
3392 cx: &mut Context<Self>,
3393 ) {
3394 if window.is_window_active() || !self.notifications.is_empty() {
3395 return;
3396 }
3397
3398 let title = self.title(cx);
3399
3400 match AgentSettings::get_global(cx).notify_when_agent_waiting {
3401 NotifyWhenAgentWaiting::PrimaryScreen => {
3402 if let Some(primary) = cx.primary_display() {
3403 self.pop_up(icon, caption.into(), title, window, primary, cx);
3404 }
3405 }
3406 NotifyWhenAgentWaiting::AllScreens => {
3407 let caption = caption.into();
3408 for screen in cx.displays() {
3409 self.pop_up(icon, caption.clone(), title.clone(), window, screen, cx);
3410 }
3411 }
3412 NotifyWhenAgentWaiting::Never => {
3413 // Don't show anything
3414 }
3415 }
3416 }
3417
3418 fn pop_up(
3419 &mut self,
3420 icon: IconName,
3421 caption: SharedString,
3422 title: SharedString,
3423 window: &mut Window,
3424 screen: Rc<dyn PlatformDisplay>,
3425 cx: &mut Context<Self>,
3426 ) {
3427 let options = AgentNotification::window_options(screen, cx);
3428
3429 let project_name = self.workspace.upgrade().and_then(|workspace| {
3430 workspace
3431 .read(cx)
3432 .project()
3433 .read(cx)
3434 .visible_worktrees(cx)
3435 .next()
3436 .map(|worktree| worktree.read(cx).root_name().to_string())
3437 });
3438
3439 if let Some(screen_window) = cx
3440 .open_window(options, |_, cx| {
3441 cx.new(|_| {
3442 AgentNotification::new(title.clone(), caption.clone(), icon, project_name)
3443 })
3444 })
3445 .log_err()
3446 && let Some(pop_up) = screen_window.entity(cx).log_err()
3447 {
3448 self.notification_subscriptions
3449 .entry(screen_window)
3450 .or_insert_with(Vec::new)
3451 .push(cx.subscribe_in(&pop_up, window, {
3452 |this, _, event, window, cx| match event {
3453 AgentNotificationEvent::Accepted => {
3454 let handle = window.window_handle();
3455 cx.activate(true);
3456
3457 let workspace_handle = this.workspace.clone();
3458
3459 // If there are multiple Zed windows, activate the correct one.
3460 cx.defer(move |cx| {
3461 handle
3462 .update(cx, |_view, window, _cx| {
3463 window.activate_window();
3464
3465 if let Some(workspace) = workspace_handle.upgrade() {
3466 workspace.update(_cx, |workspace, cx| {
3467 workspace.focus_panel::<AgentPanel>(window, cx);
3468 });
3469 }
3470 })
3471 .log_err();
3472 });
3473
3474 this.dismiss_notifications(cx);
3475 }
3476 AgentNotificationEvent::Dismissed => {
3477 this.dismiss_notifications(cx);
3478 }
3479 }
3480 }));
3481
3482 self.notifications.push(screen_window);
3483
3484 // If the user manually refocuses the original window, dismiss the popup.
3485 self.notification_subscriptions
3486 .entry(screen_window)
3487 .or_insert_with(Vec::new)
3488 .push({
3489 let pop_up_weak = pop_up.downgrade();
3490
3491 cx.observe_window_activation(window, move |_, window, cx| {
3492 if window.is_window_active()
3493 && let Some(pop_up) = pop_up_weak.upgrade()
3494 {
3495 pop_up.update(cx, |_, cx| {
3496 cx.emit(AgentNotificationEvent::Dismissed);
3497 });
3498 }
3499 })
3500 });
3501 }
3502 }
3503
3504 fn dismiss_notifications(&mut self, cx: &mut Context<Self>) {
3505 for window in self.notifications.drain(..) {
3506 window
3507 .update(cx, |_, window, _| {
3508 window.remove_window();
3509 })
3510 .ok();
3511
3512 self.notification_subscriptions.remove(&window);
3513 }
3514 }
3515
3516 fn render_thread_controls(&self, cx: &Context<Self>) -> impl IntoElement {
3517 let open_as_markdown = IconButton::new("open-as-markdown", IconName::FileMarkdown)
3518 .shape(ui::IconButtonShape::Square)
3519 .icon_size(IconSize::Small)
3520 .icon_color(Color::Ignored)
3521 .tooltip(Tooltip::text("Open Thread as Markdown"))
3522 .on_click(cx.listener(move |this, _, window, cx| {
3523 if let Some(workspace) = this.workspace.upgrade() {
3524 this.open_thread_as_markdown(workspace, window, cx)
3525 .detach_and_log_err(cx);
3526 }
3527 }));
3528
3529 let scroll_to_top = IconButton::new("scroll_to_top", IconName::ArrowUp)
3530 .shape(ui::IconButtonShape::Square)
3531 .icon_size(IconSize::Small)
3532 .icon_color(Color::Ignored)
3533 .tooltip(Tooltip::text("Scroll To Top"))
3534 .on_click(cx.listener(move |this, _, _, cx| {
3535 this.scroll_to_top(cx);
3536 }));
3537
3538 h_flex()
3539 .w_full()
3540 .mr_1()
3541 .pb_2()
3542 .px(RESPONSE_PADDING_X)
3543 .opacity(0.4)
3544 .hover(|style| style.opacity(1.))
3545 .flex_wrap()
3546 .justify_end()
3547 .child(open_as_markdown)
3548 .child(scroll_to_top)
3549 }
3550
3551 fn render_vertical_scrollbar(&self, cx: &mut Context<Self>) -> Stateful<Div> {
3552 div()
3553 .id("acp-thread-scrollbar")
3554 .occlude()
3555 .on_mouse_move(cx.listener(|_, _, _, cx| {
3556 cx.notify();
3557 cx.stop_propagation()
3558 }))
3559 .on_hover(|_, _, cx| {
3560 cx.stop_propagation();
3561 })
3562 .on_any_mouse_down(|_, _, cx| {
3563 cx.stop_propagation();
3564 })
3565 .on_mouse_up(
3566 MouseButton::Left,
3567 cx.listener(|_, _, _, cx| {
3568 cx.stop_propagation();
3569 }),
3570 )
3571 .on_scroll_wheel(cx.listener(|_, _, _, cx| {
3572 cx.notify();
3573 }))
3574 .h_full()
3575 .absolute()
3576 .right_1()
3577 .top_1()
3578 .bottom_0()
3579 .w(px(12.))
3580 .cursor_default()
3581 .children(Scrollbar::vertical(self.scrollbar_state.clone()).map(|s| s.auto_hide(cx)))
3582 }
3583
3584 fn settings_changed(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
3585 self.entry_view_state.update(cx, |entry_view_state, cx| {
3586 entry_view_state.settings_changed(cx);
3587 });
3588 }
3589
3590 pub(crate) fn insert_dragged_files(
3591 &self,
3592 paths: Vec<project::ProjectPath>,
3593 added_worktrees: Vec<Entity<project::Worktree>>,
3594 window: &mut Window,
3595 cx: &mut Context<Self>,
3596 ) {
3597 self.message_editor.update(cx, |message_editor, cx| {
3598 message_editor.insert_dragged_files(paths, added_worktrees, window, cx);
3599 })
3600 }
3601
3602 fn render_thread_retry_status_callout(
3603 &self,
3604 _window: &mut Window,
3605 _cx: &mut Context<Self>,
3606 ) -> Option<Callout> {
3607 let state = self.thread_retry_status.as_ref()?;
3608
3609 let next_attempt_in = state
3610 .duration
3611 .saturating_sub(Instant::now().saturating_duration_since(state.started_at));
3612 if next_attempt_in.is_zero() {
3613 return None;
3614 }
3615
3616 let next_attempt_in_secs = next_attempt_in.as_secs() + 1;
3617
3618 let retry_message = if state.max_attempts == 1 {
3619 if next_attempt_in_secs == 1 {
3620 "Retrying. Next attempt in 1 second.".to_string()
3621 } else {
3622 format!("Retrying. Next attempt in {next_attempt_in_secs} seconds.")
3623 }
3624 } else if next_attempt_in_secs == 1 {
3625 format!(
3626 "Retrying. Next attempt in 1 second (Attempt {} of {}).",
3627 state.attempt, state.max_attempts,
3628 )
3629 } else {
3630 format!(
3631 "Retrying. Next attempt in {next_attempt_in_secs} seconds (Attempt {} of {}).",
3632 state.attempt, state.max_attempts,
3633 )
3634 };
3635
3636 Some(
3637 Callout::new()
3638 .severity(Severity::Warning)
3639 .title(state.last_error.clone())
3640 .description(retry_message),
3641 )
3642 }
3643
3644 fn render_thread_error(&self, window: &mut Window, cx: &mut Context<Self>) -> Option<Div> {
3645 let content = match self.thread_error.as_ref()? {
3646 ThreadError::Other(error) => self.render_any_thread_error(error.clone(), cx),
3647 ThreadError::PaymentRequired => self.render_payment_required_error(cx),
3648 ThreadError::ModelRequestLimitReached(plan) => {
3649 self.render_model_request_limit_reached_error(*plan, cx)
3650 }
3651 ThreadError::ToolUseLimitReached => {
3652 self.render_tool_use_limit_reached_error(window, cx)?
3653 }
3654 };
3655
3656 Some(div().child(content))
3657 }
3658
3659 fn render_any_thread_error(&self, error: SharedString, cx: &mut Context<'_, Self>) -> Callout {
3660 Callout::new()
3661 .severity(Severity::Error)
3662 .title("Error")
3663 .description(error.clone())
3664 .actions_slot(self.create_copy_button(error.to_string()))
3665 .dismiss_action(self.dismiss_error_button(cx))
3666 }
3667
3668 fn render_payment_required_error(&self, cx: &mut Context<Self>) -> Callout {
3669 const ERROR_MESSAGE: &str =
3670 "You reached your free usage limit. Upgrade to Zed Pro for more prompts.";
3671
3672 Callout::new()
3673 .severity(Severity::Error)
3674 .title("Free Usage Exceeded")
3675 .description(ERROR_MESSAGE)
3676 .actions_slot(
3677 h_flex()
3678 .gap_0p5()
3679 .child(self.upgrade_button(cx))
3680 .child(self.create_copy_button(ERROR_MESSAGE)),
3681 )
3682 .dismiss_action(self.dismiss_error_button(cx))
3683 }
3684
3685 fn render_model_request_limit_reached_error(
3686 &self,
3687 plan: cloud_llm_client::Plan,
3688 cx: &mut Context<Self>,
3689 ) -> Callout {
3690 let error_message = match plan {
3691 cloud_llm_client::Plan::ZedPro => "Upgrade to usage-based billing for more prompts.",
3692 cloud_llm_client::Plan::ZedProTrial | cloud_llm_client::Plan::ZedFree => {
3693 "Upgrade to Zed Pro for more prompts."
3694 }
3695 };
3696
3697 Callout::new()
3698 .severity(Severity::Error)
3699 .title("Model Prompt Limit Reached")
3700 .description(error_message)
3701 .actions_slot(
3702 h_flex()
3703 .gap_0p5()
3704 .child(self.upgrade_button(cx))
3705 .child(self.create_copy_button(error_message)),
3706 )
3707 .dismiss_action(self.dismiss_error_button(cx))
3708 }
3709
3710 fn render_tool_use_limit_reached_error(
3711 &self,
3712 window: &mut Window,
3713 cx: &mut Context<Self>,
3714 ) -> Option<Callout> {
3715 let thread = self.as_native_thread(cx)?;
3716 let supports_burn_mode = thread
3717 .read(cx)
3718 .model()
3719 .is_some_and(|model| model.supports_burn_mode());
3720
3721 let focus_handle = self.focus_handle(cx);
3722
3723 Some(
3724 Callout::new()
3725 .icon(IconName::Info)
3726 .title("Consecutive tool use limit reached.")
3727 .actions_slot(
3728 h_flex()
3729 .gap_0p5()
3730 .when(supports_burn_mode, |this| {
3731 this.child(
3732 Button::new("continue-burn-mode", "Continue with Burn Mode")
3733 .style(ButtonStyle::Filled)
3734 .style(ButtonStyle::Tinted(ui::TintColor::Accent))
3735 .layer(ElevationIndex::ModalSurface)
3736 .label_size(LabelSize::Small)
3737 .key_binding(
3738 KeyBinding::for_action_in(
3739 &ContinueWithBurnMode,
3740 &focus_handle,
3741 window,
3742 cx,
3743 )
3744 .map(|kb| kb.size(rems_from_px(10.))),
3745 )
3746 .tooltip(Tooltip::text(
3747 "Enable Burn Mode for unlimited tool use.",
3748 ))
3749 .on_click({
3750 cx.listener(move |this, _, _window, cx| {
3751 thread.update(cx, |thread, cx| {
3752 thread
3753 .set_completion_mode(CompletionMode::Burn, cx);
3754 });
3755 this.resume_chat(cx);
3756 })
3757 }),
3758 )
3759 })
3760 .child(
3761 Button::new("continue-conversation", "Continue")
3762 .layer(ElevationIndex::ModalSurface)
3763 .label_size(LabelSize::Small)
3764 .key_binding(
3765 KeyBinding::for_action_in(
3766 &ContinueThread,
3767 &focus_handle,
3768 window,
3769 cx,
3770 )
3771 .map(|kb| kb.size(rems_from_px(10.))),
3772 )
3773 .on_click(cx.listener(|this, _, _window, cx| {
3774 this.resume_chat(cx);
3775 })),
3776 ),
3777 ),
3778 )
3779 }
3780
3781 fn create_copy_button(&self, message: impl Into<String>) -> impl IntoElement {
3782 let message = message.into();
3783
3784 IconButton::new("copy", IconName::Copy)
3785 .icon_size(IconSize::Small)
3786 .icon_color(Color::Muted)
3787 .tooltip(Tooltip::text("Copy Error Message"))
3788 .on_click(move |_, _, cx| {
3789 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
3790 })
3791 }
3792
3793 fn dismiss_error_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
3794 IconButton::new("dismiss", IconName::Close)
3795 .icon_size(IconSize::Small)
3796 .icon_color(Color::Muted)
3797 .tooltip(Tooltip::text("Dismiss Error"))
3798 .on_click(cx.listener({
3799 move |this, _, _, cx| {
3800 this.clear_thread_error(cx);
3801 cx.notify();
3802 }
3803 }))
3804 }
3805
3806 fn upgrade_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
3807 Button::new("upgrade", "Upgrade")
3808 .label_size(LabelSize::Small)
3809 .style(ButtonStyle::Tinted(ui::TintColor::Accent))
3810 .on_click(cx.listener({
3811 move |this, _, _, cx| {
3812 this.clear_thread_error(cx);
3813 cx.open_url(&zed_urls::upgrade_to_zed_pro_url(cx));
3814 }
3815 }))
3816 }
3817
3818 fn reset(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3819 self.thread_state = Self::initial_state(
3820 self.agent.clone(),
3821 None,
3822 self.workspace.clone(),
3823 self.project.clone(),
3824 window,
3825 cx,
3826 );
3827 cx.notify();
3828 }
3829}
3830
3831impl Focusable for AcpThreadView {
3832 fn focus_handle(&self, cx: &App) -> FocusHandle {
3833 self.message_editor.focus_handle(cx)
3834 }
3835}
3836
3837impl Render for AcpThreadView {
3838 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
3839 let has_messages = self.list_state.item_count() > 0;
3840
3841 v_flex()
3842 .size_full()
3843 .key_context("AcpThread")
3844 .on_action(cx.listener(Self::open_agent_diff))
3845 .on_action(cx.listener(Self::toggle_burn_mode))
3846 .bg(cx.theme().colors().panel_background)
3847 .child(match &self.thread_state {
3848 ThreadState::Unauthenticated {
3849 connection,
3850 description,
3851 configuration_view,
3852 ..
3853 } => self.render_auth_required_state(
3854 connection,
3855 description.as_ref(),
3856 configuration_view.as_ref(),
3857 window,
3858 cx,
3859 ),
3860 ThreadState::Loading { .. } => v_flex().flex_1().child(self.render_empty_state(cx)),
3861 ThreadState::LoadError(e) => v_flex()
3862 .p_2()
3863 .flex_1()
3864 .items_center()
3865 .justify_center()
3866 .child(self.render_load_error(e, cx)),
3867 ThreadState::Ready { thread, .. } => {
3868 let thread_clone = thread.clone();
3869
3870 v_flex().flex_1().map(|this| {
3871 if has_messages {
3872 this.child(
3873 list(
3874 self.list_state.clone(),
3875 cx.processor(|this, index: usize, window, cx| {
3876 let Some((entry, len)) = this.thread().and_then(|thread| {
3877 let entries = &thread.read(cx).entries();
3878 Some((entries.get(index)?, entries.len()))
3879 }) else {
3880 return Empty.into_any();
3881 };
3882 this.render_entry(index, len, entry, window, cx)
3883 }),
3884 )
3885 .with_sizing_behavior(gpui::ListSizingBehavior::Auto)
3886 .flex_grow()
3887 .into_any(),
3888 )
3889 .child(self.render_vertical_scrollbar(cx))
3890 .children(
3891 match thread_clone.read(cx).status() {
3892 ThreadStatus::Idle
3893 | ThreadStatus::WaitingForToolConfirmation => None,
3894 ThreadStatus::Generating => div()
3895 .px_5()
3896 .py_2()
3897 .child(LoadingLabel::new("").size(LabelSize::Small))
3898 .into(),
3899 },
3900 )
3901 } else {
3902 this.child(self.render_empty_state(cx))
3903 }
3904 })
3905 }
3906 })
3907 // The activity bar is intentionally rendered outside of the ThreadState::Ready match
3908 // above so that the scrollbar doesn't render behind it. The current setup allows
3909 // the scrollbar to stop exactly at the activity bar start.
3910 .when(has_messages, |this| match &self.thread_state {
3911 ThreadState::Ready { thread, .. } => {
3912 this.children(self.render_activity_bar(thread, window, cx))
3913 }
3914 _ => this,
3915 })
3916 .children(self.render_thread_retry_status_callout(window, cx))
3917 .children(self.render_thread_error(window, cx))
3918 .child(self.render_message_editor(window, cx))
3919 }
3920}
3921
3922fn default_markdown_style(buffer_font: bool, window: &Window, cx: &App) -> MarkdownStyle {
3923 let theme_settings = ThemeSettings::get_global(cx);
3924 let colors = cx.theme().colors();
3925
3926 let buffer_font_size = TextSize::Small.rems(cx);
3927
3928 let mut text_style = window.text_style();
3929 let line_height = buffer_font_size * 1.75;
3930
3931 let font_family = if buffer_font {
3932 theme_settings.buffer_font.family.clone()
3933 } else {
3934 theme_settings.ui_font.family.clone()
3935 };
3936
3937 let font_size = if buffer_font {
3938 TextSize::Small.rems(cx)
3939 } else {
3940 TextSize::Default.rems(cx)
3941 };
3942
3943 text_style.refine(&TextStyleRefinement {
3944 font_family: Some(font_family),
3945 font_fallbacks: theme_settings.ui_font.fallbacks.clone(),
3946 font_features: Some(theme_settings.ui_font.features.clone()),
3947 font_size: Some(font_size.into()),
3948 line_height: Some(line_height.into()),
3949 color: Some(cx.theme().colors().text),
3950 ..Default::default()
3951 });
3952
3953 MarkdownStyle {
3954 base_text_style: text_style.clone(),
3955 syntax: cx.theme().syntax().clone(),
3956 selection_background_color: cx.theme().colors().element_selection_background,
3957 code_block_overflow_x_scroll: true,
3958 table_overflow_x_scroll: true,
3959 heading_level_styles: Some(HeadingLevelStyles {
3960 h1: Some(TextStyleRefinement {
3961 font_size: Some(rems(1.15).into()),
3962 ..Default::default()
3963 }),
3964 h2: Some(TextStyleRefinement {
3965 font_size: Some(rems(1.1).into()),
3966 ..Default::default()
3967 }),
3968 h3: Some(TextStyleRefinement {
3969 font_size: Some(rems(1.05).into()),
3970 ..Default::default()
3971 }),
3972 h4: Some(TextStyleRefinement {
3973 font_size: Some(rems(1.).into()),
3974 ..Default::default()
3975 }),
3976 h5: Some(TextStyleRefinement {
3977 font_size: Some(rems(0.95).into()),
3978 ..Default::default()
3979 }),
3980 h6: Some(TextStyleRefinement {
3981 font_size: Some(rems(0.875).into()),
3982 ..Default::default()
3983 }),
3984 }),
3985 code_block: StyleRefinement {
3986 padding: EdgesRefinement {
3987 top: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
3988 left: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
3989 right: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
3990 bottom: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
3991 },
3992 margin: EdgesRefinement {
3993 top: Some(Length::Definite(Pixels(8.).into())),
3994 left: Some(Length::Definite(Pixels(0.).into())),
3995 right: Some(Length::Definite(Pixels(0.).into())),
3996 bottom: Some(Length::Definite(Pixels(12.).into())),
3997 },
3998 border_style: Some(BorderStyle::Solid),
3999 border_widths: EdgesRefinement {
4000 top: Some(AbsoluteLength::Pixels(Pixels(1.))),
4001 left: Some(AbsoluteLength::Pixels(Pixels(1.))),
4002 right: Some(AbsoluteLength::Pixels(Pixels(1.))),
4003 bottom: Some(AbsoluteLength::Pixels(Pixels(1.))),
4004 },
4005 border_color: Some(colors.border_variant),
4006 background: Some(colors.editor_background.into()),
4007 text: Some(TextStyleRefinement {
4008 font_family: Some(theme_settings.buffer_font.family.clone()),
4009 font_fallbacks: theme_settings.buffer_font.fallbacks.clone(),
4010 font_features: Some(theme_settings.buffer_font.features.clone()),
4011 font_size: Some(buffer_font_size.into()),
4012 ..Default::default()
4013 }),
4014 ..Default::default()
4015 },
4016 inline_code: TextStyleRefinement {
4017 font_family: Some(theme_settings.buffer_font.family.clone()),
4018 font_fallbacks: theme_settings.buffer_font.fallbacks.clone(),
4019 font_features: Some(theme_settings.buffer_font.features.clone()),
4020 font_size: Some(buffer_font_size.into()),
4021 background_color: Some(colors.editor_foreground.opacity(0.08)),
4022 ..Default::default()
4023 },
4024 link: TextStyleRefinement {
4025 background_color: Some(colors.editor_foreground.opacity(0.025)),
4026 underline: Some(UnderlineStyle {
4027 color: Some(colors.text_accent.opacity(0.5)),
4028 thickness: px(1.),
4029 ..Default::default()
4030 }),
4031 ..Default::default()
4032 },
4033 ..Default::default()
4034 }
4035}
4036
4037fn plan_label_markdown_style(
4038 status: &acp::PlanEntryStatus,
4039 window: &Window,
4040 cx: &App,
4041) -> MarkdownStyle {
4042 let default_md_style = default_markdown_style(false, window, cx);
4043
4044 MarkdownStyle {
4045 base_text_style: TextStyle {
4046 color: cx.theme().colors().text_muted,
4047 strikethrough: if matches!(status, acp::PlanEntryStatus::Completed) {
4048 Some(gpui::StrikethroughStyle {
4049 thickness: px(1.),
4050 color: Some(cx.theme().colors().text_muted.opacity(0.8)),
4051 })
4052 } else {
4053 None
4054 },
4055 ..default_md_style.base_text_style
4056 },
4057 ..default_md_style
4058 }
4059}
4060
4061fn terminal_command_markdown_style(window: &Window, cx: &App) -> MarkdownStyle {
4062 let default_md_style = default_markdown_style(true, window, cx);
4063
4064 MarkdownStyle {
4065 base_text_style: TextStyle {
4066 ..default_md_style.base_text_style
4067 },
4068 selection_background_color: cx.theme().colors().element_selection_background,
4069 ..Default::default()
4070 }
4071}
4072
4073#[cfg(test)]
4074pub(crate) mod tests {
4075 use acp_thread::StubAgentConnection;
4076 use agent::{TextThreadStore, ThreadStore};
4077 use agent_client_protocol::SessionId;
4078 use assistant_context::ContextStore;
4079 use editor::EditorSettings;
4080 use fs::FakeFs;
4081 use gpui::{EventEmitter, SemanticVersion, TestAppContext, VisualTestContext};
4082 use project::Project;
4083 use serde_json::json;
4084 use settings::SettingsStore;
4085 use std::any::Any;
4086 use std::path::Path;
4087 use workspace::Item;
4088
4089 use super::*;
4090
4091 #[gpui::test]
4092 async fn test_drop(cx: &mut TestAppContext) {
4093 init_test(cx);
4094
4095 let (thread_view, _cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
4096 let weak_view = thread_view.downgrade();
4097 drop(thread_view);
4098 assert!(!weak_view.is_upgradable());
4099 }
4100
4101 #[gpui::test]
4102 async fn test_notification_for_stop_event(cx: &mut TestAppContext) {
4103 init_test(cx);
4104
4105 let (thread_view, cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
4106
4107 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
4108 message_editor.update_in(cx, |editor, window, cx| {
4109 editor.set_text("Hello", window, cx);
4110 });
4111
4112 cx.deactivate_window();
4113
4114 thread_view.update_in(cx, |thread_view, window, cx| {
4115 thread_view.send(window, cx);
4116 });
4117
4118 cx.run_until_parked();
4119
4120 assert!(
4121 cx.windows()
4122 .iter()
4123 .any(|window| window.downcast::<AgentNotification>().is_some())
4124 );
4125 }
4126
4127 #[gpui::test]
4128 async fn test_notification_for_error(cx: &mut TestAppContext) {
4129 init_test(cx);
4130
4131 let (thread_view, cx) =
4132 setup_thread_view(StubAgentServer::new(SaboteurAgentConnection), cx).await;
4133
4134 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
4135 message_editor.update_in(cx, |editor, window, cx| {
4136 editor.set_text("Hello", window, cx);
4137 });
4138
4139 cx.deactivate_window();
4140
4141 thread_view.update_in(cx, |thread_view, window, cx| {
4142 thread_view.send(window, cx);
4143 });
4144
4145 cx.run_until_parked();
4146
4147 assert!(
4148 cx.windows()
4149 .iter()
4150 .any(|window| window.downcast::<AgentNotification>().is_some())
4151 );
4152 }
4153
4154 #[gpui::test]
4155 async fn test_notification_for_tool_authorization(cx: &mut TestAppContext) {
4156 init_test(cx);
4157
4158 let tool_call_id = acp::ToolCallId("1".into());
4159 let tool_call = acp::ToolCall {
4160 id: tool_call_id.clone(),
4161 title: "Label".into(),
4162 kind: acp::ToolKind::Edit,
4163 status: acp::ToolCallStatus::Pending,
4164 content: vec!["hi".into()],
4165 locations: vec![],
4166 raw_input: None,
4167 raw_output: None,
4168 };
4169 let connection =
4170 StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
4171 tool_call_id,
4172 vec![acp::PermissionOption {
4173 id: acp::PermissionOptionId("1".into()),
4174 name: "Allow".into(),
4175 kind: acp::PermissionOptionKind::AllowOnce,
4176 }],
4177 )]));
4178
4179 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
4180
4181 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
4182
4183 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
4184 message_editor.update_in(cx, |editor, window, cx| {
4185 editor.set_text("Hello", window, cx);
4186 });
4187
4188 cx.deactivate_window();
4189
4190 thread_view.update_in(cx, |thread_view, window, cx| {
4191 thread_view.send(window, cx);
4192 });
4193
4194 cx.run_until_parked();
4195
4196 assert!(
4197 cx.windows()
4198 .iter()
4199 .any(|window| window.downcast::<AgentNotification>().is_some())
4200 );
4201 }
4202
4203 async fn setup_thread_view(
4204 agent: impl AgentServer + 'static,
4205 cx: &mut TestAppContext,
4206 ) -> (Entity<AcpThreadView>, &mut VisualTestContext) {
4207 let fs = FakeFs::new(cx.executor());
4208 let project = Project::test(fs, [], cx).await;
4209 let (workspace, cx) =
4210 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4211
4212 let thread_store =
4213 cx.update(|_window, cx| cx.new(|cx| ThreadStore::fake(project.clone(), cx)));
4214 let text_thread_store =
4215 cx.update(|_window, cx| cx.new(|cx| TextThreadStore::fake(project.clone(), cx)));
4216 let context_store =
4217 cx.update(|_window, cx| cx.new(|cx| ContextStore::fake(project.clone(), cx)));
4218 let history_store =
4219 cx.update(|_window, cx| cx.new(|cx| HistoryStore::new(context_store, cx)));
4220
4221 let thread_view = cx.update(|window, cx| {
4222 cx.new(|cx| {
4223 AcpThreadView::new(
4224 Rc::new(agent),
4225 None,
4226 workspace.downgrade(),
4227 project,
4228 history_store,
4229 thread_store.clone(),
4230 text_thread_store.clone(),
4231 window,
4232 cx,
4233 )
4234 })
4235 });
4236 cx.run_until_parked();
4237 (thread_view, cx)
4238 }
4239
4240 fn add_to_workspace(thread_view: Entity<AcpThreadView>, cx: &mut VisualTestContext) {
4241 let workspace = thread_view.read_with(cx, |thread_view, _cx| thread_view.workspace.clone());
4242
4243 workspace
4244 .update_in(cx, |workspace, window, cx| {
4245 workspace.add_item_to_active_pane(
4246 Box::new(cx.new(|_| ThreadViewItem(thread_view.clone()))),
4247 None,
4248 true,
4249 window,
4250 cx,
4251 );
4252 })
4253 .unwrap();
4254 }
4255
4256 struct ThreadViewItem(Entity<AcpThreadView>);
4257
4258 impl Item for ThreadViewItem {
4259 type Event = ();
4260
4261 fn include_in_nav_history() -> bool {
4262 false
4263 }
4264
4265 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
4266 "Test".into()
4267 }
4268 }
4269
4270 impl EventEmitter<()> for ThreadViewItem {}
4271
4272 impl Focusable for ThreadViewItem {
4273 fn focus_handle(&self, cx: &App) -> FocusHandle {
4274 self.0.read(cx).focus_handle(cx).clone()
4275 }
4276 }
4277
4278 impl Render for ThreadViewItem {
4279 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
4280 self.0.clone().into_any_element()
4281 }
4282 }
4283
4284 struct StubAgentServer<C> {
4285 connection: C,
4286 }
4287
4288 impl<C> StubAgentServer<C> {
4289 fn new(connection: C) -> Self {
4290 Self { connection }
4291 }
4292 }
4293
4294 impl StubAgentServer<StubAgentConnection> {
4295 fn default_response() -> Self {
4296 let conn = StubAgentConnection::new();
4297 conn.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk {
4298 content: "Default response".into(),
4299 }]);
4300 Self::new(conn)
4301 }
4302 }
4303
4304 impl<C> AgentServer for StubAgentServer<C>
4305 where
4306 C: 'static + AgentConnection + Send + Clone,
4307 {
4308 fn logo(&self) -> ui::IconName {
4309 ui::IconName::Ai
4310 }
4311
4312 fn name(&self) -> &'static str {
4313 "Test"
4314 }
4315
4316 fn empty_state_headline(&self) -> &'static str {
4317 "Test"
4318 }
4319
4320 fn empty_state_message(&self) -> &'static str {
4321 "Test"
4322 }
4323
4324 fn connect(
4325 &self,
4326 _root_dir: &Path,
4327 _project: &Entity<Project>,
4328 _cx: &mut App,
4329 ) -> Task<gpui::Result<Rc<dyn AgentConnection>>> {
4330 Task::ready(Ok(Rc::new(self.connection.clone())))
4331 }
4332
4333 fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
4334 self
4335 }
4336 }
4337
4338 #[derive(Clone)]
4339 struct SaboteurAgentConnection;
4340
4341 impl AgentConnection for SaboteurAgentConnection {
4342 fn new_thread(
4343 self: Rc<Self>,
4344 project: Entity<Project>,
4345 _cwd: &Path,
4346 cx: &mut gpui::App,
4347 ) -> Task<gpui::Result<Entity<AcpThread>>> {
4348 Task::ready(Ok(cx.new(|cx| {
4349 let action_log = cx.new(|_| ActionLog::new(project.clone()));
4350 AcpThread::new(
4351 "SaboteurAgentConnection",
4352 self,
4353 project,
4354 action_log,
4355 SessionId("test".into()),
4356 )
4357 })))
4358 }
4359
4360 fn auth_methods(&self) -> &[acp::AuthMethod] {
4361 &[]
4362 }
4363
4364 fn authenticate(
4365 &self,
4366 _method_id: acp::AuthMethodId,
4367 _cx: &mut App,
4368 ) -> Task<gpui::Result<()>> {
4369 unimplemented!()
4370 }
4371
4372 fn prompt(
4373 &self,
4374 _id: Option<acp_thread::UserMessageId>,
4375 _params: acp::PromptRequest,
4376 _cx: &mut App,
4377 ) -> Task<gpui::Result<acp::PromptResponse>> {
4378 Task::ready(Err(anyhow::anyhow!("Error prompting")))
4379 }
4380
4381 fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {
4382 unimplemented!()
4383 }
4384
4385 fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
4386 self
4387 }
4388 }
4389
4390 pub(crate) fn init_test(cx: &mut TestAppContext) {
4391 cx.update(|cx| {
4392 let settings_store = SettingsStore::test(cx);
4393 cx.set_global(settings_store);
4394 language::init(cx);
4395 Project::init_settings(cx);
4396 AgentSettings::register(cx);
4397 workspace::init_settings(cx);
4398 ThemeSettings::register(cx);
4399 release_channel::init(SemanticVersion::default(), cx);
4400 EditorSettings::register(cx);
4401 });
4402 }
4403
4404 #[gpui::test]
4405 async fn test_rewind_views(cx: &mut TestAppContext) {
4406 init_test(cx);
4407
4408 let fs = FakeFs::new(cx.executor());
4409 fs.insert_tree(
4410 "/project",
4411 json!({
4412 "test1.txt": "old content 1",
4413 "test2.txt": "old content 2"
4414 }),
4415 )
4416 .await;
4417 let project = Project::test(fs, [Path::new("/project")], cx).await;
4418 let (workspace, cx) =
4419 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4420
4421 let thread_store =
4422 cx.update(|_window, cx| cx.new(|cx| ThreadStore::fake(project.clone(), cx)));
4423 let text_thread_store =
4424 cx.update(|_window, cx| cx.new(|cx| TextThreadStore::fake(project.clone(), cx)));
4425 let context_store =
4426 cx.update(|_window, cx| cx.new(|cx| ContextStore::fake(project.clone(), cx)));
4427 let history_store =
4428 cx.update(|_window, cx| cx.new(|cx| HistoryStore::new(context_store, cx)));
4429
4430 let connection = Rc::new(StubAgentConnection::new());
4431 let thread_view = cx.update(|window, cx| {
4432 cx.new(|cx| {
4433 AcpThreadView::new(
4434 Rc::new(StubAgentServer::new(connection.as_ref().clone())),
4435 None,
4436 workspace.downgrade(),
4437 project.clone(),
4438 history_store.clone(),
4439 thread_store.clone(),
4440 text_thread_store.clone(),
4441 window,
4442 cx,
4443 )
4444 })
4445 });
4446
4447 cx.run_until_parked();
4448
4449 let thread = thread_view
4450 .read_with(cx, |view, _| view.thread().cloned())
4451 .unwrap();
4452
4453 // First user message
4454 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(acp::ToolCall {
4455 id: acp::ToolCallId("tool1".into()),
4456 title: "Edit file 1".into(),
4457 kind: acp::ToolKind::Edit,
4458 status: acp::ToolCallStatus::Completed,
4459 content: vec![acp::ToolCallContent::Diff {
4460 diff: acp::Diff {
4461 path: "/project/test1.txt".into(),
4462 old_text: Some("old content 1".into()),
4463 new_text: "new content 1".into(),
4464 },
4465 }],
4466 locations: vec![],
4467 raw_input: None,
4468 raw_output: None,
4469 })]);
4470
4471 thread
4472 .update(cx, |thread, cx| thread.send_raw("Give me a diff", cx))
4473 .await
4474 .unwrap();
4475 cx.run_until_parked();
4476
4477 thread.read_with(cx, |thread, _| {
4478 assert_eq!(thread.entries().len(), 2);
4479 });
4480
4481 thread_view.read_with(cx, |view, cx| {
4482 view.entry_view_state.read_with(cx, |entry_view_state, _| {
4483 assert!(
4484 entry_view_state
4485 .entry(0)
4486 .unwrap()
4487 .message_editor()
4488 .is_some()
4489 );
4490 assert!(entry_view_state.entry(1).unwrap().has_content());
4491 });
4492 });
4493
4494 // Second user message
4495 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(acp::ToolCall {
4496 id: acp::ToolCallId("tool2".into()),
4497 title: "Edit file 2".into(),
4498 kind: acp::ToolKind::Edit,
4499 status: acp::ToolCallStatus::Completed,
4500 content: vec![acp::ToolCallContent::Diff {
4501 diff: acp::Diff {
4502 path: "/project/test2.txt".into(),
4503 old_text: Some("old content 2".into()),
4504 new_text: "new content 2".into(),
4505 },
4506 }],
4507 locations: vec![],
4508 raw_input: None,
4509 raw_output: None,
4510 })]);
4511
4512 thread
4513 .update(cx, |thread, cx| thread.send_raw("Another one", cx))
4514 .await
4515 .unwrap();
4516 cx.run_until_parked();
4517
4518 let second_user_message_id = thread.read_with(cx, |thread, _| {
4519 assert_eq!(thread.entries().len(), 4);
4520 let AgentThreadEntry::UserMessage(user_message) = &thread.entries()[2] else {
4521 panic!();
4522 };
4523 user_message.id.clone().unwrap()
4524 });
4525
4526 thread_view.read_with(cx, |view, cx| {
4527 view.entry_view_state.read_with(cx, |entry_view_state, _| {
4528 assert!(
4529 entry_view_state
4530 .entry(0)
4531 .unwrap()
4532 .message_editor()
4533 .is_some()
4534 );
4535 assert!(entry_view_state.entry(1).unwrap().has_content());
4536 assert!(
4537 entry_view_state
4538 .entry(2)
4539 .unwrap()
4540 .message_editor()
4541 .is_some()
4542 );
4543 assert!(entry_view_state.entry(3).unwrap().has_content());
4544 });
4545 });
4546
4547 // Rewind to first message
4548 thread
4549 .update(cx, |thread, cx| thread.rewind(second_user_message_id, cx))
4550 .await
4551 .unwrap();
4552
4553 cx.run_until_parked();
4554
4555 thread.read_with(cx, |thread, _| {
4556 assert_eq!(thread.entries().len(), 2);
4557 });
4558
4559 thread_view.read_with(cx, |view, cx| {
4560 view.entry_view_state.read_with(cx, |entry_view_state, _| {
4561 assert!(
4562 entry_view_state
4563 .entry(0)
4564 .unwrap()
4565 .message_editor()
4566 .is_some()
4567 );
4568 assert!(entry_view_state.entry(1).unwrap().has_content());
4569
4570 // Old views should be dropped
4571 assert!(entry_view_state.entry(2).is_none());
4572 assert!(entry_view_state.entry(3).is_none());
4573 });
4574 });
4575 }
4576
4577 #[gpui::test]
4578 async fn test_message_editing_cancel(cx: &mut TestAppContext) {
4579 init_test(cx);
4580
4581 let connection = StubAgentConnection::new();
4582
4583 connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk {
4584 content: acp::ContentBlock::Text(acp::TextContent {
4585 text: "Response".into(),
4586 annotations: None,
4587 }),
4588 }]);
4589
4590 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
4591 add_to_workspace(thread_view.clone(), cx);
4592
4593 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
4594 message_editor.update_in(cx, |editor, window, cx| {
4595 editor.set_text("Original message to edit", window, cx);
4596 });
4597 thread_view.update_in(cx, |thread_view, window, cx| {
4598 thread_view.send(window, cx);
4599 });
4600
4601 cx.run_until_parked();
4602
4603 let user_message_editor = thread_view.read_with(cx, |view, cx| {
4604 assert_eq!(view.editing_message, None);
4605
4606 view.entry_view_state
4607 .read(cx)
4608 .entry(0)
4609 .unwrap()
4610 .message_editor()
4611 .unwrap()
4612 .clone()
4613 });
4614
4615 // Focus
4616 cx.focus(&user_message_editor);
4617 thread_view.read_with(cx, |view, _cx| {
4618 assert_eq!(view.editing_message, Some(0));
4619 });
4620
4621 // Edit
4622 user_message_editor.update_in(cx, |editor, window, cx| {
4623 editor.set_text("Edited message content", window, cx);
4624 });
4625
4626 // Cancel
4627 user_message_editor.update_in(cx, |_editor, window, cx| {
4628 window.dispatch_action(Box::new(editor::actions::Cancel), cx);
4629 });
4630
4631 thread_view.read_with(cx, |view, _cx| {
4632 assert_eq!(view.editing_message, None);
4633 });
4634
4635 user_message_editor.read_with(cx, |editor, cx| {
4636 assert_eq!(editor.text(cx), "Original message to edit");
4637 });
4638 }
4639
4640 #[gpui::test]
4641 async fn test_message_doesnt_send_if_empty(cx: &mut TestAppContext) {
4642 init_test(cx);
4643
4644 let connection = StubAgentConnection::new();
4645
4646 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
4647 add_to_workspace(thread_view.clone(), cx);
4648
4649 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
4650 let mut events = cx.events(&message_editor);
4651 message_editor.update_in(cx, |editor, window, cx| {
4652 editor.set_text("", window, cx);
4653 });
4654
4655 message_editor.update_in(cx, |_editor, window, cx| {
4656 window.dispatch_action(Box::new(Chat), cx);
4657 });
4658 cx.run_until_parked();
4659 // We shouldn't have received any messages
4660 assert!(matches!(
4661 events.try_next(),
4662 Err(futures::channel::mpsc::TryRecvError { .. })
4663 ));
4664 }
4665
4666 #[gpui::test]
4667 async fn test_message_editing_regenerate(cx: &mut TestAppContext) {
4668 init_test(cx);
4669
4670 let connection = StubAgentConnection::new();
4671
4672 connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk {
4673 content: acp::ContentBlock::Text(acp::TextContent {
4674 text: "Response".into(),
4675 annotations: None,
4676 }),
4677 }]);
4678
4679 let (thread_view, cx) =
4680 setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
4681 add_to_workspace(thread_view.clone(), cx);
4682
4683 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
4684 message_editor.update_in(cx, |editor, window, cx| {
4685 editor.set_text("Original message to edit", window, cx);
4686 });
4687 thread_view.update_in(cx, |thread_view, window, cx| {
4688 thread_view.send(window, cx);
4689 });
4690
4691 cx.run_until_parked();
4692
4693 let user_message_editor = thread_view.read_with(cx, |view, cx| {
4694 assert_eq!(view.editing_message, None);
4695 assert_eq!(view.thread().unwrap().read(cx).entries().len(), 2);
4696
4697 view.entry_view_state
4698 .read(cx)
4699 .entry(0)
4700 .unwrap()
4701 .message_editor()
4702 .unwrap()
4703 .clone()
4704 });
4705
4706 // Focus
4707 cx.focus(&user_message_editor);
4708
4709 // Edit
4710 user_message_editor.update_in(cx, |editor, window, cx| {
4711 editor.set_text("Edited message content", window, cx);
4712 });
4713
4714 // Send
4715 connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk {
4716 content: acp::ContentBlock::Text(acp::TextContent {
4717 text: "New Response".into(),
4718 annotations: None,
4719 }),
4720 }]);
4721
4722 user_message_editor.update_in(cx, |_editor, window, cx| {
4723 window.dispatch_action(Box::new(Chat), cx);
4724 });
4725
4726 cx.run_until_parked();
4727
4728 thread_view.read_with(cx, |view, cx| {
4729 assert_eq!(view.editing_message, None);
4730
4731 let entries = view.thread().unwrap().read(cx).entries();
4732 assert_eq!(entries.len(), 2);
4733 assert_eq!(
4734 entries[0].to_markdown(cx),
4735 "## User\n\nEdited message content\n\n"
4736 );
4737 assert_eq!(
4738 entries[1].to_markdown(cx),
4739 "## Assistant\n\nNew Response\n\n"
4740 );
4741
4742 let new_editor = view.entry_view_state.read_with(cx, |state, _cx| {
4743 assert!(!state.entry(1).unwrap().has_content());
4744 state.entry(0).unwrap().message_editor().unwrap().clone()
4745 });
4746
4747 assert_eq!(new_editor.read(cx).text(cx), "Edited message content");
4748 })
4749 }
4750
4751 #[gpui::test]
4752 async fn test_message_editing_while_generating(cx: &mut TestAppContext) {
4753 init_test(cx);
4754
4755 let connection = StubAgentConnection::new();
4756
4757 let (thread_view, cx) =
4758 setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
4759 add_to_workspace(thread_view.clone(), cx);
4760
4761 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
4762 message_editor.update_in(cx, |editor, window, cx| {
4763 editor.set_text("Original message to edit", window, cx);
4764 });
4765 thread_view.update_in(cx, |thread_view, window, cx| {
4766 thread_view.send(window, cx);
4767 });
4768
4769 cx.run_until_parked();
4770
4771 let (user_message_editor, session_id) = thread_view.read_with(cx, |view, cx| {
4772 let thread = view.thread().unwrap().read(cx);
4773 assert_eq!(thread.entries().len(), 1);
4774
4775 let editor = view
4776 .entry_view_state
4777 .read(cx)
4778 .entry(0)
4779 .unwrap()
4780 .message_editor()
4781 .unwrap()
4782 .clone();
4783
4784 (editor, thread.session_id().clone())
4785 });
4786
4787 // Focus
4788 cx.focus(&user_message_editor);
4789
4790 thread_view.read_with(cx, |view, _cx| {
4791 assert_eq!(view.editing_message, Some(0));
4792 });
4793
4794 // Edit
4795 user_message_editor.update_in(cx, |editor, window, cx| {
4796 editor.set_text("Edited message content", window, cx);
4797 });
4798
4799 thread_view.read_with(cx, |view, _cx| {
4800 assert_eq!(view.editing_message, Some(0));
4801 });
4802
4803 // Finish streaming response
4804 cx.update(|_, cx| {
4805 connection.send_update(
4806 session_id.clone(),
4807 acp::SessionUpdate::AgentMessageChunk {
4808 content: acp::ContentBlock::Text(acp::TextContent {
4809 text: "Response".into(),
4810 annotations: None,
4811 }),
4812 },
4813 cx,
4814 );
4815 connection.end_turn(session_id, acp::StopReason::EndTurn);
4816 });
4817
4818 thread_view.read_with(cx, |view, _cx| {
4819 assert_eq!(view.editing_message, Some(0));
4820 });
4821
4822 cx.run_until_parked();
4823
4824 // Should still be editing
4825 cx.update(|window, cx| {
4826 assert!(user_message_editor.focus_handle(cx).is_focused(window));
4827 assert_eq!(thread_view.read(cx).editing_message, Some(0));
4828 assert_eq!(
4829 user_message_editor.read(cx).text(cx),
4830 "Edited message content"
4831 );
4832 });
4833 }
4834
4835 #[gpui::test]
4836 async fn test_interrupt(cx: &mut TestAppContext) {
4837 init_test(cx);
4838
4839 let connection = StubAgentConnection::new();
4840
4841 let (thread_view, cx) =
4842 setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
4843 add_to_workspace(thread_view.clone(), cx);
4844
4845 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
4846 message_editor.update_in(cx, |editor, window, cx| {
4847 editor.set_text("Message 1", window, cx);
4848 });
4849 thread_view.update_in(cx, |thread_view, window, cx| {
4850 thread_view.send(window, cx);
4851 });
4852
4853 let (thread, session_id) = thread_view.read_with(cx, |view, cx| {
4854 let thread = view.thread().unwrap();
4855
4856 (thread.clone(), thread.read(cx).session_id().clone())
4857 });
4858
4859 cx.run_until_parked();
4860
4861 cx.update(|_, cx| {
4862 connection.send_update(
4863 session_id.clone(),
4864 acp::SessionUpdate::AgentMessageChunk {
4865 content: "Message 1 resp".into(),
4866 },
4867 cx,
4868 );
4869 });
4870
4871 cx.run_until_parked();
4872
4873 thread.read_with(cx, |thread, cx| {
4874 assert_eq!(
4875 thread.to_markdown(cx),
4876 indoc::indoc! {"
4877 ## User
4878
4879 Message 1
4880
4881 ## Assistant
4882
4883 Message 1 resp
4884
4885 "}
4886 )
4887 });
4888
4889 message_editor.update_in(cx, |editor, window, cx| {
4890 editor.set_text("Message 2", window, cx);
4891 });
4892 thread_view.update_in(cx, |thread_view, window, cx| {
4893 thread_view.send(window, cx);
4894 });
4895
4896 cx.update(|_, cx| {
4897 // Simulate a response sent after beginning to cancel
4898 connection.send_update(
4899 session_id.clone(),
4900 acp::SessionUpdate::AgentMessageChunk {
4901 content: "onse".into(),
4902 },
4903 cx,
4904 );
4905 });
4906
4907 cx.run_until_parked();
4908
4909 // Last Message 1 response should appear before Message 2
4910 thread.read_with(cx, |thread, cx| {
4911 assert_eq!(
4912 thread.to_markdown(cx),
4913 indoc::indoc! {"
4914 ## User
4915
4916 Message 1
4917
4918 ## Assistant
4919
4920 Message 1 response
4921
4922 ## User
4923
4924 Message 2
4925
4926 "}
4927 )
4928 });
4929
4930 cx.update(|_, cx| {
4931 connection.send_update(
4932 session_id.clone(),
4933 acp::SessionUpdate::AgentMessageChunk {
4934 content: "Message 2 response".into(),
4935 },
4936 cx,
4937 );
4938 connection.end_turn(session_id.clone(), acp::StopReason::EndTurn);
4939 });
4940
4941 cx.run_until_parked();
4942
4943 thread.read_with(cx, |thread, cx| {
4944 assert_eq!(
4945 thread.to_markdown(cx),
4946 indoc::indoc! {"
4947 ## User
4948
4949 Message 1
4950
4951 ## Assistant
4952
4953 Message 1 response
4954
4955 ## User
4956
4957 Message 2
4958
4959 ## Assistant
4960
4961 Message 2 response
4962
4963 "}
4964 )
4965 });
4966 }
4967}