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