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 .map_or(false, |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 => {}
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().into_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.into_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.profile_selector.clone())
2798 .children(self.model_selector.clone())
2799 .child(self.render_send_button(cx)),
2800 ),
2801 )
2802 .into_any()
2803 }
2804
2805 pub(crate) fn as_native_connection(
2806 &self,
2807 cx: &App,
2808 ) -> Option<Rc<agent2::NativeAgentConnection>> {
2809 let acp_thread = self.thread()?.read(cx);
2810 acp_thread.connection().clone().downcast()
2811 }
2812
2813 pub(crate) fn as_native_thread(&self, cx: &App) -> Option<Entity<agent2::Thread>> {
2814 let acp_thread = self.thread()?.read(cx);
2815 self.as_native_connection(cx)?
2816 .thread(acp_thread.session_id(), cx)
2817 }
2818
2819 fn toggle_burn_mode(
2820 &mut self,
2821 _: &ToggleBurnMode,
2822 _window: &mut Window,
2823 cx: &mut Context<Self>,
2824 ) {
2825 let Some(thread) = self.as_native_thread(cx) else {
2826 return;
2827 };
2828
2829 thread.update(cx, |thread, cx| {
2830 let current_mode = thread.completion_mode();
2831 thread.set_completion_mode(
2832 match current_mode {
2833 CompletionMode::Burn => CompletionMode::Normal,
2834 CompletionMode::Normal => CompletionMode::Burn,
2835 },
2836 cx,
2837 );
2838 });
2839 }
2840
2841 fn render_burn_mode_toggle(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
2842 let thread = self.as_native_thread(cx)?.read(cx);
2843
2844 if thread
2845 .model()
2846 .map_or(true, |model| !model.supports_burn_mode())
2847 {
2848 return None;
2849 }
2850
2851 let active_completion_mode = thread.completion_mode();
2852 let burn_mode_enabled = active_completion_mode == CompletionMode::Burn;
2853 let icon = if burn_mode_enabled {
2854 IconName::ZedBurnModeOn
2855 } else {
2856 IconName::ZedBurnMode
2857 };
2858
2859 Some(
2860 IconButton::new("burn-mode", icon)
2861 .icon_size(IconSize::Small)
2862 .icon_color(Color::Muted)
2863 .toggle_state(burn_mode_enabled)
2864 .selected_icon_color(Color::Error)
2865 .on_click(cx.listener(|this, _event, window, cx| {
2866 this.toggle_burn_mode(&ToggleBurnMode, window, cx);
2867 }))
2868 .tooltip(move |_window, cx| {
2869 cx.new(|_| BurnModeTooltip::new().selected(burn_mode_enabled))
2870 .into()
2871 })
2872 .into_any_element(),
2873 )
2874 }
2875
2876 fn render_send_button(&self, cx: &mut Context<Self>) -> AnyElement {
2877 let is_editor_empty = self.message_editor.read(cx).is_empty(cx);
2878 let is_generating = self.thread().map_or(false, |thread| {
2879 thread.read(cx).status() != ThreadStatus::Idle
2880 });
2881
2882 if is_generating && is_editor_empty {
2883 IconButton::new("stop-generation", IconName::Stop)
2884 .icon_color(Color::Error)
2885 .style(ButtonStyle::Tinted(ui::TintColor::Error))
2886 .tooltip(move |window, cx| {
2887 Tooltip::for_action("Stop Generation", &editor::actions::Cancel, window, cx)
2888 })
2889 .on_click(cx.listener(|this, _event, _, cx| this.cancel_generation(cx)))
2890 .into_any_element()
2891 } else {
2892 let send_btn_tooltip = if is_editor_empty && !is_generating {
2893 "Type to Send"
2894 } else if is_generating {
2895 "Stop and Send Message"
2896 } else {
2897 "Send"
2898 };
2899
2900 IconButton::new("send-message", IconName::Send)
2901 .style(ButtonStyle::Filled)
2902 .map(|this| {
2903 if is_editor_empty && !is_generating {
2904 this.disabled(true).icon_color(Color::Muted)
2905 } else {
2906 this.icon_color(Color::Accent)
2907 }
2908 })
2909 .tooltip(move |window, cx| Tooltip::for_action(send_btn_tooltip, &Chat, window, cx))
2910 .on_click(cx.listener(|this, _, window, cx| {
2911 this.send(window, cx);
2912 }))
2913 .into_any_element()
2914 }
2915 }
2916
2917 fn render_follow_toggle(&self, cx: &mut Context<Self>) -> impl IntoElement {
2918 let following = self
2919 .workspace
2920 .read_with(cx, |workspace, _| {
2921 workspace.is_being_followed(CollaboratorId::Agent)
2922 })
2923 .unwrap_or(false);
2924
2925 IconButton::new("follow-agent", IconName::Crosshair)
2926 .icon_size(IconSize::Small)
2927 .icon_color(Color::Muted)
2928 .toggle_state(following)
2929 .selected_icon_color(Some(Color::Custom(cx.theme().players().agent().cursor)))
2930 .tooltip(move |window, cx| {
2931 if following {
2932 Tooltip::for_action("Stop Following Agent", &Follow, window, cx)
2933 } else {
2934 Tooltip::with_meta(
2935 "Follow Agent",
2936 Some(&Follow),
2937 "Track the agent's location as it reads and edits files.",
2938 window,
2939 cx,
2940 )
2941 }
2942 })
2943 .on_click(cx.listener(move |this, _, window, cx| {
2944 this.workspace
2945 .update(cx, |workspace, cx| {
2946 if following {
2947 workspace.unfollow(CollaboratorId::Agent, window, cx);
2948 } else {
2949 workspace.follow(CollaboratorId::Agent, window, cx);
2950 }
2951 })
2952 .ok();
2953 }))
2954 }
2955
2956 fn render_markdown(&self, markdown: Entity<Markdown>, style: MarkdownStyle) -> MarkdownElement {
2957 let workspace = self.workspace.clone();
2958 MarkdownElement::new(markdown, style).on_url_click(move |text, window, cx| {
2959 Self::open_link(text, &workspace, window, cx);
2960 })
2961 }
2962
2963 fn open_link(
2964 url: SharedString,
2965 workspace: &WeakEntity<Workspace>,
2966 window: &mut Window,
2967 cx: &mut App,
2968 ) {
2969 let Some(workspace) = workspace.upgrade() else {
2970 cx.open_url(&url);
2971 return;
2972 };
2973
2974 if let Some(mention) = MentionUri::parse(&url).log_err() {
2975 workspace.update(cx, |workspace, cx| match mention {
2976 MentionUri::File { abs_path } => {
2977 let project = workspace.project();
2978 let Some(path) =
2979 project.update(cx, |project, cx| project.find_project_path(abs_path, cx))
2980 else {
2981 return;
2982 };
2983
2984 workspace
2985 .open_path(path, None, true, window, cx)
2986 .detach_and_log_err(cx);
2987 }
2988 MentionUri::Directory { abs_path } => {
2989 let project = workspace.project();
2990 let Some(entry) = project.update(cx, |project, cx| {
2991 let path = project.find_project_path(abs_path, cx)?;
2992 project.entry_for_path(&path, cx)
2993 }) else {
2994 return;
2995 };
2996
2997 project.update(cx, |_, cx| {
2998 cx.emit(project::Event::RevealInProjectPanel(entry.id));
2999 });
3000 }
3001 MentionUri::Symbol {
3002 path, line_range, ..
3003 }
3004 | MentionUri::Selection { path, line_range } => {
3005 let project = workspace.project();
3006 let Some((path, _)) = project.update(cx, |project, cx| {
3007 let path = project.find_project_path(path, cx)?;
3008 let entry = project.entry_for_path(&path, cx)?;
3009 Some((path, entry))
3010 }) else {
3011 return;
3012 };
3013
3014 let item = workspace.open_path(path, None, true, window, cx);
3015 window
3016 .spawn(cx, async move |cx| {
3017 let Some(editor) = item.await?.downcast::<Editor>() else {
3018 return Ok(());
3019 };
3020 let range =
3021 Point::new(line_range.start, 0)..Point::new(line_range.start, 0);
3022 editor
3023 .update_in(cx, |editor, window, cx| {
3024 editor.change_selections(
3025 SelectionEffects::scroll(Autoscroll::center()),
3026 window,
3027 cx,
3028 |s| s.select_ranges(vec![range]),
3029 );
3030 })
3031 .ok();
3032 anyhow::Ok(())
3033 })
3034 .detach_and_log_err(cx);
3035 }
3036 MentionUri::Thread { id, .. } => {
3037 if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
3038 panel.update(cx, |panel, cx| {
3039 panel
3040 .open_thread_by_id(&id, window, cx)
3041 .detach_and_log_err(cx)
3042 });
3043 }
3044 }
3045 MentionUri::TextThread { path, .. } => {
3046 if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
3047 panel.update(cx, |panel, cx| {
3048 panel
3049 .open_saved_prompt_editor(path.as_path().into(), window, cx)
3050 .detach_and_log_err(cx);
3051 });
3052 }
3053 }
3054 MentionUri::Rule { id, .. } => {
3055 let PromptId::User { uuid } = id else {
3056 return;
3057 };
3058 window.dispatch_action(
3059 Box::new(OpenRulesLibrary {
3060 prompt_to_select: Some(uuid.0),
3061 }),
3062 cx,
3063 )
3064 }
3065 MentionUri::Fetch { url } => {
3066 cx.open_url(url.as_str());
3067 }
3068 })
3069 } else {
3070 cx.open_url(&url);
3071 }
3072 }
3073
3074 fn open_tool_call_location(
3075 &self,
3076 entry_ix: usize,
3077 location_ix: usize,
3078 window: &mut Window,
3079 cx: &mut Context<Self>,
3080 ) -> Option<()> {
3081 let (tool_call_location, agent_location) = self
3082 .thread()?
3083 .read(cx)
3084 .entries()
3085 .get(entry_ix)?
3086 .location(location_ix)?;
3087
3088 let project_path = self
3089 .project
3090 .read(cx)
3091 .find_project_path(&tool_call_location.path, cx)?;
3092
3093 let open_task = self
3094 .workspace
3095 .update(cx, |workspace, cx| {
3096 workspace.open_path(project_path, None, true, window, cx)
3097 })
3098 .log_err()?;
3099 window
3100 .spawn(cx, async move |cx| {
3101 let item = open_task.await?;
3102
3103 let Some(active_editor) = item.downcast::<Editor>() else {
3104 return anyhow::Ok(());
3105 };
3106
3107 active_editor.update_in(cx, |editor, window, cx| {
3108 let multibuffer = editor.buffer().read(cx);
3109 let buffer = multibuffer.as_singleton();
3110 if agent_location.buffer.upgrade() == buffer {
3111 let excerpt_id = multibuffer.excerpt_ids().first().cloned();
3112 let anchor = editor::Anchor::in_buffer(
3113 excerpt_id.unwrap(),
3114 buffer.unwrap().read(cx).remote_id(),
3115 agent_location.position,
3116 );
3117 editor.change_selections(Default::default(), window, cx, |selections| {
3118 selections.select_anchor_ranges([anchor..anchor]);
3119 })
3120 } else {
3121 let row = tool_call_location.line.unwrap_or_default();
3122 editor.change_selections(Default::default(), window, cx, |selections| {
3123 selections.select_ranges([Point::new(row, 0)..Point::new(row, 0)]);
3124 })
3125 }
3126 })?;
3127
3128 anyhow::Ok(())
3129 })
3130 .detach_and_log_err(cx);
3131
3132 None
3133 }
3134
3135 pub fn open_thread_as_markdown(
3136 &self,
3137 workspace: Entity<Workspace>,
3138 window: &mut Window,
3139 cx: &mut App,
3140 ) -> Task<anyhow::Result<()>> {
3141 let markdown_language_task = workspace
3142 .read(cx)
3143 .app_state()
3144 .languages
3145 .language_for_name("Markdown");
3146
3147 let (thread_summary, markdown) = if let Some(thread) = self.thread() {
3148 let thread = thread.read(cx);
3149 (thread.title().to_string(), thread.to_markdown(cx))
3150 } else {
3151 return Task::ready(Ok(()));
3152 };
3153
3154 window.spawn(cx, async move |cx| {
3155 let markdown_language = markdown_language_task.await?;
3156
3157 workspace.update_in(cx, |workspace, window, cx| {
3158 let project = workspace.project().clone();
3159
3160 if !project.read(cx).is_local() {
3161 bail!("failed to open active thread as markdown in remote project");
3162 }
3163
3164 let buffer = project.update(cx, |project, cx| {
3165 project.create_local_buffer(&markdown, Some(markdown_language), cx)
3166 });
3167 let buffer = cx.new(|cx| {
3168 MultiBuffer::singleton(buffer, cx).with_title(thread_summary.clone())
3169 });
3170
3171 workspace.add_item_to_active_pane(
3172 Box::new(cx.new(|cx| {
3173 let mut editor =
3174 Editor::for_multibuffer(buffer, Some(project.clone()), window, cx);
3175 editor.set_breadcrumb_header(thread_summary);
3176 editor
3177 })),
3178 None,
3179 true,
3180 window,
3181 cx,
3182 );
3183
3184 anyhow::Ok(())
3185 })??;
3186 anyhow::Ok(())
3187 })
3188 }
3189
3190 fn scroll_to_top(&mut self, cx: &mut Context<Self>) {
3191 self.list_state.scroll_to(ListOffset::default());
3192 cx.notify();
3193 }
3194
3195 pub fn scroll_to_bottom(&mut self, cx: &mut Context<Self>) {
3196 if let Some(thread) = self.thread() {
3197 let entry_count = thread.read(cx).entries().len();
3198 self.list_state.reset(entry_count);
3199 cx.notify();
3200 }
3201 }
3202
3203 fn notify_with_sound(
3204 &mut self,
3205 caption: impl Into<SharedString>,
3206 icon: IconName,
3207 window: &mut Window,
3208 cx: &mut Context<Self>,
3209 ) {
3210 self.play_notification_sound(window, cx);
3211 self.show_notification(caption, icon, window, cx);
3212 }
3213
3214 fn play_notification_sound(&self, window: &Window, cx: &mut App) {
3215 let settings = AgentSettings::get_global(cx);
3216 if settings.play_sound_when_agent_done && !window.is_window_active() {
3217 Audio::play_sound(Sound::AgentDone, cx);
3218 }
3219 }
3220
3221 fn show_notification(
3222 &mut self,
3223 caption: impl Into<SharedString>,
3224 icon: IconName,
3225 window: &mut Window,
3226 cx: &mut Context<Self>,
3227 ) {
3228 if window.is_window_active() || !self.notifications.is_empty() {
3229 return;
3230 }
3231
3232 let title = self.title(cx);
3233
3234 match AgentSettings::get_global(cx).notify_when_agent_waiting {
3235 NotifyWhenAgentWaiting::PrimaryScreen => {
3236 if let Some(primary) = cx.primary_display() {
3237 self.pop_up(icon, caption.into(), title, window, primary, cx);
3238 }
3239 }
3240 NotifyWhenAgentWaiting::AllScreens => {
3241 let caption = caption.into();
3242 for screen in cx.displays() {
3243 self.pop_up(icon, caption.clone(), title.clone(), window, screen, cx);
3244 }
3245 }
3246 NotifyWhenAgentWaiting::Never => {
3247 // Don't show anything
3248 }
3249 }
3250 }
3251
3252 fn pop_up(
3253 &mut self,
3254 icon: IconName,
3255 caption: SharedString,
3256 title: SharedString,
3257 window: &mut Window,
3258 screen: Rc<dyn PlatformDisplay>,
3259 cx: &mut Context<Self>,
3260 ) {
3261 let options = AgentNotification::window_options(screen, cx);
3262
3263 let project_name = self.workspace.upgrade().and_then(|workspace| {
3264 workspace
3265 .read(cx)
3266 .project()
3267 .read(cx)
3268 .visible_worktrees(cx)
3269 .next()
3270 .map(|worktree| worktree.read(cx).root_name().to_string())
3271 });
3272
3273 if let Some(screen_window) = cx
3274 .open_window(options, |_, cx| {
3275 cx.new(|_| {
3276 AgentNotification::new(title.clone(), caption.clone(), icon, project_name)
3277 })
3278 })
3279 .log_err()
3280 && let Some(pop_up) = screen_window.entity(cx).log_err()
3281 {
3282 self.notification_subscriptions
3283 .entry(screen_window)
3284 .or_insert_with(Vec::new)
3285 .push(cx.subscribe_in(&pop_up, window, {
3286 |this, _, event, window, cx| match event {
3287 AgentNotificationEvent::Accepted => {
3288 let handle = window.window_handle();
3289 cx.activate(true);
3290
3291 let workspace_handle = this.workspace.clone();
3292
3293 // If there are multiple Zed windows, activate the correct one.
3294 cx.defer(move |cx| {
3295 handle
3296 .update(cx, |_view, window, _cx| {
3297 window.activate_window();
3298
3299 if let Some(workspace) = workspace_handle.upgrade() {
3300 workspace.update(_cx, |workspace, cx| {
3301 workspace.focus_panel::<AgentPanel>(window, cx);
3302 });
3303 }
3304 })
3305 .log_err();
3306 });
3307
3308 this.dismiss_notifications(cx);
3309 }
3310 AgentNotificationEvent::Dismissed => {
3311 this.dismiss_notifications(cx);
3312 }
3313 }
3314 }));
3315
3316 self.notifications.push(screen_window);
3317
3318 // If the user manually refocuses the original window, dismiss the popup.
3319 self.notification_subscriptions
3320 .entry(screen_window)
3321 .or_insert_with(Vec::new)
3322 .push({
3323 let pop_up_weak = pop_up.downgrade();
3324
3325 cx.observe_window_activation(window, move |_, window, cx| {
3326 if window.is_window_active()
3327 && let Some(pop_up) = pop_up_weak.upgrade()
3328 {
3329 pop_up.update(cx, |_, cx| {
3330 cx.emit(AgentNotificationEvent::Dismissed);
3331 });
3332 }
3333 })
3334 });
3335 }
3336 }
3337
3338 fn dismiss_notifications(&mut self, cx: &mut Context<Self>) {
3339 for window in self.notifications.drain(..) {
3340 window
3341 .update(cx, |_, window, _| {
3342 window.remove_window();
3343 })
3344 .ok();
3345
3346 self.notification_subscriptions.remove(&window);
3347 }
3348 }
3349
3350 fn render_thread_controls(&self, cx: &Context<Self>) -> impl IntoElement {
3351 let open_as_markdown = IconButton::new("open-as-markdown", IconName::FileMarkdown)
3352 .shape(ui::IconButtonShape::Square)
3353 .icon_size(IconSize::Small)
3354 .icon_color(Color::Ignored)
3355 .tooltip(Tooltip::text("Open Thread as Markdown"))
3356 .on_click(cx.listener(move |this, _, window, cx| {
3357 if let Some(workspace) = this.workspace.upgrade() {
3358 this.open_thread_as_markdown(workspace, window, cx)
3359 .detach_and_log_err(cx);
3360 }
3361 }));
3362
3363 let scroll_to_top = IconButton::new("scroll_to_top", IconName::ArrowUp)
3364 .shape(ui::IconButtonShape::Square)
3365 .icon_size(IconSize::Small)
3366 .icon_color(Color::Ignored)
3367 .tooltip(Tooltip::text("Scroll To Top"))
3368 .on_click(cx.listener(move |this, _, _, cx| {
3369 this.scroll_to_top(cx);
3370 }));
3371
3372 h_flex()
3373 .w_full()
3374 .mr_1()
3375 .pb_2()
3376 .px(RESPONSE_PADDING_X)
3377 .opacity(0.4)
3378 .hover(|style| style.opacity(1.))
3379 .flex_wrap()
3380 .justify_end()
3381 .child(open_as_markdown)
3382 .child(scroll_to_top)
3383 }
3384
3385 fn render_vertical_scrollbar(&self, cx: &mut Context<Self>) -> Stateful<Div> {
3386 div()
3387 .id("acp-thread-scrollbar")
3388 .occlude()
3389 .on_mouse_move(cx.listener(|_, _, _, cx| {
3390 cx.notify();
3391 cx.stop_propagation()
3392 }))
3393 .on_hover(|_, _, cx| {
3394 cx.stop_propagation();
3395 })
3396 .on_any_mouse_down(|_, _, cx| {
3397 cx.stop_propagation();
3398 })
3399 .on_mouse_up(
3400 MouseButton::Left,
3401 cx.listener(|_, _, _, cx| {
3402 cx.stop_propagation();
3403 }),
3404 )
3405 .on_scroll_wheel(cx.listener(|_, _, _, cx| {
3406 cx.notify();
3407 }))
3408 .h_full()
3409 .absolute()
3410 .right_1()
3411 .top_1()
3412 .bottom_0()
3413 .w(px(12.))
3414 .cursor_default()
3415 .children(Scrollbar::vertical(self.scrollbar_state.clone()).map(|s| s.auto_hide(cx)))
3416 }
3417
3418 fn settings_changed(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
3419 self.entry_view_state.update(cx, |entry_view_state, cx| {
3420 entry_view_state.settings_changed(cx);
3421 });
3422 }
3423
3424 pub(crate) fn insert_dragged_files(
3425 &self,
3426 paths: Vec<project::ProjectPath>,
3427 added_worktrees: Vec<Entity<project::Worktree>>,
3428 window: &mut Window,
3429 cx: &mut Context<Self>,
3430 ) {
3431 self.message_editor.update(cx, |message_editor, cx| {
3432 message_editor.insert_dragged_files(paths, added_worktrees, window, cx);
3433 })
3434 }
3435
3436 fn render_thread_retry_status_callout(
3437 &self,
3438 _window: &mut Window,
3439 _cx: &mut Context<Self>,
3440 ) -> Option<Callout> {
3441 let state = self.thread_retry_status.as_ref()?;
3442
3443 let next_attempt_in = state
3444 .duration
3445 .saturating_sub(Instant::now().saturating_duration_since(state.started_at));
3446 if next_attempt_in.is_zero() {
3447 return None;
3448 }
3449
3450 let next_attempt_in_secs = next_attempt_in.as_secs() + 1;
3451
3452 let retry_message = if state.max_attempts == 1 {
3453 if next_attempt_in_secs == 1 {
3454 "Retrying. Next attempt in 1 second.".to_string()
3455 } else {
3456 format!("Retrying. Next attempt in {next_attempt_in_secs} seconds.")
3457 }
3458 } else {
3459 if next_attempt_in_secs == 1 {
3460 format!(
3461 "Retrying. Next attempt in 1 second (Attempt {} of {}).",
3462 state.attempt, state.max_attempts,
3463 )
3464 } else {
3465 format!(
3466 "Retrying. Next attempt in {next_attempt_in_secs} seconds (Attempt {} of {}).",
3467 state.attempt, state.max_attempts,
3468 )
3469 }
3470 };
3471
3472 Some(
3473 Callout::new()
3474 .severity(Severity::Warning)
3475 .title(state.last_error.clone())
3476 .description(retry_message),
3477 )
3478 }
3479
3480 fn render_thread_error(&self, window: &mut Window, cx: &mut Context<Self>) -> Option<Div> {
3481 let content = match self.thread_error.as_ref()? {
3482 ThreadError::Other(error) => self.render_any_thread_error(error.clone(), cx),
3483 ThreadError::PaymentRequired => self.render_payment_required_error(cx),
3484 ThreadError::ModelRequestLimitReached(plan) => {
3485 self.render_model_request_limit_reached_error(*plan, cx)
3486 }
3487 ThreadError::ToolUseLimitReached => {
3488 self.render_tool_use_limit_reached_error(window, cx)?
3489 }
3490 };
3491
3492 Some(div().child(content))
3493 }
3494
3495 fn render_any_thread_error(&self, error: SharedString, cx: &mut Context<'_, Self>) -> Callout {
3496 Callout::new()
3497 .severity(Severity::Error)
3498 .title("Error")
3499 .description(error.clone())
3500 .actions_slot(self.create_copy_button(error.to_string()))
3501 .dismiss_action(self.dismiss_error_button(cx))
3502 }
3503
3504 fn render_payment_required_error(&self, cx: &mut Context<Self>) -> Callout {
3505 const ERROR_MESSAGE: &str =
3506 "You reached your free usage limit. Upgrade to Zed Pro for more prompts.";
3507
3508 Callout::new()
3509 .severity(Severity::Error)
3510 .title("Free Usage Exceeded")
3511 .description(ERROR_MESSAGE)
3512 .actions_slot(
3513 h_flex()
3514 .gap_0p5()
3515 .child(self.upgrade_button(cx))
3516 .child(self.create_copy_button(ERROR_MESSAGE)),
3517 )
3518 .dismiss_action(self.dismiss_error_button(cx))
3519 }
3520
3521 fn render_model_request_limit_reached_error(
3522 &self,
3523 plan: cloud_llm_client::Plan,
3524 cx: &mut Context<Self>,
3525 ) -> Callout {
3526 let error_message = match plan {
3527 cloud_llm_client::Plan::ZedPro => "Upgrade to usage-based billing for more prompts.",
3528 cloud_llm_client::Plan::ZedProTrial | cloud_llm_client::Plan::ZedFree => {
3529 "Upgrade to Zed Pro for more prompts."
3530 }
3531 };
3532
3533 Callout::new()
3534 .severity(Severity::Error)
3535 .title("Model Prompt Limit Reached")
3536 .description(error_message)
3537 .actions_slot(
3538 h_flex()
3539 .gap_0p5()
3540 .child(self.upgrade_button(cx))
3541 .child(self.create_copy_button(error_message)),
3542 )
3543 .dismiss_action(self.dismiss_error_button(cx))
3544 }
3545
3546 fn render_tool_use_limit_reached_error(
3547 &self,
3548 window: &mut Window,
3549 cx: &mut Context<Self>,
3550 ) -> Option<Callout> {
3551 let thread = self.as_native_thread(cx)?;
3552 let supports_burn_mode = thread
3553 .read(cx)
3554 .model()
3555 .map_or(false, |model| model.supports_burn_mode());
3556
3557 let focus_handle = self.focus_handle(cx);
3558
3559 Some(
3560 Callout::new()
3561 .icon(IconName::Info)
3562 .title("Consecutive tool use limit reached.")
3563 .actions_slot(
3564 h_flex()
3565 .gap_0p5()
3566 .when(supports_burn_mode, |this| {
3567 this.child(
3568 Button::new("continue-burn-mode", "Continue with Burn Mode")
3569 .style(ButtonStyle::Filled)
3570 .style(ButtonStyle::Tinted(ui::TintColor::Accent))
3571 .layer(ElevationIndex::ModalSurface)
3572 .label_size(LabelSize::Small)
3573 .key_binding(
3574 KeyBinding::for_action_in(
3575 &ContinueWithBurnMode,
3576 &focus_handle,
3577 window,
3578 cx,
3579 )
3580 .map(|kb| kb.size(rems_from_px(10.))),
3581 )
3582 .tooltip(Tooltip::text(
3583 "Enable Burn Mode for unlimited tool use.",
3584 ))
3585 .on_click({
3586 cx.listener(move |this, _, _window, cx| {
3587 thread.update(cx, |thread, cx| {
3588 thread
3589 .set_completion_mode(CompletionMode::Burn, cx);
3590 });
3591 this.resume_chat(cx);
3592 })
3593 }),
3594 )
3595 })
3596 .child(
3597 Button::new("continue-conversation", "Continue")
3598 .layer(ElevationIndex::ModalSurface)
3599 .label_size(LabelSize::Small)
3600 .key_binding(
3601 KeyBinding::for_action_in(
3602 &ContinueThread,
3603 &focus_handle,
3604 window,
3605 cx,
3606 )
3607 .map(|kb| kb.size(rems_from_px(10.))),
3608 )
3609 .on_click(cx.listener(|this, _, _window, cx| {
3610 this.resume_chat(cx);
3611 })),
3612 ),
3613 ),
3614 )
3615 }
3616
3617 fn create_copy_button(&self, message: impl Into<String>) -> impl IntoElement {
3618 let message = message.into();
3619
3620 IconButton::new("copy", IconName::Copy)
3621 .icon_size(IconSize::Small)
3622 .icon_color(Color::Muted)
3623 .tooltip(Tooltip::text("Copy Error Message"))
3624 .on_click(move |_, _, cx| {
3625 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
3626 })
3627 }
3628
3629 fn dismiss_error_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
3630 IconButton::new("dismiss", IconName::Close)
3631 .icon_size(IconSize::Small)
3632 .icon_color(Color::Muted)
3633 .tooltip(Tooltip::text("Dismiss Error"))
3634 .on_click(cx.listener({
3635 move |this, _, _, cx| {
3636 this.clear_thread_error(cx);
3637 cx.notify();
3638 }
3639 }))
3640 }
3641
3642 fn upgrade_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
3643 Button::new("upgrade", "Upgrade")
3644 .label_size(LabelSize::Small)
3645 .style(ButtonStyle::Tinted(ui::TintColor::Accent))
3646 .on_click(cx.listener({
3647 move |this, _, _, cx| {
3648 this.clear_thread_error(cx);
3649 cx.open_url(&zed_urls::upgrade_to_zed_pro_url(cx));
3650 }
3651 }))
3652 }
3653}
3654
3655impl Focusable for AcpThreadView {
3656 fn focus_handle(&self, cx: &App) -> FocusHandle {
3657 self.message_editor.focus_handle(cx)
3658 }
3659}
3660
3661impl Render for AcpThreadView {
3662 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
3663 let has_messages = self.list_state.item_count() > 0;
3664
3665 v_flex()
3666 .size_full()
3667 .key_context("AcpThread")
3668 .on_action(cx.listener(Self::open_agent_diff))
3669 .on_action(cx.listener(Self::toggle_burn_mode))
3670 .bg(cx.theme().colors().panel_background)
3671 .child(match &self.thread_state {
3672 ThreadState::Unauthenticated {
3673 connection,
3674 description,
3675 configuration_view,
3676 ..
3677 } => self.render_auth_required_state(
3678 connection,
3679 description.as_ref(),
3680 configuration_view.as_ref(),
3681 window,
3682 cx,
3683 ),
3684 ThreadState::Loading { .. } => v_flex().flex_1().child(self.render_empty_state(cx)),
3685 ThreadState::LoadError(e) => v_flex()
3686 .p_2()
3687 .flex_1()
3688 .items_center()
3689 .justify_center()
3690 .child(self.render_load_error(e, cx)),
3691 ThreadState::ServerExited { status } => v_flex()
3692 .p_2()
3693 .flex_1()
3694 .items_center()
3695 .justify_center()
3696 .child(self.render_server_exited(*status, cx)),
3697 ThreadState::Ready { thread, .. } => {
3698 let thread_clone = thread.clone();
3699
3700 v_flex().flex_1().map(|this| {
3701 if has_messages {
3702 this.child(
3703 list(
3704 self.list_state.clone(),
3705 cx.processor(|this, index: usize, window, cx| {
3706 let Some((entry, len)) = this.thread().and_then(|thread| {
3707 let entries = &thread.read(cx).entries();
3708 Some((entries.get(index)?, entries.len()))
3709 }) else {
3710 return Empty.into_any();
3711 };
3712 this.render_entry(index, len, entry, window, cx)
3713 }),
3714 )
3715 .with_sizing_behavior(gpui::ListSizingBehavior::Auto)
3716 .flex_grow()
3717 .into_any(),
3718 )
3719 .child(self.render_vertical_scrollbar(cx))
3720 .children(
3721 match thread_clone.read(cx).status() {
3722 ThreadStatus::Idle
3723 | ThreadStatus::WaitingForToolConfirmation => None,
3724 ThreadStatus::Generating => div()
3725 .px_5()
3726 .py_2()
3727 .child(LoadingLabel::new("").size(LabelSize::Small))
3728 .into(),
3729 },
3730 )
3731 } else {
3732 this.child(self.render_empty_state(cx))
3733 }
3734 })
3735 }
3736 })
3737 // The activity bar is intentionally rendered outside of the ThreadState::Ready match
3738 // above so that the scrollbar doesn't render behind it. The current setup allows
3739 // the scrollbar to stop exactly at the activity bar start.
3740 .when(has_messages, |this| match &self.thread_state {
3741 ThreadState::Ready { thread, .. } => {
3742 this.children(self.render_activity_bar(thread, window, cx))
3743 }
3744 _ => this,
3745 })
3746 .children(self.render_thread_retry_status_callout(window, cx))
3747 .children(self.render_thread_error(window, cx))
3748 .child(self.render_message_editor(window, cx))
3749 }
3750}
3751
3752fn default_markdown_style(buffer_font: bool, window: &Window, cx: &App) -> MarkdownStyle {
3753 let theme_settings = ThemeSettings::get_global(cx);
3754 let colors = cx.theme().colors();
3755
3756 let buffer_font_size = TextSize::Small.rems(cx);
3757
3758 let mut text_style = window.text_style();
3759 let line_height = buffer_font_size * 1.75;
3760
3761 let font_family = if buffer_font {
3762 theme_settings.buffer_font.family.clone()
3763 } else {
3764 theme_settings.ui_font.family.clone()
3765 };
3766
3767 let font_size = if buffer_font {
3768 TextSize::Small.rems(cx)
3769 } else {
3770 TextSize::Default.rems(cx)
3771 };
3772
3773 text_style.refine(&TextStyleRefinement {
3774 font_family: Some(font_family),
3775 font_fallbacks: theme_settings.ui_font.fallbacks.clone(),
3776 font_features: Some(theme_settings.ui_font.features.clone()),
3777 font_size: Some(font_size.into()),
3778 line_height: Some(line_height.into()),
3779 color: Some(cx.theme().colors().text),
3780 ..Default::default()
3781 });
3782
3783 MarkdownStyle {
3784 base_text_style: text_style.clone(),
3785 syntax: cx.theme().syntax().clone(),
3786 selection_background_color: cx.theme().colors().element_selection_background,
3787 code_block_overflow_x_scroll: true,
3788 table_overflow_x_scroll: true,
3789 heading_level_styles: Some(HeadingLevelStyles {
3790 h1: Some(TextStyleRefinement {
3791 font_size: Some(rems(1.15).into()),
3792 ..Default::default()
3793 }),
3794 h2: Some(TextStyleRefinement {
3795 font_size: Some(rems(1.1).into()),
3796 ..Default::default()
3797 }),
3798 h3: Some(TextStyleRefinement {
3799 font_size: Some(rems(1.05).into()),
3800 ..Default::default()
3801 }),
3802 h4: Some(TextStyleRefinement {
3803 font_size: Some(rems(1.).into()),
3804 ..Default::default()
3805 }),
3806 h5: Some(TextStyleRefinement {
3807 font_size: Some(rems(0.95).into()),
3808 ..Default::default()
3809 }),
3810 h6: Some(TextStyleRefinement {
3811 font_size: Some(rems(0.875).into()),
3812 ..Default::default()
3813 }),
3814 }),
3815 code_block: StyleRefinement {
3816 padding: EdgesRefinement {
3817 top: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
3818 left: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
3819 right: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
3820 bottom: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
3821 },
3822 margin: EdgesRefinement {
3823 top: Some(Length::Definite(Pixels(8.).into())),
3824 left: Some(Length::Definite(Pixels(0.).into())),
3825 right: Some(Length::Definite(Pixels(0.).into())),
3826 bottom: Some(Length::Definite(Pixels(12.).into())),
3827 },
3828 border_style: Some(BorderStyle::Solid),
3829 border_widths: EdgesRefinement {
3830 top: Some(AbsoluteLength::Pixels(Pixels(1.))),
3831 left: Some(AbsoluteLength::Pixels(Pixels(1.))),
3832 right: Some(AbsoluteLength::Pixels(Pixels(1.))),
3833 bottom: Some(AbsoluteLength::Pixels(Pixels(1.))),
3834 },
3835 border_color: Some(colors.border_variant),
3836 background: Some(colors.editor_background.into()),
3837 text: Some(TextStyleRefinement {
3838 font_family: Some(theme_settings.buffer_font.family.clone()),
3839 font_fallbacks: theme_settings.buffer_font.fallbacks.clone(),
3840 font_features: Some(theme_settings.buffer_font.features.clone()),
3841 font_size: Some(buffer_font_size.into()),
3842 ..Default::default()
3843 }),
3844 ..Default::default()
3845 },
3846 inline_code: TextStyleRefinement {
3847 font_family: Some(theme_settings.buffer_font.family.clone()),
3848 font_fallbacks: theme_settings.buffer_font.fallbacks.clone(),
3849 font_features: Some(theme_settings.buffer_font.features.clone()),
3850 font_size: Some(buffer_font_size.into()),
3851 background_color: Some(colors.editor_foreground.opacity(0.08)),
3852 ..Default::default()
3853 },
3854 link: TextStyleRefinement {
3855 background_color: Some(colors.editor_foreground.opacity(0.025)),
3856 underline: Some(UnderlineStyle {
3857 color: Some(colors.text_accent.opacity(0.5)),
3858 thickness: px(1.),
3859 ..Default::default()
3860 }),
3861 ..Default::default()
3862 },
3863 ..Default::default()
3864 }
3865}
3866
3867fn plan_label_markdown_style(
3868 status: &acp::PlanEntryStatus,
3869 window: &Window,
3870 cx: &App,
3871) -> MarkdownStyle {
3872 let default_md_style = default_markdown_style(false, window, cx);
3873
3874 MarkdownStyle {
3875 base_text_style: TextStyle {
3876 color: cx.theme().colors().text_muted,
3877 strikethrough: if matches!(status, acp::PlanEntryStatus::Completed) {
3878 Some(gpui::StrikethroughStyle {
3879 thickness: px(1.),
3880 color: Some(cx.theme().colors().text_muted.opacity(0.8)),
3881 })
3882 } else {
3883 None
3884 },
3885 ..default_md_style.base_text_style
3886 },
3887 ..default_md_style
3888 }
3889}
3890
3891fn terminal_command_markdown_style(window: &Window, cx: &App) -> MarkdownStyle {
3892 let default_md_style = default_markdown_style(true, window, cx);
3893
3894 MarkdownStyle {
3895 base_text_style: TextStyle {
3896 ..default_md_style.base_text_style
3897 },
3898 selection_background_color: cx.theme().colors().element_selection_background,
3899 ..Default::default()
3900 }
3901}
3902
3903#[cfg(test)]
3904pub(crate) mod tests {
3905 use acp_thread::StubAgentConnection;
3906 use agent::{TextThreadStore, ThreadStore};
3907 use agent_client_protocol::SessionId;
3908 use editor::EditorSettings;
3909 use fs::FakeFs;
3910 use gpui::{EventEmitter, SemanticVersion, TestAppContext, VisualTestContext};
3911 use project::Project;
3912 use serde_json::json;
3913 use settings::SettingsStore;
3914 use std::any::Any;
3915 use std::path::Path;
3916 use workspace::Item;
3917
3918 use super::*;
3919
3920 #[gpui::test]
3921 async fn test_drop(cx: &mut TestAppContext) {
3922 init_test(cx);
3923
3924 let (thread_view, _cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
3925 let weak_view = thread_view.downgrade();
3926 drop(thread_view);
3927 assert!(!weak_view.is_upgradable());
3928 }
3929
3930 #[gpui::test]
3931 async fn test_notification_for_stop_event(cx: &mut TestAppContext) {
3932 init_test(cx);
3933
3934 let (thread_view, cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
3935
3936 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
3937 message_editor.update_in(cx, |editor, window, cx| {
3938 editor.set_text("Hello", window, cx);
3939 });
3940
3941 cx.deactivate_window();
3942
3943 thread_view.update_in(cx, |thread_view, window, cx| {
3944 thread_view.send(window, cx);
3945 });
3946
3947 cx.run_until_parked();
3948
3949 assert!(
3950 cx.windows()
3951 .iter()
3952 .any(|window| window.downcast::<AgentNotification>().is_some())
3953 );
3954 }
3955
3956 #[gpui::test]
3957 async fn test_notification_for_error(cx: &mut TestAppContext) {
3958 init_test(cx);
3959
3960 let (thread_view, cx) =
3961 setup_thread_view(StubAgentServer::new(SaboteurAgentConnection), cx).await;
3962
3963 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
3964 message_editor.update_in(cx, |editor, window, cx| {
3965 editor.set_text("Hello", window, cx);
3966 });
3967
3968 cx.deactivate_window();
3969
3970 thread_view.update_in(cx, |thread_view, window, cx| {
3971 thread_view.send(window, cx);
3972 });
3973
3974 cx.run_until_parked();
3975
3976 assert!(
3977 cx.windows()
3978 .iter()
3979 .any(|window| window.downcast::<AgentNotification>().is_some())
3980 );
3981 }
3982
3983 #[gpui::test]
3984 async fn test_notification_for_tool_authorization(cx: &mut TestAppContext) {
3985 init_test(cx);
3986
3987 let tool_call_id = acp::ToolCallId("1".into());
3988 let tool_call = acp::ToolCall {
3989 id: tool_call_id.clone(),
3990 title: "Label".into(),
3991 kind: acp::ToolKind::Edit,
3992 status: acp::ToolCallStatus::Pending,
3993 content: vec!["hi".into()],
3994 locations: vec![],
3995 raw_input: None,
3996 raw_output: None,
3997 };
3998 let connection =
3999 StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
4000 tool_call_id,
4001 vec![acp::PermissionOption {
4002 id: acp::PermissionOptionId("1".into()),
4003 name: "Allow".into(),
4004 kind: acp::PermissionOptionKind::AllowOnce,
4005 }],
4006 )]));
4007
4008 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
4009
4010 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
4011
4012 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
4013 message_editor.update_in(cx, |editor, window, cx| {
4014 editor.set_text("Hello", window, cx);
4015 });
4016
4017 cx.deactivate_window();
4018
4019 thread_view.update_in(cx, |thread_view, window, cx| {
4020 thread_view.send(window, cx);
4021 });
4022
4023 cx.run_until_parked();
4024
4025 assert!(
4026 cx.windows()
4027 .iter()
4028 .any(|window| window.downcast::<AgentNotification>().is_some())
4029 );
4030 }
4031
4032 async fn setup_thread_view(
4033 agent: impl AgentServer + 'static,
4034 cx: &mut TestAppContext,
4035 ) -> (Entity<AcpThreadView>, &mut VisualTestContext) {
4036 let fs = FakeFs::new(cx.executor());
4037 let project = Project::test(fs, [], cx).await;
4038 let (workspace, cx) =
4039 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4040
4041 let thread_store =
4042 cx.update(|_window, cx| cx.new(|cx| ThreadStore::fake(project.clone(), cx)));
4043 let text_thread_store =
4044 cx.update(|_window, cx| cx.new(|cx| TextThreadStore::fake(project.clone(), cx)));
4045
4046 let thread_view = cx.update(|window, cx| {
4047 cx.new(|cx| {
4048 AcpThreadView::new(
4049 Rc::new(agent),
4050 None,
4051 workspace.downgrade(),
4052 project,
4053 thread_store.clone(),
4054 text_thread_store.clone(),
4055 window,
4056 cx,
4057 )
4058 })
4059 });
4060 cx.run_until_parked();
4061 (thread_view, cx)
4062 }
4063
4064 fn add_to_workspace(thread_view: Entity<AcpThreadView>, cx: &mut VisualTestContext) {
4065 let workspace = thread_view.read_with(cx, |thread_view, _cx| thread_view.workspace.clone());
4066
4067 workspace
4068 .update_in(cx, |workspace, window, cx| {
4069 workspace.add_item_to_active_pane(
4070 Box::new(cx.new(|_| ThreadViewItem(thread_view.clone()))),
4071 None,
4072 true,
4073 window,
4074 cx,
4075 );
4076 })
4077 .unwrap();
4078 }
4079
4080 struct ThreadViewItem(Entity<AcpThreadView>);
4081
4082 impl Item for ThreadViewItem {
4083 type Event = ();
4084
4085 fn include_in_nav_history() -> bool {
4086 false
4087 }
4088
4089 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
4090 "Test".into()
4091 }
4092 }
4093
4094 impl EventEmitter<()> for ThreadViewItem {}
4095
4096 impl Focusable for ThreadViewItem {
4097 fn focus_handle(&self, cx: &App) -> FocusHandle {
4098 self.0.read(cx).focus_handle(cx).clone()
4099 }
4100 }
4101
4102 impl Render for ThreadViewItem {
4103 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
4104 self.0.clone().into_any_element()
4105 }
4106 }
4107
4108 struct StubAgentServer<C> {
4109 connection: C,
4110 }
4111
4112 impl<C> StubAgentServer<C> {
4113 fn new(connection: C) -> Self {
4114 Self { connection }
4115 }
4116 }
4117
4118 impl StubAgentServer<StubAgentConnection> {
4119 fn default_response() -> Self {
4120 let conn = StubAgentConnection::new();
4121 conn.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk {
4122 content: "Default response".into(),
4123 }]);
4124 Self::new(conn)
4125 }
4126 }
4127
4128 impl<C> AgentServer for StubAgentServer<C>
4129 where
4130 C: 'static + AgentConnection + Send + Clone,
4131 {
4132 fn logo(&self) -> ui::IconName {
4133 ui::IconName::Ai
4134 }
4135
4136 fn name(&self) -> &'static str {
4137 "Test"
4138 }
4139
4140 fn empty_state_headline(&self) -> &'static str {
4141 "Test"
4142 }
4143
4144 fn empty_state_message(&self) -> &'static str {
4145 "Test"
4146 }
4147
4148 fn connect(
4149 &self,
4150 _root_dir: &Path,
4151 _project: &Entity<Project>,
4152 _cx: &mut App,
4153 ) -> Task<gpui::Result<Rc<dyn AgentConnection>>> {
4154 Task::ready(Ok(Rc::new(self.connection.clone())))
4155 }
4156
4157 fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
4158 self
4159 }
4160 }
4161
4162 #[derive(Clone)]
4163 struct SaboteurAgentConnection;
4164
4165 impl AgentConnection for SaboteurAgentConnection {
4166 fn new_thread(
4167 self: Rc<Self>,
4168 project: Entity<Project>,
4169 _cwd: &Path,
4170 cx: &mut gpui::App,
4171 ) -> Task<gpui::Result<Entity<AcpThread>>> {
4172 Task::ready(Ok(cx.new(|cx| {
4173 let action_log = cx.new(|_| ActionLog::new(project.clone()));
4174 AcpThread::new(
4175 "SaboteurAgentConnection",
4176 self,
4177 project,
4178 action_log,
4179 SessionId("test".into()),
4180 )
4181 })))
4182 }
4183
4184 fn auth_methods(&self) -> &[acp::AuthMethod] {
4185 &[]
4186 }
4187
4188 fn authenticate(
4189 &self,
4190 _method_id: acp::AuthMethodId,
4191 _cx: &mut App,
4192 ) -> Task<gpui::Result<()>> {
4193 unimplemented!()
4194 }
4195
4196 fn prompt(
4197 &self,
4198 _id: Option<acp_thread::UserMessageId>,
4199 _params: acp::PromptRequest,
4200 _cx: &mut App,
4201 ) -> Task<gpui::Result<acp::PromptResponse>> {
4202 Task::ready(Err(anyhow::anyhow!("Error prompting")))
4203 }
4204
4205 fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {
4206 unimplemented!()
4207 }
4208
4209 fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
4210 self
4211 }
4212 }
4213
4214 pub(crate) fn init_test(cx: &mut TestAppContext) {
4215 cx.update(|cx| {
4216 let settings_store = SettingsStore::test(cx);
4217 cx.set_global(settings_store);
4218 language::init(cx);
4219 Project::init_settings(cx);
4220 AgentSettings::register(cx);
4221 workspace::init_settings(cx);
4222 ThemeSettings::register(cx);
4223 release_channel::init(SemanticVersion::default(), cx);
4224 EditorSettings::register(cx);
4225 });
4226 }
4227
4228 #[gpui::test]
4229 async fn test_rewind_views(cx: &mut TestAppContext) {
4230 init_test(cx);
4231
4232 let fs = FakeFs::new(cx.executor());
4233 fs.insert_tree(
4234 "/project",
4235 json!({
4236 "test1.txt": "old content 1",
4237 "test2.txt": "old content 2"
4238 }),
4239 )
4240 .await;
4241 let project = Project::test(fs, [Path::new("/project")], cx).await;
4242 let (workspace, cx) =
4243 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4244
4245 let thread_store =
4246 cx.update(|_window, cx| cx.new(|cx| ThreadStore::fake(project.clone(), cx)));
4247 let text_thread_store =
4248 cx.update(|_window, cx| cx.new(|cx| TextThreadStore::fake(project.clone(), cx)));
4249
4250 let connection = Rc::new(StubAgentConnection::new());
4251 let thread_view = cx.update(|window, cx| {
4252 cx.new(|cx| {
4253 AcpThreadView::new(
4254 Rc::new(StubAgentServer::new(connection.as_ref().clone())),
4255 None,
4256 workspace.downgrade(),
4257 project.clone(),
4258 thread_store.clone(),
4259 text_thread_store.clone(),
4260 window,
4261 cx,
4262 )
4263 })
4264 });
4265
4266 cx.run_until_parked();
4267
4268 let thread = thread_view
4269 .read_with(cx, |view, _| view.thread().cloned())
4270 .unwrap();
4271
4272 // First user message
4273 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(acp::ToolCall {
4274 id: acp::ToolCallId("tool1".into()),
4275 title: "Edit file 1".into(),
4276 kind: acp::ToolKind::Edit,
4277 status: acp::ToolCallStatus::Completed,
4278 content: vec![acp::ToolCallContent::Diff {
4279 diff: acp::Diff {
4280 path: "/project/test1.txt".into(),
4281 old_text: Some("old content 1".into()),
4282 new_text: "new content 1".into(),
4283 },
4284 }],
4285 locations: vec![],
4286 raw_input: None,
4287 raw_output: None,
4288 })]);
4289
4290 thread
4291 .update(cx, |thread, cx| thread.send_raw("Give me a diff", cx))
4292 .await
4293 .unwrap();
4294 cx.run_until_parked();
4295
4296 thread.read_with(cx, |thread, _| {
4297 assert_eq!(thread.entries().len(), 2);
4298 });
4299
4300 thread_view.read_with(cx, |view, cx| {
4301 view.entry_view_state.read_with(cx, |entry_view_state, _| {
4302 assert!(
4303 entry_view_state
4304 .entry(0)
4305 .unwrap()
4306 .message_editor()
4307 .is_some()
4308 );
4309 assert!(entry_view_state.entry(1).unwrap().has_content());
4310 });
4311 });
4312
4313 // Second user message
4314 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(acp::ToolCall {
4315 id: acp::ToolCallId("tool2".into()),
4316 title: "Edit file 2".into(),
4317 kind: acp::ToolKind::Edit,
4318 status: acp::ToolCallStatus::Completed,
4319 content: vec![acp::ToolCallContent::Diff {
4320 diff: acp::Diff {
4321 path: "/project/test2.txt".into(),
4322 old_text: Some("old content 2".into()),
4323 new_text: "new content 2".into(),
4324 },
4325 }],
4326 locations: vec![],
4327 raw_input: None,
4328 raw_output: None,
4329 })]);
4330
4331 thread
4332 .update(cx, |thread, cx| thread.send_raw("Another one", cx))
4333 .await
4334 .unwrap();
4335 cx.run_until_parked();
4336
4337 let second_user_message_id = thread.read_with(cx, |thread, _| {
4338 assert_eq!(thread.entries().len(), 4);
4339 let AgentThreadEntry::UserMessage(user_message) = &thread.entries()[2] else {
4340 panic!();
4341 };
4342 user_message.id.clone().unwrap()
4343 });
4344
4345 thread_view.read_with(cx, |view, cx| {
4346 view.entry_view_state.read_with(cx, |entry_view_state, _| {
4347 assert!(
4348 entry_view_state
4349 .entry(0)
4350 .unwrap()
4351 .message_editor()
4352 .is_some()
4353 );
4354 assert!(entry_view_state.entry(1).unwrap().has_content());
4355 assert!(
4356 entry_view_state
4357 .entry(2)
4358 .unwrap()
4359 .message_editor()
4360 .is_some()
4361 );
4362 assert!(entry_view_state.entry(3).unwrap().has_content());
4363 });
4364 });
4365
4366 // Rewind to first message
4367 thread
4368 .update(cx, |thread, cx| thread.rewind(second_user_message_id, cx))
4369 .await
4370 .unwrap();
4371
4372 cx.run_until_parked();
4373
4374 thread.read_with(cx, |thread, _| {
4375 assert_eq!(thread.entries().len(), 2);
4376 });
4377
4378 thread_view.read_with(cx, |view, cx| {
4379 view.entry_view_state.read_with(cx, |entry_view_state, _| {
4380 assert!(
4381 entry_view_state
4382 .entry(0)
4383 .unwrap()
4384 .message_editor()
4385 .is_some()
4386 );
4387 assert!(entry_view_state.entry(1).unwrap().has_content());
4388
4389 // Old views should be dropped
4390 assert!(entry_view_state.entry(2).is_none());
4391 assert!(entry_view_state.entry(3).is_none());
4392 });
4393 });
4394 }
4395
4396 #[gpui::test]
4397 async fn test_message_editing_cancel(cx: &mut TestAppContext) {
4398 init_test(cx);
4399
4400 let connection = StubAgentConnection::new();
4401
4402 connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk {
4403 content: acp::ContentBlock::Text(acp::TextContent {
4404 text: "Response".into(),
4405 annotations: None,
4406 }),
4407 }]);
4408
4409 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
4410 add_to_workspace(thread_view.clone(), cx);
4411
4412 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
4413 message_editor.update_in(cx, |editor, window, cx| {
4414 editor.set_text("Original message to edit", window, cx);
4415 });
4416 thread_view.update_in(cx, |thread_view, window, cx| {
4417 thread_view.send(window, cx);
4418 });
4419
4420 cx.run_until_parked();
4421
4422 let user_message_editor = thread_view.read_with(cx, |view, cx| {
4423 assert_eq!(view.editing_message, None);
4424
4425 view.entry_view_state
4426 .read(cx)
4427 .entry(0)
4428 .unwrap()
4429 .message_editor()
4430 .unwrap()
4431 .clone()
4432 });
4433
4434 // Focus
4435 cx.focus(&user_message_editor);
4436 thread_view.read_with(cx, |view, _cx| {
4437 assert_eq!(view.editing_message, Some(0));
4438 });
4439
4440 // Edit
4441 user_message_editor.update_in(cx, |editor, window, cx| {
4442 editor.set_text("Edited message content", window, cx);
4443 });
4444
4445 // Cancel
4446 user_message_editor.update_in(cx, |_editor, window, cx| {
4447 window.dispatch_action(Box::new(editor::actions::Cancel), cx);
4448 });
4449
4450 thread_view.read_with(cx, |view, _cx| {
4451 assert_eq!(view.editing_message, None);
4452 });
4453
4454 user_message_editor.read_with(cx, |editor, cx| {
4455 assert_eq!(editor.text(cx), "Original message to edit");
4456 });
4457 }
4458
4459 #[gpui::test]
4460 async fn test_message_editing_regenerate(cx: &mut TestAppContext) {
4461 init_test(cx);
4462
4463 let connection = StubAgentConnection::new();
4464
4465 connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk {
4466 content: acp::ContentBlock::Text(acp::TextContent {
4467 text: "Response".into(),
4468 annotations: None,
4469 }),
4470 }]);
4471
4472 let (thread_view, cx) =
4473 setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
4474 add_to_workspace(thread_view.clone(), cx);
4475
4476 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
4477 message_editor.update_in(cx, |editor, window, cx| {
4478 editor.set_text("Original message to edit", window, cx);
4479 });
4480 thread_view.update_in(cx, |thread_view, window, cx| {
4481 thread_view.send(window, cx);
4482 });
4483
4484 cx.run_until_parked();
4485
4486 let user_message_editor = thread_view.read_with(cx, |view, cx| {
4487 assert_eq!(view.editing_message, None);
4488 assert_eq!(view.thread().unwrap().read(cx).entries().len(), 2);
4489
4490 view.entry_view_state
4491 .read(cx)
4492 .entry(0)
4493 .unwrap()
4494 .message_editor()
4495 .unwrap()
4496 .clone()
4497 });
4498
4499 // Focus
4500 cx.focus(&user_message_editor);
4501
4502 // Edit
4503 user_message_editor.update_in(cx, |editor, window, cx| {
4504 editor.set_text("Edited message content", window, cx);
4505 });
4506
4507 // Send
4508 connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk {
4509 content: acp::ContentBlock::Text(acp::TextContent {
4510 text: "New Response".into(),
4511 annotations: None,
4512 }),
4513 }]);
4514
4515 user_message_editor.update_in(cx, |_editor, window, cx| {
4516 window.dispatch_action(Box::new(Chat), cx);
4517 });
4518
4519 cx.run_until_parked();
4520
4521 thread_view.read_with(cx, |view, cx| {
4522 assert_eq!(view.editing_message, None);
4523
4524 let entries = view.thread().unwrap().read(cx).entries();
4525 assert_eq!(entries.len(), 2);
4526 assert_eq!(
4527 entries[0].to_markdown(cx),
4528 "## User\n\nEdited message content\n\n"
4529 );
4530 assert_eq!(
4531 entries[1].to_markdown(cx),
4532 "## Assistant\n\nNew Response\n\n"
4533 );
4534
4535 let new_editor = view.entry_view_state.read_with(cx, |state, _cx| {
4536 assert!(!state.entry(1).unwrap().has_content());
4537 state.entry(0).unwrap().message_editor().unwrap().clone()
4538 });
4539
4540 assert_eq!(new_editor.read(cx).text(cx), "Edited message content");
4541 })
4542 }
4543
4544 #[gpui::test]
4545 async fn test_message_editing_while_generating(cx: &mut TestAppContext) {
4546 init_test(cx);
4547
4548 let connection = StubAgentConnection::new();
4549
4550 let (thread_view, cx) =
4551 setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
4552 add_to_workspace(thread_view.clone(), cx);
4553
4554 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
4555 message_editor.update_in(cx, |editor, window, cx| {
4556 editor.set_text("Original message to edit", window, cx);
4557 });
4558 thread_view.update_in(cx, |thread_view, window, cx| {
4559 thread_view.send(window, cx);
4560 });
4561
4562 cx.run_until_parked();
4563
4564 let (user_message_editor, session_id) = thread_view.read_with(cx, |view, cx| {
4565 let thread = view.thread().unwrap().read(cx);
4566 assert_eq!(thread.entries().len(), 1);
4567
4568 let editor = view
4569 .entry_view_state
4570 .read(cx)
4571 .entry(0)
4572 .unwrap()
4573 .message_editor()
4574 .unwrap()
4575 .clone();
4576
4577 (editor, thread.session_id().clone())
4578 });
4579
4580 // Focus
4581 cx.focus(&user_message_editor);
4582
4583 thread_view.read_with(cx, |view, _cx| {
4584 assert_eq!(view.editing_message, Some(0));
4585 });
4586
4587 // Edit
4588 user_message_editor.update_in(cx, |editor, window, cx| {
4589 editor.set_text("Edited message content", window, cx);
4590 });
4591
4592 thread_view.read_with(cx, |view, _cx| {
4593 assert_eq!(view.editing_message, Some(0));
4594 });
4595
4596 // Finish streaming response
4597 cx.update(|_, cx| {
4598 connection.send_update(
4599 session_id.clone(),
4600 acp::SessionUpdate::AgentMessageChunk {
4601 content: acp::ContentBlock::Text(acp::TextContent {
4602 text: "Response".into(),
4603 annotations: None,
4604 }),
4605 },
4606 cx,
4607 );
4608 connection.end_turn(session_id, acp::StopReason::EndTurn);
4609 });
4610
4611 thread_view.read_with(cx, |view, _cx| {
4612 assert_eq!(view.editing_message, Some(0));
4613 });
4614
4615 cx.run_until_parked();
4616
4617 // Should still be editing
4618 cx.update(|window, cx| {
4619 assert!(user_message_editor.focus_handle(cx).is_focused(window));
4620 assert_eq!(thread_view.read(cx).editing_message, Some(0));
4621 assert_eq!(
4622 user_message_editor.read(cx).text(cx),
4623 "Edited message content"
4624 );
4625 });
4626 }
4627
4628 #[gpui::test]
4629 async fn test_interrupt(cx: &mut TestAppContext) {
4630 init_test(cx);
4631
4632 let connection = StubAgentConnection::new();
4633
4634 let (thread_view, cx) =
4635 setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
4636 add_to_workspace(thread_view.clone(), cx);
4637
4638 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
4639 message_editor.update_in(cx, |editor, window, cx| {
4640 editor.set_text("Message 1", window, cx);
4641 });
4642 thread_view.update_in(cx, |thread_view, window, cx| {
4643 thread_view.send(window, cx);
4644 });
4645
4646 let (thread, session_id) = thread_view.read_with(cx, |view, cx| {
4647 let thread = view.thread().unwrap();
4648
4649 (thread.clone(), thread.read(cx).session_id().clone())
4650 });
4651
4652 cx.run_until_parked();
4653
4654 cx.update(|_, cx| {
4655 connection.send_update(
4656 session_id.clone(),
4657 acp::SessionUpdate::AgentMessageChunk {
4658 content: "Message 1 resp".into(),
4659 },
4660 cx,
4661 );
4662 });
4663
4664 cx.run_until_parked();
4665
4666 thread.read_with(cx, |thread, cx| {
4667 assert_eq!(
4668 thread.to_markdown(cx),
4669 indoc::indoc! {"
4670 ## User
4671
4672 Message 1
4673
4674 ## Assistant
4675
4676 Message 1 resp
4677
4678 "}
4679 )
4680 });
4681
4682 message_editor.update_in(cx, |editor, window, cx| {
4683 editor.set_text("Message 2", window, cx);
4684 });
4685 thread_view.update_in(cx, |thread_view, window, cx| {
4686 thread_view.send(window, cx);
4687 });
4688
4689 cx.update(|_, cx| {
4690 // Simulate a response sent after beginning to cancel
4691 connection.send_update(
4692 session_id.clone(),
4693 acp::SessionUpdate::AgentMessageChunk {
4694 content: "onse".into(),
4695 },
4696 cx,
4697 );
4698 });
4699
4700 cx.run_until_parked();
4701
4702 // Last Message 1 response should appear before Message 2
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 response
4714
4715 ## User
4716
4717 Message 2
4718
4719 "}
4720 )
4721 });
4722
4723 cx.update(|_, cx| {
4724 connection.send_update(
4725 session_id.clone(),
4726 acp::SessionUpdate::AgentMessageChunk {
4727 content: "Message 2 response".into(),
4728 },
4729 cx,
4730 );
4731 connection.end_turn(session_id.clone(), acp::StopReason::EndTurn);
4732 });
4733
4734 cx.run_until_parked();
4735
4736 thread.read_with(cx, |thread, cx| {
4737 assert_eq!(
4738 thread.to_markdown(cx),
4739 indoc::indoc! {"
4740 ## User
4741
4742 Message 1
4743
4744 ## Assistant
4745
4746 Message 1 response
4747
4748 ## User
4749
4750 Message 2
4751
4752 ## Assistant
4753
4754 Message 2 response
4755
4756 "}
4757 )
4758 });
4759 }
4760}