1use acp_thread::{
2 AcpThread, AcpThreadEvent, AgentThreadEntry, AssistantMessage, AssistantMessageChunk,
3 AuthRequired, LoadError, MentionUri, RetryStatus, ThreadStatus, ToolCall, ToolCallContent,
4 ToolCallStatus, UserMessageId,
5};
6use acp_thread::{AgentConnection, Plan};
7use action_log::ActionLog;
8use agent::{TextThreadStore, ThreadStore};
9use agent_client_protocol::{self as acp};
10use agent_servers::{AgentServer, ClaudeCode};
11use agent_settings::{AgentProfileId, AgentSettings, CompletionMode, NotifyWhenAgentWaiting};
12use agent2::DbThreadMetadata;
13use anyhow::bail;
14use audio::{Audio, Sound};
15use buffer_diff::BufferDiff;
16use client::zed_urls;
17use collections::{HashMap, HashSet};
18use editor::scroll::Autoscroll;
19use editor::{Editor, EditorMode, MultiBuffer, PathKey, SelectionEffects};
20use file_icons::FileIcons;
21use fs::Fs;
22use gpui::{
23 Action, Animation, AnimationExt, AnyView, App, BorderStyle, ClickEvent, ClipboardItem,
24 EdgesRefinement, Empty, Entity, FocusHandle, Focusable, Hsla, Length, ListOffset, ListState,
25 MouseButton, PlatformDisplay, SharedString, Stateful, StyleRefinement, Subscription, Task,
26 TextStyle, TextStyleRefinement, Transformation, UnderlineStyle, WeakEntity, Window,
27 WindowHandle, div, linear_color_stop, linear_gradient, list, percentage, point, prelude::*,
28 pulsating_between,
29};
30use language::Buffer;
31
32use language_model::LanguageModelRegistry;
33use markdown::{HeadingLevelStyles, Markdown, MarkdownElement, MarkdownStyle};
34use project::{Project, ProjectEntryId};
35use prompt_store::PromptId;
36use rope::Point;
37use settings::{Settings as _, SettingsStore};
38use std::sync::Arc;
39use std::time::Instant;
40use std::{collections::BTreeMap, process::ExitStatus, rc::Rc, time::Duration};
41use text::Anchor;
42use theme::ThemeSettings;
43use ui::{
44 Callout, Disclosure, Divider, DividerColor, ElevationIndex, KeyBinding, PopoverMenuHandle,
45 Scrollbar, ScrollbarState, Tooltip, prelude::*,
46};
47use util::{ResultExt, size::format_file_size, time::duration_alt_display};
48use workspace::{CollaboratorId, Workspace};
49use zed_actions::agent::{Chat, ToggleModelSelector};
50use zed_actions::assistant::OpenRulesLibrary;
51
52use super::entry_view_state::EntryViewState;
53use crate::acp::AcpModelSelectorPopover;
54use crate::acp::entry_view_state::{EntryViewEvent, ViewEvent};
55use crate::acp::message_editor::{MessageEditor, MessageEditorEvent};
56use crate::agent_diff::AgentDiff;
57use crate::profile_selector::{ProfileProvider, ProfileSelector};
58use crate::ui::{AgentNotification, AgentNotificationEvent, BurnModeTooltip};
59use crate::{
60 AgentDiffPane, AgentPanel, ContinueThread, ContinueWithBurnMode, ExpandMessageEditor, Follow,
61 KeepAll, OpenAgentDiff, RejectAll, ToggleBurnMode, ToggleProfileSelector,
62};
63
64const RESPONSE_PADDING_X: Pixels = px(19.);
65pub const MIN_EDITOR_LINES: usize = 4;
66pub const MAX_EDITOR_LINES: usize = 8;
67
68enum ThreadError {
69 PaymentRequired,
70 ModelRequestLimitReached(cloud_llm_client::Plan),
71 ToolUseLimitReached,
72 Other(SharedString),
73}
74
75impl ThreadError {
76 fn from_err(error: anyhow::Error) -> Self {
77 if error.is::<language_model::PaymentRequiredError>() {
78 Self::PaymentRequired
79 } else if error.is::<language_model::ToolUseLimitReachedError>() {
80 Self::ToolUseLimitReached
81 } else if let Some(error) =
82 error.downcast_ref::<language_model::ModelRequestLimitReachedError>()
83 {
84 Self::ModelRequestLimitReached(error.plan)
85 } else {
86 Self::Other(error.to_string().into())
87 }
88 }
89}
90
91impl ProfileProvider for Entity<agent2::Thread> {
92 fn profile_id(&self, cx: &App) -> AgentProfileId {
93 self.read(cx).profile().clone()
94 }
95
96 fn set_profile(&self, profile_id: AgentProfileId, cx: &mut App) {
97 self.update(cx, |thread, _cx| {
98 thread.set_profile(profile_id);
99 });
100 }
101
102 fn profiles_supported(&self, cx: &App) -> bool {
103 self.read(cx)
104 .model()
105 .is_some_and(|model| model.supports_tools())
106 }
107}
108
109pub struct AcpThreadView {
110 agent: Rc<dyn AgentServer>,
111 workspace: WeakEntity<Workspace>,
112 project: Entity<Project>,
113 thread_state: ThreadState,
114 entry_view_state: Entity<EntryViewState>,
115 message_editor: Entity<MessageEditor>,
116 model_selector: Option<Entity<AcpModelSelectorPopover>>,
117 profile_selector: Option<Entity<ProfileSelector>>,
118 notifications: Vec<WindowHandle<AgentNotification>>,
119 notification_subscriptions: HashMap<WindowHandle<AgentNotification>, Vec<Subscription>>,
120 thread_retry_status: Option<RetryStatus>,
121 thread_error: Option<ThreadError>,
122 list_state: ListState,
123 scrollbar_state: ScrollbarState,
124 auth_task: Option<Task<()>>,
125 expanded_tool_calls: HashSet<acp::ToolCallId>,
126 expanded_thinking_blocks: HashSet<(usize, usize)>,
127 edits_expanded: bool,
128 plan_expanded: bool,
129 editor_expanded: bool,
130 terminal_expanded: bool,
131 editing_message: Option<usize>,
132 _cancel_task: Option<Task<()>>,
133 _subscriptions: [Subscription; 3],
134}
135
136enum ThreadState {
137 Loading {
138 _task: Task<()>,
139 },
140 Ready {
141 thread: Entity<AcpThread>,
142 _subscription: [Subscription; 2],
143 },
144 LoadError(LoadError),
145 Unauthenticated {
146 connection: Rc<dyn AgentConnection>,
147 description: Option<Entity<Markdown>>,
148 configuration_view: Option<AnyView>,
149 _subscription: Option<Subscription>,
150 },
151 ServerExited {
152 status: ExitStatus,
153 },
154}
155
156impl AcpThreadView {
157 pub fn new(
158 agent: Rc<dyn AgentServer>,
159 resume_thread: Option<DbThreadMetadata>,
160 workspace: WeakEntity<Workspace>,
161 project: Entity<Project>,
162 thread_store: Entity<ThreadStore>,
163 text_thread_store: Entity<TextThreadStore>,
164 window: &mut Window,
165 cx: &mut Context<Self>,
166 ) -> Self {
167 let prevent_slash_commands = agent.clone().downcast::<ClaudeCode>().is_some();
168 let message_editor = cx.new(|cx| {
169 MessageEditor::new(
170 workspace.clone(),
171 project.clone(),
172 thread_store.clone(),
173 text_thread_store.clone(),
174 "Message the agent - @ to include context",
175 prevent_slash_commands,
176 editor::EditorMode::AutoHeight {
177 min_lines: MIN_EDITOR_LINES,
178 max_lines: Some(MAX_EDITOR_LINES),
179 },
180 window,
181 cx,
182 )
183 });
184
185 let list_state = ListState::new(0, gpui::ListAlignment::Bottom, px(2048.0));
186
187 let entry_view_state = cx.new(|_| {
188 EntryViewState::new(
189 workspace.clone(),
190 project.clone(),
191 thread_store.clone(),
192 text_thread_store.clone(),
193 prevent_slash_commands,
194 )
195 });
196
197 let subscriptions = [
198 cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
199 cx.subscribe_in(&message_editor, window, Self::handle_message_editor_event),
200 cx.subscribe_in(&entry_view_state, window, Self::handle_entry_view_event),
201 ];
202
203 Self {
204 agent: agent.clone(),
205 workspace: workspace.clone(),
206 project: project.clone(),
207 entry_view_state,
208 thread_state: Self::initial_state(agent, resume_thread, workspace, project, window, cx),
209 message_editor,
210 model_selector: None,
211 profile_selector: None,
212 notifications: Vec::new(),
213 notification_subscriptions: HashMap::default(),
214 list_state: list_state.clone(),
215 scrollbar_state: ScrollbarState::new(list_state).parent_entity(&cx.entity()),
216 thread_retry_status: None,
217 thread_error: None,
218 auth_task: None,
219 expanded_tool_calls: HashSet::default(),
220 expanded_thinking_blocks: HashSet::default(),
221 editing_message: None,
222 edits_expanded: false,
223 plan_expanded: false,
224 editor_expanded: false,
225 terminal_expanded: true,
226 _subscriptions: subscriptions,
227 _cancel_task: None,
228 }
229 }
230
231 fn initial_state(
232 agent: Rc<dyn AgentServer>,
233 resume_thread: Option<DbThreadMetadata>,
234 workspace: WeakEntity<Workspace>,
235 project: Entity<Project>,
236 window: &mut Window,
237 cx: &mut Context<Self>,
238 ) -> ThreadState {
239 let root_dir = project
240 .read(cx)
241 .visible_worktrees(cx)
242 .next()
243 .map(|worktree| worktree.read(cx).abs_path())
244 .unwrap_or_else(|| paths::home_dir().as_path().into());
245
246 let connect_task = agent.connect(&root_dir, &project, cx);
247 let load_task = cx.spawn_in(window, async move |this, cx| {
248 let connection = match connect_task.await {
249 Ok(connection) => connection,
250 Err(err) => {
251 this.update(cx, |this, cx| {
252 this.handle_load_error(err, cx);
253 cx.notify();
254 })
255 .log_err();
256 return;
257 }
258 };
259
260 let result = if let Some(native_agent) = connection
261 .clone()
262 .downcast::<agent2::NativeAgentConnection>()
263 && let Some(resume) = resume_thread
264 {
265 cx.update(|_, cx| {
266 native_agent
267 .0
268 .update(cx, |agent, cx| agent.open_thread(resume.id, cx))
269 })
270 .log_err()
271 } else {
272 cx.update(|_, cx| {
273 connection
274 .clone()
275 .new_thread(project.clone(), &root_dir, cx)
276 })
277 .log_err()
278 };
279
280 let Some(result) = result else {
281 return;
282 };
283
284 let result = match result.await {
285 Err(e) => match e.downcast::<acp_thread::AuthRequired>() {
286 Ok(err) => {
287 cx.update(|window, cx| {
288 Self::handle_auth_required(this, err, agent, connection, window, cx)
289 })
290 .log_err();
291 return;
292 }
293 Err(err) => Err(err),
294 },
295 Ok(thread) => Ok(thread),
296 };
297
298 this.update_in(cx, |this, window, cx| {
299 match result {
300 Ok(thread) => {
301 let thread_subscription =
302 cx.subscribe_in(&thread, window, Self::handle_thread_event);
303
304 let action_log = thread.read(cx).action_log().clone();
305 let action_log_subscription =
306 cx.observe(&action_log, |_, _, cx| cx.notify());
307
308 let count = thread.read(cx).entries().len();
309 this.list_state.splice(0..0, count);
310 this.entry_view_state.update(cx, |view_state, cx| {
311 for ix in 0..count {
312 view_state.sync_entry(ix, &thread, window, cx);
313 }
314 });
315
316 AgentDiff::set_active_thread(&workspace, thread.clone(), window, cx);
317
318 this.model_selector =
319 thread
320 .read(cx)
321 .connection()
322 .model_selector()
323 .map(|selector| {
324 cx.new(|cx| {
325 AcpModelSelectorPopover::new(
326 thread.read(cx).session_id().clone(),
327 selector,
328 PopoverMenuHandle::default(),
329 this.focus_handle(cx),
330 window,
331 cx,
332 )
333 })
334 });
335
336 this.thread_state = ThreadState::Ready {
337 thread,
338 _subscription: [thread_subscription, action_log_subscription],
339 };
340
341 this.profile_selector = this.as_native_thread(cx).map(|thread| {
342 cx.new(|cx| {
343 ProfileSelector::new(
344 <dyn Fs>::global(cx),
345 Arc::new(thread.clone()),
346 this.focus_handle(cx),
347 cx,
348 )
349 })
350 });
351
352 cx.notify();
353 }
354 Err(err) => {
355 this.handle_load_error(err, cx);
356 }
357 };
358 })
359 .log_err();
360 });
361
362 ThreadState::Loading { _task: load_task }
363 }
364
365 fn handle_auth_required(
366 this: WeakEntity<Self>,
367 err: AuthRequired,
368 agent: Rc<dyn AgentServer>,
369 connection: Rc<dyn AgentConnection>,
370 window: &mut Window,
371 cx: &mut App,
372 ) {
373 let agent_name = agent.name();
374 let (configuration_view, subscription) = if let Some(provider_id) = err.provider_id {
375 let registry = LanguageModelRegistry::global(cx);
376
377 let sub = window.subscribe(®istry, cx, {
378 let provider_id = provider_id.clone();
379 let this = this.clone();
380 move |_, ev, window, cx| {
381 if let language_model::Event::ProviderStateChanged(updated_provider_id) = &ev
382 && &provider_id == updated_provider_id
383 {
384 this.update(cx, |this, cx| {
385 this.thread_state = Self::initial_state(
386 agent.clone(),
387 None,
388 this.workspace.clone(),
389 this.project.clone(),
390 window,
391 cx,
392 );
393 cx.notify();
394 })
395 .ok();
396 }
397 }
398 });
399
400 let view = registry.read(cx).provider(&provider_id).map(|provider| {
401 provider.configuration_view(
402 language_model::ConfigurationViewTargetAgent::Other(agent_name),
403 window,
404 cx,
405 )
406 });
407
408 (view, Some(sub))
409 } else {
410 (None, None)
411 };
412
413 this.update(cx, |this, cx| {
414 this.thread_state = ThreadState::Unauthenticated {
415 connection,
416 configuration_view,
417 description: err
418 .description
419 .clone()
420 .map(|desc| cx.new(|cx| Markdown::new(desc.into(), None, None, cx))),
421 _subscription: subscription,
422 };
423 cx.notify();
424 })
425 .ok();
426 }
427
428 fn handle_load_error(&mut self, err: anyhow::Error, cx: &mut Context<Self>) {
429 if let Some(load_err) = err.downcast_ref::<LoadError>() {
430 self.thread_state = ThreadState::LoadError(load_err.clone());
431 } else {
432 self.thread_state = ThreadState::LoadError(LoadError::Other(err.to_string().into()))
433 }
434 cx.notify();
435 }
436
437 pub fn thread(&self) -> Option<&Entity<AcpThread>> {
438 match &self.thread_state {
439 ThreadState::Ready { thread, .. } => Some(thread),
440 ThreadState::Unauthenticated { .. }
441 | ThreadState::Loading { .. }
442 | ThreadState::LoadError(..)
443 | ThreadState::ServerExited { .. } => None,
444 }
445 }
446
447 pub fn title(&self, cx: &App) -> SharedString {
448 match &self.thread_state {
449 ThreadState::Ready { thread, .. } => thread.read(cx).title(),
450 ThreadState::Loading { .. } => "Loading…".into(),
451 ThreadState::LoadError(_) => "Failed to load".into(),
452 ThreadState::Unauthenticated { .. } => "Authentication Required".into(),
453 ThreadState::ServerExited { .. } => "Server exited unexpectedly".into(),
454 }
455 }
456
457 pub fn cancel_generation(&mut self, cx: &mut Context<Self>) {
458 self.thread_error.take();
459 self.thread_retry_status.take();
460
461 if let Some(thread) = self.thread() {
462 self._cancel_task = Some(thread.update(cx, |thread, cx| thread.cancel(cx)));
463 }
464 }
465
466 pub fn expand_message_editor(
467 &mut self,
468 _: &ExpandMessageEditor,
469 _window: &mut Window,
470 cx: &mut Context<Self>,
471 ) {
472 self.set_editor_is_expanded(!self.editor_expanded, cx);
473 cx.notify();
474 }
475
476 fn set_editor_is_expanded(&mut self, is_expanded: bool, cx: &mut Context<Self>) {
477 self.editor_expanded = is_expanded;
478 self.message_editor.update(cx, |editor, cx| {
479 if is_expanded {
480 editor.set_mode(
481 EditorMode::Full {
482 scale_ui_elements_with_buffer_font_size: false,
483 show_active_line_background: false,
484 sized_by_content: false,
485 },
486 cx,
487 )
488 } else {
489 editor.set_mode(
490 EditorMode::AutoHeight {
491 min_lines: MIN_EDITOR_LINES,
492 max_lines: Some(MAX_EDITOR_LINES),
493 },
494 cx,
495 )
496 }
497 });
498 cx.notify();
499 }
500
501 pub fn handle_message_editor_event(
502 &mut self,
503 _: &Entity<MessageEditor>,
504 event: &MessageEditorEvent,
505 window: &mut Window,
506 cx: &mut Context<Self>,
507 ) {
508 match event {
509 MessageEditorEvent::Send => self.send(window, cx),
510 MessageEditorEvent::Cancel => self.cancel_generation(cx),
511 MessageEditorEvent::Focus => {
512 self.cancel_editing(&Default::default(), window, cx);
513 }
514 }
515 }
516
517 pub fn handle_entry_view_event(
518 &mut self,
519 _: &Entity<EntryViewState>,
520 event: &EntryViewEvent,
521 window: &mut Window,
522 cx: &mut Context<Self>,
523 ) {
524 match &event.view_event {
525 ViewEvent::MessageEditorEvent(_editor, MessageEditorEvent::Focus) => {
526 self.editing_message = Some(event.entry_index);
527 cx.notify();
528 }
529 ViewEvent::MessageEditorEvent(editor, MessageEditorEvent::Send) => {
530 self.regenerate(event.entry_index, editor, window, cx);
531 }
532 ViewEvent::MessageEditorEvent(_editor, MessageEditorEvent::Cancel) => {
533 self.cancel_editing(&Default::default(), window, cx);
534 }
535 }
536 }
537
538 fn resume_chat(&mut self, cx: &mut Context<Self>) {
539 self.thread_error.take();
540 let Some(thread) = self.thread() else {
541 return;
542 };
543
544 let task = thread.update(cx, |thread, cx| thread.resume(cx));
545 cx.spawn(async move |this, cx| {
546 let result = task.await;
547
548 this.update(cx, |this, cx| {
549 if let Err(err) = result {
550 this.handle_thread_error(err, cx);
551 }
552 })
553 })
554 .detach();
555 }
556
557 fn send(&mut self, window: &mut Window, cx: &mut Context<Self>) {
558 if let Some(thread) = self.thread()
559 && thread.read(cx).status() != ThreadStatus::Idle
560 {
561 self.stop_current_and_send_new_message(window, cx);
562 return;
563 }
564
565 let contents = self
566 .message_editor
567 .update(cx, |message_editor, cx| message_editor.contents(window, cx));
568 self.send_impl(contents, window, cx)
569 }
570
571 fn stop_current_and_send_new_message(&mut self, window: &mut Window, cx: &mut Context<Self>) {
572 let Some(thread) = self.thread().cloned() else {
573 return;
574 };
575
576 let cancelled = thread.update(cx, |thread, cx| thread.cancel(cx));
577
578 let contents = self
579 .message_editor
580 .update(cx, |message_editor, cx| message_editor.contents(window, cx));
581
582 cx.spawn_in(window, async move |this, cx| {
583 cancelled.await;
584
585 this.update_in(cx, |this, window, cx| {
586 this.send_impl(contents, window, cx);
587 })
588 .ok();
589 })
590 .detach();
591 }
592
593 fn send_impl(
594 &mut self,
595 contents: Task<anyhow::Result<Vec<acp::ContentBlock>>>,
596 window: &mut Window,
597 cx: &mut Context<Self>,
598 ) {
599 self.thread_error.take();
600 self.editing_message.take();
601
602 let Some(thread) = self.thread().cloned() else {
603 return;
604 };
605 let task = cx.spawn_in(window, async move |this, cx| {
606 let contents = contents.await?;
607
608 if contents.is_empty() {
609 return Ok(());
610 }
611
612 this.update_in(cx, |this, window, cx| {
613 this.set_editor_is_expanded(false, cx);
614 this.scroll_to_bottom(cx);
615 this.message_editor.update(cx, |message_editor, cx| {
616 message_editor.clear(window, cx);
617 });
618 })?;
619 let send = thread.update(cx, |thread, cx| thread.send(contents, cx))?;
620 send.await
621 });
622
623 cx.spawn(async move |this, cx| {
624 if let Err(err) = task.await {
625 this.update(cx, |this, cx| {
626 this.handle_thread_error(err, cx);
627 })
628 .ok();
629 }
630 })
631 .detach();
632 }
633
634 fn cancel_editing(&mut self, _: &ClickEvent, window: &mut Window, cx: &mut Context<Self>) {
635 let Some(thread) = self.thread().cloned() else {
636 return;
637 };
638
639 if let Some(index) = self.editing_message.take()
640 && let Some(editor) = self
641 .entry_view_state
642 .read(cx)
643 .entry(index)
644 .and_then(|e| e.message_editor())
645 .cloned()
646 {
647 editor.update(cx, |editor, cx| {
648 if let Some(user_message) = thread
649 .read(cx)
650 .entries()
651 .get(index)
652 .and_then(|e| e.user_message())
653 {
654 editor.set_message(user_message.chunks.clone(), window, cx);
655 }
656 })
657 };
658 self.focus_handle(cx).focus(window);
659 cx.notify();
660 }
661
662 fn regenerate(
663 &mut self,
664 entry_ix: usize,
665 message_editor: &Entity<MessageEditor>,
666 window: &mut Window,
667 cx: &mut Context<Self>,
668 ) {
669 let Some(thread) = self.thread().cloned() else {
670 return;
671 };
672
673 let Some(rewind) = thread.update(cx, |thread, cx| {
674 let user_message_id = thread.entries().get(entry_ix)?.user_message()?.id.clone()?;
675 Some(thread.rewind(user_message_id, cx))
676 }) else {
677 return;
678 };
679
680 let contents =
681 message_editor.update(cx, |message_editor, cx| message_editor.contents(window, cx));
682
683 let task = cx.foreground_executor().spawn(async move {
684 rewind.await?;
685 contents.await
686 });
687 self.send_impl(task, window, cx);
688 }
689
690 fn open_agent_diff(&mut self, _: &OpenAgentDiff, window: &mut Window, cx: &mut Context<Self>) {
691 if let Some(thread) = self.thread() {
692 AgentDiffPane::deploy(thread.clone(), self.workspace.clone(), window, cx).log_err();
693 }
694 }
695
696 fn open_edited_buffer(
697 &mut self,
698 buffer: &Entity<Buffer>,
699 window: &mut Window,
700 cx: &mut Context<Self>,
701 ) {
702 let Some(thread) = self.thread() else {
703 return;
704 };
705
706 let Some(diff) =
707 AgentDiffPane::deploy(thread.clone(), self.workspace.clone(), window, cx).log_err()
708 else {
709 return;
710 };
711
712 diff.update(cx, |diff, cx| {
713 diff.move_to_path(PathKey::for_buffer(buffer, cx), window, cx)
714 })
715 }
716
717 fn handle_open_rules(&mut self, _: &ClickEvent, window: &mut Window, cx: &mut Context<Self>) {
718 let Some(thread) = self.as_native_thread(cx) else {
719 return;
720 };
721 let project_context = thread.read(cx).project_context().read(cx);
722
723 let project_entry_ids = project_context
724 .worktrees
725 .iter()
726 .flat_map(|worktree| worktree.rules_file.as_ref())
727 .map(|rules_file| ProjectEntryId::from_usize(rules_file.project_entry_id))
728 .collect::<Vec<_>>();
729
730 self.workspace
731 .update(cx, move |workspace, cx| {
732 // TODO: Open a multibuffer instead? In some cases this doesn't make the set of rules
733 // files clear. For example, if rules file 1 is already open but rules file 2 is not,
734 // this would open and focus rules file 2 in a tab that is not next to rules file 1.
735 let project = workspace.project().read(cx);
736 let project_paths = project_entry_ids
737 .into_iter()
738 .flat_map(|entry_id| project.path_for_entry(entry_id, cx))
739 .collect::<Vec<_>>();
740 for project_path in project_paths {
741 workspace
742 .open_path(project_path, None, true, window, cx)
743 .detach_and_log_err(cx);
744 }
745 })
746 .ok();
747 }
748
749 fn handle_thread_error(&mut self, error: anyhow::Error, cx: &mut Context<Self>) {
750 self.thread_error = Some(ThreadError::from_err(error));
751 cx.notify();
752 }
753
754 fn clear_thread_error(&mut self, cx: &mut Context<Self>) {
755 self.thread_error = None;
756 cx.notify();
757 }
758
759 fn handle_thread_event(
760 &mut self,
761 thread: &Entity<AcpThread>,
762 event: &AcpThreadEvent,
763 window: &mut Window,
764 cx: &mut Context<Self>,
765 ) {
766 match event {
767 AcpThreadEvent::NewEntry => {
768 let len = thread.read(cx).entries().len();
769 let index = len - 1;
770 self.entry_view_state.update(cx, |view_state, cx| {
771 view_state.sync_entry(index, thread, window, cx)
772 });
773 self.list_state.splice(index..index, 1);
774 }
775 AcpThreadEvent::EntryUpdated(index) => {
776 self.entry_view_state.update(cx, |view_state, cx| {
777 view_state.sync_entry(*index, thread, window, cx)
778 });
779 self.list_state.splice(*index..index + 1, 1);
780 }
781 AcpThreadEvent::EntriesRemoved(range) => {
782 self.entry_view_state
783 .update(cx, |view_state, _cx| view_state.remove(range.clone()));
784 self.list_state.splice(range.clone(), 0);
785 }
786 AcpThreadEvent::ToolAuthorizationRequired => {
787 self.notify_with_sound("Waiting for tool confirmation", IconName::Info, window, cx);
788 }
789 AcpThreadEvent::Retry(retry) => {
790 self.thread_retry_status = Some(retry.clone());
791 }
792 AcpThreadEvent::Stopped => {
793 self.thread_retry_status.take();
794 let used_tools = thread.read(cx).used_tools_since_last_user_message();
795 self.notify_with_sound(
796 if used_tools {
797 "Finished running tools"
798 } else {
799 "New message"
800 },
801 IconName::ZedAssistant,
802 window,
803 cx,
804 );
805 }
806 AcpThreadEvent::Error => {
807 self.thread_retry_status.take();
808 self.notify_with_sound(
809 "Agent stopped due to an error",
810 IconName::Warning,
811 window,
812 cx,
813 );
814 }
815 AcpThreadEvent::ServerExited(status) => {
816 self.thread_retry_status.take();
817 self.thread_state = ThreadState::ServerExited { status: *status };
818 }
819 AcpThreadEvent::TitleUpdated => {}
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 .is_none_or(|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
2879 .thread()
2880 .is_some_and(|thread| thread.read(cx).status() != ThreadStatus::Idle);
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 if next_attempt_in_secs == 1 {
3459 format!(
3460 "Retrying. Next attempt in 1 second (Attempt {} of {}).",
3461 state.attempt, state.max_attempts,
3462 )
3463 } else {
3464 format!(
3465 "Retrying. Next attempt in {next_attempt_in_secs} seconds (Attempt {} of {}).",
3466 state.attempt, state.max_attempts,
3467 )
3468 };
3469
3470 Some(
3471 Callout::new()
3472 .severity(Severity::Warning)
3473 .title(state.last_error.clone())
3474 .description(retry_message),
3475 )
3476 }
3477
3478 fn render_thread_error(&self, window: &mut Window, cx: &mut Context<Self>) -> Option<Div> {
3479 let content = match self.thread_error.as_ref()? {
3480 ThreadError::Other(error) => self.render_any_thread_error(error.clone(), cx),
3481 ThreadError::PaymentRequired => self.render_payment_required_error(cx),
3482 ThreadError::ModelRequestLimitReached(plan) => {
3483 self.render_model_request_limit_reached_error(*plan, cx)
3484 }
3485 ThreadError::ToolUseLimitReached => {
3486 self.render_tool_use_limit_reached_error(window, cx)?
3487 }
3488 };
3489
3490 Some(div().child(content))
3491 }
3492
3493 fn render_any_thread_error(&self, error: SharedString, cx: &mut Context<'_, Self>) -> Callout {
3494 Callout::new()
3495 .severity(Severity::Error)
3496 .title("Error")
3497 .description(error.clone())
3498 .actions_slot(self.create_copy_button(error.to_string()))
3499 .dismiss_action(self.dismiss_error_button(cx))
3500 }
3501
3502 fn render_payment_required_error(&self, cx: &mut Context<Self>) -> Callout {
3503 const ERROR_MESSAGE: &str =
3504 "You reached your free usage limit. Upgrade to Zed Pro for more prompts.";
3505
3506 Callout::new()
3507 .severity(Severity::Error)
3508 .title("Free Usage Exceeded")
3509 .description(ERROR_MESSAGE)
3510 .actions_slot(
3511 h_flex()
3512 .gap_0p5()
3513 .child(self.upgrade_button(cx))
3514 .child(self.create_copy_button(ERROR_MESSAGE)),
3515 )
3516 .dismiss_action(self.dismiss_error_button(cx))
3517 }
3518
3519 fn render_model_request_limit_reached_error(
3520 &self,
3521 plan: cloud_llm_client::Plan,
3522 cx: &mut Context<Self>,
3523 ) -> Callout {
3524 let error_message = match plan {
3525 cloud_llm_client::Plan::ZedPro => "Upgrade to usage-based billing for more prompts.",
3526 cloud_llm_client::Plan::ZedProTrial | cloud_llm_client::Plan::ZedFree => {
3527 "Upgrade to Zed Pro for more prompts."
3528 }
3529 };
3530
3531 Callout::new()
3532 .severity(Severity::Error)
3533 .title("Model Prompt Limit Reached")
3534 .description(error_message)
3535 .actions_slot(
3536 h_flex()
3537 .gap_0p5()
3538 .child(self.upgrade_button(cx))
3539 .child(self.create_copy_button(error_message)),
3540 )
3541 .dismiss_action(self.dismiss_error_button(cx))
3542 }
3543
3544 fn render_tool_use_limit_reached_error(
3545 &self,
3546 window: &mut Window,
3547 cx: &mut Context<Self>,
3548 ) -> Option<Callout> {
3549 let thread = self.as_native_thread(cx)?;
3550 let supports_burn_mode = thread
3551 .read(cx)
3552 .model()
3553 .is_some_and(|model| model.supports_burn_mode());
3554
3555 let focus_handle = self.focus_handle(cx);
3556
3557 Some(
3558 Callout::new()
3559 .icon(IconName::Info)
3560 .title("Consecutive tool use limit reached.")
3561 .actions_slot(
3562 h_flex()
3563 .gap_0p5()
3564 .when(supports_burn_mode, |this| {
3565 this.child(
3566 Button::new("continue-burn-mode", "Continue with Burn Mode")
3567 .style(ButtonStyle::Filled)
3568 .style(ButtonStyle::Tinted(ui::TintColor::Accent))
3569 .layer(ElevationIndex::ModalSurface)
3570 .label_size(LabelSize::Small)
3571 .key_binding(
3572 KeyBinding::for_action_in(
3573 &ContinueWithBurnMode,
3574 &focus_handle,
3575 window,
3576 cx,
3577 )
3578 .map(|kb| kb.size(rems_from_px(10.))),
3579 )
3580 .tooltip(Tooltip::text(
3581 "Enable Burn Mode for unlimited tool use.",
3582 ))
3583 .on_click({
3584 cx.listener(move |this, _, _window, cx| {
3585 thread.update(cx, |thread, cx| {
3586 thread
3587 .set_completion_mode(CompletionMode::Burn, cx);
3588 });
3589 this.resume_chat(cx);
3590 })
3591 }),
3592 )
3593 })
3594 .child(
3595 Button::new("continue-conversation", "Continue")
3596 .layer(ElevationIndex::ModalSurface)
3597 .label_size(LabelSize::Small)
3598 .key_binding(
3599 KeyBinding::for_action_in(
3600 &ContinueThread,
3601 &focus_handle,
3602 window,
3603 cx,
3604 )
3605 .map(|kb| kb.size(rems_from_px(10.))),
3606 )
3607 .on_click(cx.listener(|this, _, _window, cx| {
3608 this.resume_chat(cx);
3609 })),
3610 ),
3611 ),
3612 )
3613 }
3614
3615 fn create_copy_button(&self, message: impl Into<String>) -> impl IntoElement {
3616 let message = message.into();
3617
3618 IconButton::new("copy", IconName::Copy)
3619 .icon_size(IconSize::Small)
3620 .icon_color(Color::Muted)
3621 .tooltip(Tooltip::text("Copy Error Message"))
3622 .on_click(move |_, _, cx| {
3623 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
3624 })
3625 }
3626
3627 fn dismiss_error_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
3628 IconButton::new("dismiss", IconName::Close)
3629 .icon_size(IconSize::Small)
3630 .icon_color(Color::Muted)
3631 .tooltip(Tooltip::text("Dismiss Error"))
3632 .on_click(cx.listener({
3633 move |this, _, _, cx| {
3634 this.clear_thread_error(cx);
3635 cx.notify();
3636 }
3637 }))
3638 }
3639
3640 fn upgrade_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
3641 Button::new("upgrade", "Upgrade")
3642 .label_size(LabelSize::Small)
3643 .style(ButtonStyle::Tinted(ui::TintColor::Accent))
3644 .on_click(cx.listener({
3645 move |this, _, _, cx| {
3646 this.clear_thread_error(cx);
3647 cx.open_url(&zed_urls::upgrade_to_zed_pro_url(cx));
3648 }
3649 }))
3650 }
3651}
3652
3653impl Focusable for AcpThreadView {
3654 fn focus_handle(&self, cx: &App) -> FocusHandle {
3655 self.message_editor.focus_handle(cx)
3656 }
3657}
3658
3659impl Render for AcpThreadView {
3660 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
3661 let has_messages = self.list_state.item_count() > 0;
3662
3663 v_flex()
3664 .size_full()
3665 .key_context("AcpThread")
3666 .on_action(cx.listener(Self::open_agent_diff))
3667 .on_action(cx.listener(Self::toggle_burn_mode))
3668 .bg(cx.theme().colors().panel_background)
3669 .child(match &self.thread_state {
3670 ThreadState::Unauthenticated {
3671 connection,
3672 description,
3673 configuration_view,
3674 ..
3675 } => self.render_auth_required_state(
3676 connection,
3677 description.as_ref(),
3678 configuration_view.as_ref(),
3679 window,
3680 cx,
3681 ),
3682 ThreadState::Loading { .. } => v_flex().flex_1().child(self.render_empty_state(cx)),
3683 ThreadState::LoadError(e) => v_flex()
3684 .p_2()
3685 .flex_1()
3686 .items_center()
3687 .justify_center()
3688 .child(self.render_load_error(e, cx)),
3689 ThreadState::ServerExited { status } => v_flex()
3690 .p_2()
3691 .flex_1()
3692 .items_center()
3693 .justify_center()
3694 .child(self.render_server_exited(*status, cx)),
3695 ThreadState::Ready { thread, .. } => {
3696 let thread_clone = thread.clone();
3697
3698 v_flex().flex_1().map(|this| {
3699 if has_messages {
3700 this.child(
3701 list(
3702 self.list_state.clone(),
3703 cx.processor(|this, index: usize, window, cx| {
3704 let Some((entry, len)) = this.thread().and_then(|thread| {
3705 let entries = &thread.read(cx).entries();
3706 Some((entries.get(index)?, entries.len()))
3707 }) else {
3708 return Empty.into_any();
3709 };
3710 this.render_entry(index, len, entry, window, cx)
3711 }),
3712 )
3713 .with_sizing_behavior(gpui::ListSizingBehavior::Auto)
3714 .flex_grow()
3715 .into_any(),
3716 )
3717 .child(self.render_vertical_scrollbar(cx))
3718 .children(
3719 match thread_clone.read(cx).status() {
3720 ThreadStatus::Idle
3721 | ThreadStatus::WaitingForToolConfirmation => None,
3722 ThreadStatus::Generating => div()
3723 .px_5()
3724 .py_2()
3725 .child(LoadingLabel::new("").size(LabelSize::Small))
3726 .into(),
3727 },
3728 )
3729 } else {
3730 this.child(self.render_empty_state(cx))
3731 }
3732 })
3733 }
3734 })
3735 // The activity bar is intentionally rendered outside of the ThreadState::Ready match
3736 // above so that the scrollbar doesn't render behind it. The current setup allows
3737 // the scrollbar to stop exactly at the activity bar start.
3738 .when(has_messages, |this| match &self.thread_state {
3739 ThreadState::Ready { thread, .. } => {
3740 this.children(self.render_activity_bar(thread, window, cx))
3741 }
3742 _ => this,
3743 })
3744 .children(self.render_thread_retry_status_callout(window, cx))
3745 .children(self.render_thread_error(window, cx))
3746 .child(self.render_message_editor(window, cx))
3747 }
3748}
3749
3750fn default_markdown_style(buffer_font: bool, window: &Window, cx: &App) -> MarkdownStyle {
3751 let theme_settings = ThemeSettings::get_global(cx);
3752 let colors = cx.theme().colors();
3753
3754 let buffer_font_size = TextSize::Small.rems(cx);
3755
3756 let mut text_style = window.text_style();
3757 let line_height = buffer_font_size * 1.75;
3758
3759 let font_family = if buffer_font {
3760 theme_settings.buffer_font.family.clone()
3761 } else {
3762 theme_settings.ui_font.family.clone()
3763 };
3764
3765 let font_size = if buffer_font {
3766 TextSize::Small.rems(cx)
3767 } else {
3768 TextSize::Default.rems(cx)
3769 };
3770
3771 text_style.refine(&TextStyleRefinement {
3772 font_family: Some(font_family),
3773 font_fallbacks: theme_settings.ui_font.fallbacks.clone(),
3774 font_features: Some(theme_settings.ui_font.features.clone()),
3775 font_size: Some(font_size.into()),
3776 line_height: Some(line_height.into()),
3777 color: Some(cx.theme().colors().text),
3778 ..Default::default()
3779 });
3780
3781 MarkdownStyle {
3782 base_text_style: text_style.clone(),
3783 syntax: cx.theme().syntax().clone(),
3784 selection_background_color: cx.theme().colors().element_selection_background,
3785 code_block_overflow_x_scroll: true,
3786 table_overflow_x_scroll: true,
3787 heading_level_styles: Some(HeadingLevelStyles {
3788 h1: Some(TextStyleRefinement {
3789 font_size: Some(rems(1.15).into()),
3790 ..Default::default()
3791 }),
3792 h2: Some(TextStyleRefinement {
3793 font_size: Some(rems(1.1).into()),
3794 ..Default::default()
3795 }),
3796 h3: Some(TextStyleRefinement {
3797 font_size: Some(rems(1.05).into()),
3798 ..Default::default()
3799 }),
3800 h4: Some(TextStyleRefinement {
3801 font_size: Some(rems(1.).into()),
3802 ..Default::default()
3803 }),
3804 h5: Some(TextStyleRefinement {
3805 font_size: Some(rems(0.95).into()),
3806 ..Default::default()
3807 }),
3808 h6: Some(TextStyleRefinement {
3809 font_size: Some(rems(0.875).into()),
3810 ..Default::default()
3811 }),
3812 }),
3813 code_block: StyleRefinement {
3814 padding: EdgesRefinement {
3815 top: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
3816 left: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
3817 right: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
3818 bottom: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
3819 },
3820 margin: EdgesRefinement {
3821 top: Some(Length::Definite(Pixels(8.).into())),
3822 left: Some(Length::Definite(Pixels(0.).into())),
3823 right: Some(Length::Definite(Pixels(0.).into())),
3824 bottom: Some(Length::Definite(Pixels(12.).into())),
3825 },
3826 border_style: Some(BorderStyle::Solid),
3827 border_widths: EdgesRefinement {
3828 top: Some(AbsoluteLength::Pixels(Pixels(1.))),
3829 left: Some(AbsoluteLength::Pixels(Pixels(1.))),
3830 right: Some(AbsoluteLength::Pixels(Pixels(1.))),
3831 bottom: Some(AbsoluteLength::Pixels(Pixels(1.))),
3832 },
3833 border_color: Some(colors.border_variant),
3834 background: Some(colors.editor_background.into()),
3835 text: Some(TextStyleRefinement {
3836 font_family: Some(theme_settings.buffer_font.family.clone()),
3837 font_fallbacks: theme_settings.buffer_font.fallbacks.clone(),
3838 font_features: Some(theme_settings.buffer_font.features.clone()),
3839 font_size: Some(buffer_font_size.into()),
3840 ..Default::default()
3841 }),
3842 ..Default::default()
3843 },
3844 inline_code: TextStyleRefinement {
3845 font_family: Some(theme_settings.buffer_font.family.clone()),
3846 font_fallbacks: theme_settings.buffer_font.fallbacks.clone(),
3847 font_features: Some(theme_settings.buffer_font.features.clone()),
3848 font_size: Some(buffer_font_size.into()),
3849 background_color: Some(colors.editor_foreground.opacity(0.08)),
3850 ..Default::default()
3851 },
3852 link: TextStyleRefinement {
3853 background_color: Some(colors.editor_foreground.opacity(0.025)),
3854 underline: Some(UnderlineStyle {
3855 color: Some(colors.text_accent.opacity(0.5)),
3856 thickness: px(1.),
3857 ..Default::default()
3858 }),
3859 ..Default::default()
3860 },
3861 ..Default::default()
3862 }
3863}
3864
3865fn plan_label_markdown_style(
3866 status: &acp::PlanEntryStatus,
3867 window: &Window,
3868 cx: &App,
3869) -> MarkdownStyle {
3870 let default_md_style = default_markdown_style(false, window, cx);
3871
3872 MarkdownStyle {
3873 base_text_style: TextStyle {
3874 color: cx.theme().colors().text_muted,
3875 strikethrough: if matches!(status, acp::PlanEntryStatus::Completed) {
3876 Some(gpui::StrikethroughStyle {
3877 thickness: px(1.),
3878 color: Some(cx.theme().colors().text_muted.opacity(0.8)),
3879 })
3880 } else {
3881 None
3882 },
3883 ..default_md_style.base_text_style
3884 },
3885 ..default_md_style
3886 }
3887}
3888
3889fn terminal_command_markdown_style(window: &Window, cx: &App) -> MarkdownStyle {
3890 let default_md_style = default_markdown_style(true, window, cx);
3891
3892 MarkdownStyle {
3893 base_text_style: TextStyle {
3894 ..default_md_style.base_text_style
3895 },
3896 selection_background_color: cx.theme().colors().element_selection_background,
3897 ..Default::default()
3898 }
3899}
3900
3901#[cfg(test)]
3902pub(crate) mod tests {
3903 use acp_thread::StubAgentConnection;
3904 use agent::{TextThreadStore, ThreadStore};
3905 use agent_client_protocol::SessionId;
3906 use editor::EditorSettings;
3907 use fs::FakeFs;
3908 use gpui::{EventEmitter, SemanticVersion, TestAppContext, VisualTestContext};
3909 use project::Project;
3910 use serde_json::json;
3911 use settings::SettingsStore;
3912 use std::any::Any;
3913 use std::path::Path;
3914 use workspace::Item;
3915
3916 use super::*;
3917
3918 #[gpui::test]
3919 async fn test_drop(cx: &mut TestAppContext) {
3920 init_test(cx);
3921
3922 let (thread_view, _cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
3923 let weak_view = thread_view.downgrade();
3924 drop(thread_view);
3925 assert!(!weak_view.is_upgradable());
3926 }
3927
3928 #[gpui::test]
3929 async fn test_notification_for_stop_event(cx: &mut TestAppContext) {
3930 init_test(cx);
3931
3932 let (thread_view, cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
3933
3934 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
3935 message_editor.update_in(cx, |editor, window, cx| {
3936 editor.set_text("Hello", window, cx);
3937 });
3938
3939 cx.deactivate_window();
3940
3941 thread_view.update_in(cx, |thread_view, window, cx| {
3942 thread_view.send(window, cx);
3943 });
3944
3945 cx.run_until_parked();
3946
3947 assert!(
3948 cx.windows()
3949 .iter()
3950 .any(|window| window.downcast::<AgentNotification>().is_some())
3951 );
3952 }
3953
3954 #[gpui::test]
3955 async fn test_notification_for_error(cx: &mut TestAppContext) {
3956 init_test(cx);
3957
3958 let (thread_view, cx) =
3959 setup_thread_view(StubAgentServer::new(SaboteurAgentConnection), cx).await;
3960
3961 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
3962 message_editor.update_in(cx, |editor, window, cx| {
3963 editor.set_text("Hello", window, cx);
3964 });
3965
3966 cx.deactivate_window();
3967
3968 thread_view.update_in(cx, |thread_view, window, cx| {
3969 thread_view.send(window, cx);
3970 });
3971
3972 cx.run_until_parked();
3973
3974 assert!(
3975 cx.windows()
3976 .iter()
3977 .any(|window| window.downcast::<AgentNotification>().is_some())
3978 );
3979 }
3980
3981 #[gpui::test]
3982 async fn test_notification_for_tool_authorization(cx: &mut TestAppContext) {
3983 init_test(cx);
3984
3985 let tool_call_id = acp::ToolCallId("1".into());
3986 let tool_call = acp::ToolCall {
3987 id: tool_call_id.clone(),
3988 title: "Label".into(),
3989 kind: acp::ToolKind::Edit,
3990 status: acp::ToolCallStatus::Pending,
3991 content: vec!["hi".into()],
3992 locations: vec![],
3993 raw_input: None,
3994 raw_output: None,
3995 };
3996 let connection =
3997 StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
3998 tool_call_id,
3999 vec![acp::PermissionOption {
4000 id: acp::PermissionOptionId("1".into()),
4001 name: "Allow".into(),
4002 kind: acp::PermissionOptionKind::AllowOnce,
4003 }],
4004 )]));
4005
4006 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
4007
4008 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
4009
4010 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
4011 message_editor.update_in(cx, |editor, window, cx| {
4012 editor.set_text("Hello", window, cx);
4013 });
4014
4015 cx.deactivate_window();
4016
4017 thread_view.update_in(cx, |thread_view, window, cx| {
4018 thread_view.send(window, cx);
4019 });
4020
4021 cx.run_until_parked();
4022
4023 assert!(
4024 cx.windows()
4025 .iter()
4026 .any(|window| window.downcast::<AgentNotification>().is_some())
4027 );
4028 }
4029
4030 async fn setup_thread_view(
4031 agent: impl AgentServer + 'static,
4032 cx: &mut TestAppContext,
4033 ) -> (Entity<AcpThreadView>, &mut VisualTestContext) {
4034 let fs = FakeFs::new(cx.executor());
4035 let project = Project::test(fs, [], cx).await;
4036 let (workspace, cx) =
4037 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4038
4039 let thread_store =
4040 cx.update(|_window, cx| cx.new(|cx| ThreadStore::fake(project.clone(), cx)));
4041 let text_thread_store =
4042 cx.update(|_window, cx| cx.new(|cx| TextThreadStore::fake(project.clone(), cx)));
4043
4044 let thread_view = cx.update(|window, cx| {
4045 cx.new(|cx| {
4046 AcpThreadView::new(
4047 Rc::new(agent),
4048 None,
4049 workspace.downgrade(),
4050 project,
4051 thread_store.clone(),
4052 text_thread_store.clone(),
4053 window,
4054 cx,
4055 )
4056 })
4057 });
4058 cx.run_until_parked();
4059 (thread_view, cx)
4060 }
4061
4062 fn add_to_workspace(thread_view: Entity<AcpThreadView>, cx: &mut VisualTestContext) {
4063 let workspace = thread_view.read_with(cx, |thread_view, _cx| thread_view.workspace.clone());
4064
4065 workspace
4066 .update_in(cx, |workspace, window, cx| {
4067 workspace.add_item_to_active_pane(
4068 Box::new(cx.new(|_| ThreadViewItem(thread_view.clone()))),
4069 None,
4070 true,
4071 window,
4072 cx,
4073 );
4074 })
4075 .unwrap();
4076 }
4077
4078 struct ThreadViewItem(Entity<AcpThreadView>);
4079
4080 impl Item for ThreadViewItem {
4081 type Event = ();
4082
4083 fn include_in_nav_history() -> bool {
4084 false
4085 }
4086
4087 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
4088 "Test".into()
4089 }
4090 }
4091
4092 impl EventEmitter<()> for ThreadViewItem {}
4093
4094 impl Focusable for ThreadViewItem {
4095 fn focus_handle(&self, cx: &App) -> FocusHandle {
4096 self.0.read(cx).focus_handle(cx).clone()
4097 }
4098 }
4099
4100 impl Render for ThreadViewItem {
4101 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
4102 self.0.clone().into_any_element()
4103 }
4104 }
4105
4106 struct StubAgentServer<C> {
4107 connection: C,
4108 }
4109
4110 impl<C> StubAgentServer<C> {
4111 fn new(connection: C) -> Self {
4112 Self { connection }
4113 }
4114 }
4115
4116 impl StubAgentServer<StubAgentConnection> {
4117 fn default_response() -> Self {
4118 let conn = StubAgentConnection::new();
4119 conn.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk {
4120 content: "Default response".into(),
4121 }]);
4122 Self::new(conn)
4123 }
4124 }
4125
4126 impl<C> AgentServer for StubAgentServer<C>
4127 where
4128 C: 'static + AgentConnection + Send + Clone,
4129 {
4130 fn logo(&self) -> ui::IconName {
4131 ui::IconName::Ai
4132 }
4133
4134 fn name(&self) -> &'static str {
4135 "Test"
4136 }
4137
4138 fn empty_state_headline(&self) -> &'static str {
4139 "Test"
4140 }
4141
4142 fn empty_state_message(&self) -> &'static str {
4143 "Test"
4144 }
4145
4146 fn connect(
4147 &self,
4148 _root_dir: &Path,
4149 _project: &Entity<Project>,
4150 _cx: &mut App,
4151 ) -> Task<gpui::Result<Rc<dyn AgentConnection>>> {
4152 Task::ready(Ok(Rc::new(self.connection.clone())))
4153 }
4154
4155 fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
4156 self
4157 }
4158 }
4159
4160 #[derive(Clone)]
4161 struct SaboteurAgentConnection;
4162
4163 impl AgentConnection for SaboteurAgentConnection {
4164 fn new_thread(
4165 self: Rc<Self>,
4166 project: Entity<Project>,
4167 _cwd: &Path,
4168 cx: &mut gpui::App,
4169 ) -> Task<gpui::Result<Entity<AcpThread>>> {
4170 Task::ready(Ok(cx.new(|cx| {
4171 let action_log = cx.new(|_| ActionLog::new(project.clone()));
4172 AcpThread::new(
4173 "SaboteurAgentConnection",
4174 self,
4175 project,
4176 action_log,
4177 SessionId("test".into()),
4178 )
4179 })))
4180 }
4181
4182 fn auth_methods(&self) -> &[acp::AuthMethod] {
4183 &[]
4184 }
4185
4186 fn authenticate(
4187 &self,
4188 _method_id: acp::AuthMethodId,
4189 _cx: &mut App,
4190 ) -> Task<gpui::Result<()>> {
4191 unimplemented!()
4192 }
4193
4194 fn prompt(
4195 &self,
4196 _id: Option<acp_thread::UserMessageId>,
4197 _params: acp::PromptRequest,
4198 _cx: &mut App,
4199 ) -> Task<gpui::Result<acp::PromptResponse>> {
4200 Task::ready(Err(anyhow::anyhow!("Error prompting")))
4201 }
4202
4203 fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {
4204 unimplemented!()
4205 }
4206
4207 fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
4208 self
4209 }
4210 }
4211
4212 pub(crate) fn init_test(cx: &mut TestAppContext) {
4213 cx.update(|cx| {
4214 let settings_store = SettingsStore::test(cx);
4215 cx.set_global(settings_store);
4216 language::init(cx);
4217 Project::init_settings(cx);
4218 AgentSettings::register(cx);
4219 workspace::init_settings(cx);
4220 ThemeSettings::register(cx);
4221 release_channel::init(SemanticVersion::default(), cx);
4222 EditorSettings::register(cx);
4223 });
4224 }
4225
4226 #[gpui::test]
4227 async fn test_rewind_views(cx: &mut TestAppContext) {
4228 init_test(cx);
4229
4230 let fs = FakeFs::new(cx.executor());
4231 fs.insert_tree(
4232 "/project",
4233 json!({
4234 "test1.txt": "old content 1",
4235 "test2.txt": "old content 2"
4236 }),
4237 )
4238 .await;
4239 let project = Project::test(fs, [Path::new("/project")], cx).await;
4240 let (workspace, cx) =
4241 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4242
4243 let thread_store =
4244 cx.update(|_window, cx| cx.new(|cx| ThreadStore::fake(project.clone(), cx)));
4245 let text_thread_store =
4246 cx.update(|_window, cx| cx.new(|cx| TextThreadStore::fake(project.clone(), cx)));
4247
4248 let connection = Rc::new(StubAgentConnection::new());
4249 let thread_view = cx.update(|window, cx| {
4250 cx.new(|cx| {
4251 AcpThreadView::new(
4252 Rc::new(StubAgentServer::new(connection.as_ref().clone())),
4253 None,
4254 workspace.downgrade(),
4255 project.clone(),
4256 thread_store.clone(),
4257 text_thread_store.clone(),
4258 window,
4259 cx,
4260 )
4261 })
4262 });
4263
4264 cx.run_until_parked();
4265
4266 let thread = thread_view
4267 .read_with(cx, |view, _| view.thread().cloned())
4268 .unwrap();
4269
4270 // First user message
4271 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(acp::ToolCall {
4272 id: acp::ToolCallId("tool1".into()),
4273 title: "Edit file 1".into(),
4274 kind: acp::ToolKind::Edit,
4275 status: acp::ToolCallStatus::Completed,
4276 content: vec![acp::ToolCallContent::Diff {
4277 diff: acp::Diff {
4278 path: "/project/test1.txt".into(),
4279 old_text: Some("old content 1".into()),
4280 new_text: "new content 1".into(),
4281 },
4282 }],
4283 locations: vec![],
4284 raw_input: None,
4285 raw_output: None,
4286 })]);
4287
4288 thread
4289 .update(cx, |thread, cx| thread.send_raw("Give me a diff", cx))
4290 .await
4291 .unwrap();
4292 cx.run_until_parked();
4293
4294 thread.read_with(cx, |thread, _| {
4295 assert_eq!(thread.entries().len(), 2);
4296 });
4297
4298 thread_view.read_with(cx, |view, cx| {
4299 view.entry_view_state.read_with(cx, |entry_view_state, _| {
4300 assert!(
4301 entry_view_state
4302 .entry(0)
4303 .unwrap()
4304 .message_editor()
4305 .is_some()
4306 );
4307 assert!(entry_view_state.entry(1).unwrap().has_content());
4308 });
4309 });
4310
4311 // Second user message
4312 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(acp::ToolCall {
4313 id: acp::ToolCallId("tool2".into()),
4314 title: "Edit file 2".into(),
4315 kind: acp::ToolKind::Edit,
4316 status: acp::ToolCallStatus::Completed,
4317 content: vec![acp::ToolCallContent::Diff {
4318 diff: acp::Diff {
4319 path: "/project/test2.txt".into(),
4320 old_text: Some("old content 2".into()),
4321 new_text: "new content 2".into(),
4322 },
4323 }],
4324 locations: vec![],
4325 raw_input: None,
4326 raw_output: None,
4327 })]);
4328
4329 thread
4330 .update(cx, |thread, cx| thread.send_raw("Another one", cx))
4331 .await
4332 .unwrap();
4333 cx.run_until_parked();
4334
4335 let second_user_message_id = thread.read_with(cx, |thread, _| {
4336 assert_eq!(thread.entries().len(), 4);
4337 let AgentThreadEntry::UserMessage(user_message) = &thread.entries()[2] else {
4338 panic!();
4339 };
4340 user_message.id.clone().unwrap()
4341 });
4342
4343 thread_view.read_with(cx, |view, cx| {
4344 view.entry_view_state.read_with(cx, |entry_view_state, _| {
4345 assert!(
4346 entry_view_state
4347 .entry(0)
4348 .unwrap()
4349 .message_editor()
4350 .is_some()
4351 );
4352 assert!(entry_view_state.entry(1).unwrap().has_content());
4353 assert!(
4354 entry_view_state
4355 .entry(2)
4356 .unwrap()
4357 .message_editor()
4358 .is_some()
4359 );
4360 assert!(entry_view_state.entry(3).unwrap().has_content());
4361 });
4362 });
4363
4364 // Rewind to first message
4365 thread
4366 .update(cx, |thread, cx| thread.rewind(second_user_message_id, cx))
4367 .await
4368 .unwrap();
4369
4370 cx.run_until_parked();
4371
4372 thread.read_with(cx, |thread, _| {
4373 assert_eq!(thread.entries().len(), 2);
4374 });
4375
4376 thread_view.read_with(cx, |view, cx| {
4377 view.entry_view_state.read_with(cx, |entry_view_state, _| {
4378 assert!(
4379 entry_view_state
4380 .entry(0)
4381 .unwrap()
4382 .message_editor()
4383 .is_some()
4384 );
4385 assert!(entry_view_state.entry(1).unwrap().has_content());
4386
4387 // Old views should be dropped
4388 assert!(entry_view_state.entry(2).is_none());
4389 assert!(entry_view_state.entry(3).is_none());
4390 });
4391 });
4392 }
4393
4394 #[gpui::test]
4395 async fn test_message_editing_cancel(cx: &mut TestAppContext) {
4396 init_test(cx);
4397
4398 let connection = StubAgentConnection::new();
4399
4400 connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk {
4401 content: acp::ContentBlock::Text(acp::TextContent {
4402 text: "Response".into(),
4403 annotations: None,
4404 }),
4405 }]);
4406
4407 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
4408 add_to_workspace(thread_view.clone(), cx);
4409
4410 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
4411 message_editor.update_in(cx, |editor, window, cx| {
4412 editor.set_text("Original message to edit", window, cx);
4413 });
4414 thread_view.update_in(cx, |thread_view, window, cx| {
4415 thread_view.send(window, cx);
4416 });
4417
4418 cx.run_until_parked();
4419
4420 let user_message_editor = thread_view.read_with(cx, |view, cx| {
4421 assert_eq!(view.editing_message, None);
4422
4423 view.entry_view_state
4424 .read(cx)
4425 .entry(0)
4426 .unwrap()
4427 .message_editor()
4428 .unwrap()
4429 .clone()
4430 });
4431
4432 // Focus
4433 cx.focus(&user_message_editor);
4434 thread_view.read_with(cx, |view, _cx| {
4435 assert_eq!(view.editing_message, Some(0));
4436 });
4437
4438 // Edit
4439 user_message_editor.update_in(cx, |editor, window, cx| {
4440 editor.set_text("Edited message content", window, cx);
4441 });
4442
4443 // Cancel
4444 user_message_editor.update_in(cx, |_editor, window, cx| {
4445 window.dispatch_action(Box::new(editor::actions::Cancel), cx);
4446 });
4447
4448 thread_view.read_with(cx, |view, _cx| {
4449 assert_eq!(view.editing_message, None);
4450 });
4451
4452 user_message_editor.read_with(cx, |editor, cx| {
4453 assert_eq!(editor.text(cx), "Original message to edit");
4454 });
4455 }
4456
4457 #[gpui::test]
4458 async fn test_message_editing_regenerate(cx: &mut TestAppContext) {
4459 init_test(cx);
4460
4461 let connection = StubAgentConnection::new();
4462
4463 connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk {
4464 content: acp::ContentBlock::Text(acp::TextContent {
4465 text: "Response".into(),
4466 annotations: None,
4467 }),
4468 }]);
4469
4470 let (thread_view, cx) =
4471 setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
4472 add_to_workspace(thread_view.clone(), cx);
4473
4474 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
4475 message_editor.update_in(cx, |editor, window, cx| {
4476 editor.set_text("Original message to edit", window, cx);
4477 });
4478 thread_view.update_in(cx, |thread_view, window, cx| {
4479 thread_view.send(window, cx);
4480 });
4481
4482 cx.run_until_parked();
4483
4484 let user_message_editor = thread_view.read_with(cx, |view, cx| {
4485 assert_eq!(view.editing_message, None);
4486 assert_eq!(view.thread().unwrap().read(cx).entries().len(), 2);
4487
4488 view.entry_view_state
4489 .read(cx)
4490 .entry(0)
4491 .unwrap()
4492 .message_editor()
4493 .unwrap()
4494 .clone()
4495 });
4496
4497 // Focus
4498 cx.focus(&user_message_editor);
4499
4500 // Edit
4501 user_message_editor.update_in(cx, |editor, window, cx| {
4502 editor.set_text("Edited message content", window, cx);
4503 });
4504
4505 // Send
4506 connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk {
4507 content: acp::ContentBlock::Text(acp::TextContent {
4508 text: "New Response".into(),
4509 annotations: None,
4510 }),
4511 }]);
4512
4513 user_message_editor.update_in(cx, |_editor, window, cx| {
4514 window.dispatch_action(Box::new(Chat), cx);
4515 });
4516
4517 cx.run_until_parked();
4518
4519 thread_view.read_with(cx, |view, cx| {
4520 assert_eq!(view.editing_message, None);
4521
4522 let entries = view.thread().unwrap().read(cx).entries();
4523 assert_eq!(entries.len(), 2);
4524 assert_eq!(
4525 entries[0].to_markdown(cx),
4526 "## User\n\nEdited message content\n\n"
4527 );
4528 assert_eq!(
4529 entries[1].to_markdown(cx),
4530 "## Assistant\n\nNew Response\n\n"
4531 );
4532
4533 let new_editor = view.entry_view_state.read_with(cx, |state, _cx| {
4534 assert!(!state.entry(1).unwrap().has_content());
4535 state.entry(0).unwrap().message_editor().unwrap().clone()
4536 });
4537
4538 assert_eq!(new_editor.read(cx).text(cx), "Edited message content");
4539 })
4540 }
4541
4542 #[gpui::test]
4543 async fn test_message_editing_while_generating(cx: &mut TestAppContext) {
4544 init_test(cx);
4545
4546 let connection = StubAgentConnection::new();
4547
4548 let (thread_view, cx) =
4549 setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
4550 add_to_workspace(thread_view.clone(), cx);
4551
4552 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
4553 message_editor.update_in(cx, |editor, window, cx| {
4554 editor.set_text("Original message to edit", window, cx);
4555 });
4556 thread_view.update_in(cx, |thread_view, window, cx| {
4557 thread_view.send(window, cx);
4558 });
4559
4560 cx.run_until_parked();
4561
4562 let (user_message_editor, session_id) = thread_view.read_with(cx, |view, cx| {
4563 let thread = view.thread().unwrap().read(cx);
4564 assert_eq!(thread.entries().len(), 1);
4565
4566 let editor = view
4567 .entry_view_state
4568 .read(cx)
4569 .entry(0)
4570 .unwrap()
4571 .message_editor()
4572 .unwrap()
4573 .clone();
4574
4575 (editor, thread.session_id().clone())
4576 });
4577
4578 // Focus
4579 cx.focus(&user_message_editor);
4580
4581 thread_view.read_with(cx, |view, _cx| {
4582 assert_eq!(view.editing_message, Some(0));
4583 });
4584
4585 // Edit
4586 user_message_editor.update_in(cx, |editor, window, cx| {
4587 editor.set_text("Edited message content", window, cx);
4588 });
4589
4590 thread_view.read_with(cx, |view, _cx| {
4591 assert_eq!(view.editing_message, Some(0));
4592 });
4593
4594 // Finish streaming response
4595 cx.update(|_, cx| {
4596 connection.send_update(
4597 session_id.clone(),
4598 acp::SessionUpdate::AgentMessageChunk {
4599 content: acp::ContentBlock::Text(acp::TextContent {
4600 text: "Response".into(),
4601 annotations: None,
4602 }),
4603 },
4604 cx,
4605 );
4606 connection.end_turn(session_id, acp::StopReason::EndTurn);
4607 });
4608
4609 thread_view.read_with(cx, |view, _cx| {
4610 assert_eq!(view.editing_message, Some(0));
4611 });
4612
4613 cx.run_until_parked();
4614
4615 // Should still be editing
4616 cx.update(|window, cx| {
4617 assert!(user_message_editor.focus_handle(cx).is_focused(window));
4618 assert_eq!(thread_view.read(cx).editing_message, Some(0));
4619 assert_eq!(
4620 user_message_editor.read(cx).text(cx),
4621 "Edited message content"
4622 );
4623 });
4624 }
4625
4626 #[gpui::test]
4627 async fn test_interrupt(cx: &mut TestAppContext) {
4628 init_test(cx);
4629
4630 let connection = StubAgentConnection::new();
4631
4632 let (thread_view, cx) =
4633 setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
4634 add_to_workspace(thread_view.clone(), cx);
4635
4636 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
4637 message_editor.update_in(cx, |editor, window, cx| {
4638 editor.set_text("Message 1", window, cx);
4639 });
4640 thread_view.update_in(cx, |thread_view, window, cx| {
4641 thread_view.send(window, cx);
4642 });
4643
4644 let (thread, session_id) = thread_view.read_with(cx, |view, cx| {
4645 let thread = view.thread().unwrap();
4646
4647 (thread.clone(), thread.read(cx).session_id().clone())
4648 });
4649
4650 cx.run_until_parked();
4651
4652 cx.update(|_, cx| {
4653 connection.send_update(
4654 session_id.clone(),
4655 acp::SessionUpdate::AgentMessageChunk {
4656 content: "Message 1 resp".into(),
4657 },
4658 cx,
4659 );
4660 });
4661
4662 cx.run_until_parked();
4663
4664 thread.read_with(cx, |thread, cx| {
4665 assert_eq!(
4666 thread.to_markdown(cx),
4667 indoc::indoc! {"
4668 ## User
4669
4670 Message 1
4671
4672 ## Assistant
4673
4674 Message 1 resp
4675
4676 "}
4677 )
4678 });
4679
4680 message_editor.update_in(cx, |editor, window, cx| {
4681 editor.set_text("Message 2", window, cx);
4682 });
4683 thread_view.update_in(cx, |thread_view, window, cx| {
4684 thread_view.send(window, cx);
4685 });
4686
4687 cx.update(|_, cx| {
4688 // Simulate a response sent after beginning to cancel
4689 connection.send_update(
4690 session_id.clone(),
4691 acp::SessionUpdate::AgentMessageChunk {
4692 content: "onse".into(),
4693 },
4694 cx,
4695 );
4696 });
4697
4698 cx.run_until_parked();
4699
4700 // Last Message 1 response should appear before Message 2
4701 thread.read_with(cx, |thread, cx| {
4702 assert_eq!(
4703 thread.to_markdown(cx),
4704 indoc::indoc! {"
4705 ## User
4706
4707 Message 1
4708
4709 ## Assistant
4710
4711 Message 1 response
4712
4713 ## User
4714
4715 Message 2
4716
4717 "}
4718 )
4719 });
4720
4721 cx.update(|_, cx| {
4722 connection.send_update(
4723 session_id.clone(),
4724 acp::SessionUpdate::AgentMessageChunk {
4725 content: "Message 2 response".into(),
4726 },
4727 cx,
4728 );
4729 connection.end_turn(session_id.clone(), acp::StopReason::EndTurn);
4730 });
4731
4732 cx.run_until_parked();
4733
4734 thread.read_with(cx, |thread, cx| {
4735 assert_eq!(
4736 thread.to_markdown(cx),
4737 indoc::indoc! {"
4738 ## User
4739
4740 Message 1
4741
4742 ## Assistant
4743
4744 Message 1 response
4745
4746 ## User
4747
4748 Message 2
4749
4750 ## Assistant
4751
4752 Message 2 response
4753
4754 "}
4755 )
4756 });
4757 }
4758}