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