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