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, ActionLogTelemetry};
8use agent::{DbThreadMetadata, HistoryEntry, HistoryEntryId, HistoryStore, NativeAgentServer};
9use agent_client_protocol::{self as acp, PromptCapabilities};
10use agent_servers::{AgentServer, AgentServerDelegate};
11use agent_settings::{AgentProfileId, AgentSettings, CompletionMode};
12use anyhow::{Result, anyhow};
13use arrayvec::ArrayVec;
14use audio::{Audio, Sound};
15use buffer_diff::BufferDiff;
16use client::zed_urls;
17use cloud_llm_client::PlanV1;
18use collections::{HashMap, HashSet};
19use editor::scroll::Autoscroll;
20use editor::{
21 Editor, EditorEvent, EditorMode, MultiBuffer, PathKey, SelectionEffects, SizingBehavior,
22};
23use file_icons::FileIcons;
24use fs::Fs;
25use futures::FutureExt as _;
26use gpui::{
27 Action, Animation, AnimationExt, AnyView, App, BorderStyle, ClickEvent, ClipboardItem,
28 CursorStyle, EdgesRefinement, ElementId, Empty, Entity, FocusHandle, Focusable, Hsla, Length,
29 ListOffset, ListState, PlatformDisplay, SharedString, StyleRefinement, Subscription, Task,
30 TextStyle, TextStyleRefinement, UnderlineStyle, WeakEntity, Window, WindowHandle, div,
31 ease_in_out, linear_color_stop, linear_gradient, list, point, pulsating_between,
32};
33use language::Buffer;
34
35use language_model::LanguageModelRegistry;
36use markdown::{HeadingLevelStyles, Markdown, MarkdownElement, MarkdownStyle};
37use project::{Project, ProjectEntryId};
38use prompt_store::{PromptId, PromptStore};
39use rope::Point;
40use settings::{NotifyWhenAgentWaiting, Settings as _, SettingsStore};
41use std::cell::RefCell;
42use std::path::Path;
43use std::sync::Arc;
44use std::time::Instant;
45use std::{collections::BTreeMap, rc::Rc, time::Duration};
46use terminal_view::terminal_panel::TerminalPanel;
47use text::Anchor;
48use theme::{AgentFontSize, ThemeSettings};
49use ui::{
50 Callout, CommonAnimationExt, Disclosure, Divider, DividerColor, ElevationIndex, KeyBinding,
51 PopoverMenuHandle, SpinnerLabel, TintColor, Tooltip, WithScrollbar, prelude::*,
52};
53use util::{ResultExt, size::format_file_size, time::duration_alt_display};
54use workspace::{CollaboratorId, Workspace};
55use zed_actions::agent::{Chat, ToggleModelSelector};
56use zed_actions::assistant::OpenRulesLibrary;
57
58use super::entry_view_state::EntryViewState;
59use crate::acp::AcpModelSelectorPopover;
60use crate::acp::ModeSelector;
61use crate::acp::entry_view_state::{EntryViewEvent, ViewEvent};
62use crate::acp::message_editor::{MessageEditor, MessageEditorEvent};
63use crate::agent_diff::AgentDiff;
64use crate::profile_selector::{ProfileProvider, ProfileSelector};
65
66use crate::ui::{
67 AgentNotification, AgentNotificationEvent, BurnModeTooltip, UnavailableEditingTooltip,
68 UsageCallout,
69};
70use crate::{
71 AgentDiffPane, AgentPanel, AllowAlways, AllowOnce, ContinueThread, ContinueWithBurnMode,
72 CycleModeSelector, ExpandMessageEditor, Follow, KeepAll, OpenAgentDiff, OpenHistory, RejectAll,
73 RejectOnce, ToggleBurnMode, ToggleProfileSelector,
74};
75
76#[derive(Copy, Clone, Debug, PartialEq, Eq)]
77enum ThreadFeedback {
78 Positive,
79 Negative,
80}
81
82#[derive(Debug)]
83enum ThreadError {
84 PaymentRequired,
85 ModelRequestLimitReached(cloud_llm_client::Plan),
86 ToolUseLimitReached,
87 Refusal,
88 AuthenticationRequired(SharedString),
89 Other(SharedString),
90}
91
92impl ThreadError {
93 fn from_err(error: anyhow::Error, agent: &Rc<dyn AgentServer>) -> Self {
94 if error.is::<language_model::PaymentRequiredError>() {
95 Self::PaymentRequired
96 } else if error.is::<language_model::ToolUseLimitReachedError>() {
97 Self::ToolUseLimitReached
98 } else if let Some(error) =
99 error.downcast_ref::<language_model::ModelRequestLimitReachedError>()
100 {
101 Self::ModelRequestLimitReached(error.plan)
102 } else if let Some(acp_error) = error.downcast_ref::<acp::Error>()
103 && acp_error.code == acp::ErrorCode::AUTH_REQUIRED.code
104 {
105 Self::AuthenticationRequired(acp_error.message.clone().into())
106 } else {
107 let string = format!("{:#}", error);
108 // TODO: we should have Gemini return better errors here.
109 if agent.clone().downcast::<agent_servers::Gemini>().is_some()
110 && string.contains("Could not load the default credentials")
111 || string.contains("API key not valid")
112 || string.contains("Request had invalid authentication credentials")
113 {
114 Self::AuthenticationRequired(string.into())
115 } else {
116 Self::Other(string.into())
117 }
118 }
119 }
120}
121
122impl ProfileProvider for Entity<agent::Thread> {
123 fn profile_id(&self, cx: &App) -> AgentProfileId {
124 self.read(cx).profile().clone()
125 }
126
127 fn set_profile(&self, profile_id: AgentProfileId, cx: &mut App) {
128 self.update(cx, |thread, cx| {
129 // Apply the profile and let the thread swap to its default model.
130 thread.set_profile(profile_id, cx);
131 });
132 }
133
134 fn profiles_supported(&self, cx: &App) -> bool {
135 self.read(cx)
136 .model()
137 .is_some_and(|model| model.supports_tools())
138 }
139}
140
141#[derive(Default)]
142struct ThreadFeedbackState {
143 feedback: Option<ThreadFeedback>,
144 comments_editor: Option<Entity<Editor>>,
145}
146
147impl ThreadFeedbackState {
148 pub fn submit(
149 &mut self,
150 thread: Entity<AcpThread>,
151 feedback: ThreadFeedback,
152 window: &mut Window,
153 cx: &mut App,
154 ) {
155 let Some(telemetry) = thread.read(cx).connection().telemetry() else {
156 return;
157 };
158
159 if self.feedback == Some(feedback) {
160 return;
161 }
162
163 self.feedback = Some(feedback);
164 match feedback {
165 ThreadFeedback::Positive => {
166 self.comments_editor = None;
167 }
168 ThreadFeedback::Negative => {
169 self.comments_editor = Some(Self::build_feedback_comments_editor(window, cx));
170 }
171 }
172 let session_id = thread.read(cx).session_id().clone();
173 let agent = thread.read(cx).connection().telemetry_id();
174 let task = telemetry.thread_data(&session_id, cx);
175 let rating = match feedback {
176 ThreadFeedback::Positive => "positive",
177 ThreadFeedback::Negative => "negative",
178 };
179 cx.background_spawn(async move {
180 let thread = task.await?;
181 telemetry::event!(
182 "Agent Thread Rated",
183 agent = agent,
184 session_id = session_id,
185 rating = rating,
186 thread = thread
187 );
188 anyhow::Ok(())
189 })
190 .detach_and_log_err(cx);
191 }
192
193 pub fn submit_comments(&mut self, thread: Entity<AcpThread>, cx: &mut App) {
194 let Some(telemetry) = thread.read(cx).connection().telemetry() else {
195 return;
196 };
197
198 let Some(comments) = self
199 .comments_editor
200 .as_ref()
201 .map(|editor| editor.read(cx).text(cx))
202 .filter(|text| !text.trim().is_empty())
203 else {
204 return;
205 };
206
207 self.comments_editor.take();
208
209 let session_id = thread.read(cx).session_id().clone();
210 let agent = thread.read(cx).connection().telemetry_id();
211 let task = telemetry.thread_data(&session_id, cx);
212 cx.background_spawn(async move {
213 let thread = task.await?;
214 telemetry::event!(
215 "Agent Thread Feedback Comments",
216 agent = agent,
217 session_id = session_id,
218 comments = comments,
219 thread = thread
220 );
221 anyhow::Ok(())
222 })
223 .detach_and_log_err(cx);
224 }
225
226 pub fn clear(&mut self) {
227 *self = Self::default()
228 }
229
230 pub fn dismiss_comments(&mut self) {
231 self.comments_editor.take();
232 }
233
234 fn build_feedback_comments_editor(window: &mut Window, cx: &mut App) -> Entity<Editor> {
235 let buffer = cx.new(|cx| {
236 let empty_string = String::new();
237 MultiBuffer::singleton(cx.new(|cx| Buffer::local(empty_string, cx)), cx)
238 });
239
240 let editor = cx.new(|cx| {
241 let mut editor = Editor::new(
242 editor::EditorMode::AutoHeight {
243 min_lines: 1,
244 max_lines: Some(4),
245 },
246 buffer,
247 None,
248 window,
249 cx,
250 );
251 editor.set_placeholder_text(
252 "What went wrong? Share your feedback so we can improve.",
253 window,
254 cx,
255 );
256 editor
257 });
258
259 editor.read(cx).focus_handle(cx).focus(window);
260 editor
261 }
262}
263
264pub struct AcpThreadView {
265 agent: Rc<dyn AgentServer>,
266 workspace: WeakEntity<Workspace>,
267 project: Entity<Project>,
268 thread_state: ThreadState,
269 login: Option<task::SpawnInTerminal>,
270 history_store: Entity<HistoryStore>,
271 hovered_recent_history_item: Option<usize>,
272 entry_view_state: Entity<EntryViewState>,
273 message_editor: Entity<MessageEditor>,
274 focus_handle: FocusHandle,
275 model_selector: Option<Entity<AcpModelSelectorPopover>>,
276 profile_selector: Option<Entity<ProfileSelector>>,
277 notifications: Vec<WindowHandle<AgentNotification>>,
278 notification_subscriptions: HashMap<WindowHandle<AgentNotification>, Vec<Subscription>>,
279 thread_retry_status: Option<RetryStatus>,
280 thread_error: Option<ThreadError>,
281 thread_error_markdown: Option<Entity<Markdown>>,
282 thread_feedback: ThreadFeedbackState,
283 list_state: ListState,
284 auth_task: Option<Task<()>>,
285 expanded_tool_calls: HashSet<acp::ToolCallId>,
286 expanded_thinking_blocks: HashSet<(usize, usize)>,
287 edits_expanded: bool,
288 plan_expanded: bool,
289 editor_expanded: bool,
290 should_be_following: bool,
291 editing_message: Option<usize>,
292 prompt_capabilities: Rc<RefCell<PromptCapabilities>>,
293 available_commands: Rc<RefCell<Vec<acp::AvailableCommand>>>,
294 is_loading_contents: bool,
295 new_server_version_available: Option<SharedString>,
296 resume_thread_metadata: Option<DbThreadMetadata>,
297 _cancel_task: Option<Task<()>>,
298 _subscriptions: [Subscription; 5],
299 show_codex_windows_warning: bool,
300}
301
302enum ThreadState {
303 Loading(Entity<LoadingView>),
304 Ready {
305 thread: Entity<AcpThread>,
306 title_editor: Option<Entity<Editor>>,
307 mode_selector: Option<Entity<ModeSelector>>,
308 _subscriptions: Vec<Subscription>,
309 },
310 LoadError(LoadError),
311 Unauthenticated {
312 connection: Rc<dyn AgentConnection>,
313 description: Option<Entity<Markdown>>,
314 configuration_view: Option<AnyView>,
315 pending_auth_method: Option<acp::AuthMethodId>,
316 _subscription: Option<Subscription>,
317 },
318}
319
320struct LoadingView {
321 title: SharedString,
322 _load_task: Task<()>,
323 _update_title_task: Task<anyhow::Result<()>>,
324}
325
326impl AcpThreadView {
327 pub fn new(
328 agent: Rc<dyn AgentServer>,
329 resume_thread: Option<DbThreadMetadata>,
330 summarize_thread: Option<DbThreadMetadata>,
331 workspace: WeakEntity<Workspace>,
332 project: Entity<Project>,
333 history_store: Entity<HistoryStore>,
334 prompt_store: Option<Entity<PromptStore>>,
335 window: &mut Window,
336 cx: &mut Context<Self>,
337 ) -> Self {
338 let prompt_capabilities = Rc::new(RefCell::new(acp::PromptCapabilities::default()));
339 let available_commands = Rc::new(RefCell::new(vec![]));
340
341 let placeholder = placeholder_text(agent.name().as_ref(), false);
342
343 let message_editor = cx.new(|cx| {
344 let mut editor = MessageEditor::new(
345 workspace.clone(),
346 project.clone(),
347 history_store.clone(),
348 prompt_store.clone(),
349 prompt_capabilities.clone(),
350 available_commands.clone(),
351 agent.name(),
352 &placeholder,
353 editor::EditorMode::AutoHeight {
354 min_lines: AgentSettings::get_global(cx).message_editor_min_lines,
355 max_lines: Some(AgentSettings::get_global(cx).set_message_editor_max_lines()),
356 },
357 window,
358 cx,
359 );
360 if let Some(entry) = summarize_thread {
361 editor.insert_thread_summary(entry, window, cx);
362 }
363 editor
364 });
365
366 let list_state = ListState::new(0, gpui::ListAlignment::Bottom, px(2048.0));
367
368 let entry_view_state = cx.new(|_| {
369 EntryViewState::new(
370 workspace.clone(),
371 project.clone(),
372 history_store.clone(),
373 prompt_store.clone(),
374 prompt_capabilities.clone(),
375 available_commands.clone(),
376 agent.name(),
377 )
378 });
379
380 let agent_server_store = project.read(cx).agent_server_store().clone();
381 let subscriptions = [
382 cx.observe_global_in::<SettingsStore>(window, Self::agent_ui_font_size_changed),
383 cx.observe_global_in::<AgentFontSize>(window, Self::agent_ui_font_size_changed),
384 cx.subscribe_in(&message_editor, window, Self::handle_message_editor_event),
385 cx.subscribe_in(&entry_view_state, window, Self::handle_entry_view_event),
386 cx.subscribe_in(
387 &agent_server_store,
388 window,
389 Self::handle_agent_servers_updated,
390 ),
391 ];
392
393 let show_codex_windows_warning = crate::ExternalAgent::parse_built_in(agent.as_ref())
394 == Some(crate::ExternalAgent::Codex);
395
396 Self {
397 agent: agent.clone(),
398 workspace: workspace.clone(),
399 project: project.clone(),
400 entry_view_state,
401 thread_state: Self::initial_state(
402 agent.clone(),
403 resume_thread.clone(),
404 workspace.clone(),
405 project.clone(),
406 window,
407 cx,
408 ),
409 login: None,
410 message_editor,
411 model_selector: None,
412 profile_selector: None,
413
414 notifications: Vec::new(),
415 notification_subscriptions: HashMap::default(),
416 list_state: list_state,
417 thread_retry_status: None,
418 thread_error: None,
419 thread_error_markdown: None,
420 thread_feedback: Default::default(),
421 auth_task: None,
422 expanded_tool_calls: HashSet::default(),
423 expanded_thinking_blocks: HashSet::default(),
424 editing_message: None,
425 edits_expanded: false,
426 plan_expanded: false,
427 prompt_capabilities,
428 available_commands,
429 editor_expanded: false,
430 should_be_following: false,
431 history_store,
432 hovered_recent_history_item: None,
433 is_loading_contents: false,
434 _subscriptions: subscriptions,
435 _cancel_task: None,
436 focus_handle: cx.focus_handle(),
437 new_server_version_available: None,
438 resume_thread_metadata: resume_thread,
439 show_codex_windows_warning,
440 }
441 }
442
443 fn reset(&mut self, window: &mut Window, cx: &mut Context<Self>) {
444 self.thread_state = Self::initial_state(
445 self.agent.clone(),
446 self.resume_thread_metadata.clone(),
447 self.workspace.clone(),
448 self.project.clone(),
449 window,
450 cx,
451 );
452 self.available_commands.replace(vec![]);
453 self.new_server_version_available.take();
454 cx.notify();
455 }
456
457 fn initial_state(
458 agent: Rc<dyn AgentServer>,
459 resume_thread: Option<DbThreadMetadata>,
460 workspace: WeakEntity<Workspace>,
461 project: Entity<Project>,
462 window: &mut Window,
463 cx: &mut Context<Self>,
464 ) -> ThreadState {
465 if project.read(cx).is_via_collab()
466 && agent.clone().downcast::<NativeAgentServer>().is_none()
467 {
468 return ThreadState::LoadError(LoadError::Other(
469 "External agents are not yet supported in shared projects.".into(),
470 ));
471 }
472 let mut worktrees = project.read(cx).visible_worktrees(cx).collect::<Vec<_>>();
473 // Pick the first non-single-file worktree for the root directory if there are any,
474 // and otherwise the parent of a single-file worktree, falling back to $HOME if there are no visible worktrees.
475 worktrees.sort_by(|l, r| {
476 l.read(cx)
477 .is_single_file()
478 .cmp(&r.read(cx).is_single_file())
479 });
480 let root_dir = worktrees
481 .into_iter()
482 .filter_map(|worktree| {
483 if worktree.read(cx).is_single_file() {
484 Some(worktree.read(cx).abs_path().parent()?.into())
485 } else {
486 Some(worktree.read(cx).abs_path())
487 }
488 })
489 .next();
490 let (status_tx, mut status_rx) = watch::channel("Loading…".into());
491 let (new_version_available_tx, mut new_version_available_rx) = watch::channel(None);
492 let delegate = AgentServerDelegate::new(
493 project.read(cx).agent_server_store().clone(),
494 project.clone(),
495 Some(status_tx),
496 Some(new_version_available_tx),
497 );
498
499 let connect_task = agent.connect(root_dir.as_deref(), delegate, cx);
500 let load_task = cx.spawn_in(window, async move |this, cx| {
501 let connection = match connect_task.await {
502 Ok((connection, login)) => {
503 this.update(cx, |this, _| this.login = login).ok();
504 connection
505 }
506 Err(err) => {
507 this.update_in(cx, |this, window, cx| {
508 if err.downcast_ref::<LoadError>().is_some() {
509 this.handle_load_error(err, window, cx);
510 } else {
511 this.handle_thread_error(err, cx);
512 }
513 cx.notify();
514 })
515 .log_err();
516 return;
517 }
518 };
519
520 let result = if let Some(native_agent) = connection
521 .clone()
522 .downcast::<agent::NativeAgentConnection>()
523 && let Some(resume) = resume_thread.clone()
524 {
525 cx.update(|_, cx| {
526 native_agent
527 .0
528 .update(cx, |agent, cx| agent.open_thread(resume.id, cx))
529 })
530 .log_err()
531 } else {
532 let root_dir = root_dir.unwrap_or(paths::home_dir().as_path().into());
533 cx.update(|_, cx| {
534 connection
535 .clone()
536 .new_thread(project.clone(), &root_dir, cx)
537 })
538 .log_err()
539 };
540
541 let Some(result) = result else {
542 return;
543 };
544
545 let result = match result.await {
546 Err(e) => match e.downcast::<acp_thread::AuthRequired>() {
547 Ok(err) => {
548 cx.update(|window, cx| {
549 Self::handle_auth_required(this, err, agent, connection, window, cx)
550 })
551 .log_err();
552 return;
553 }
554 Err(err) => Err(err),
555 },
556 Ok(thread) => Ok(thread),
557 };
558
559 this.update_in(cx, |this, window, cx| {
560 match result {
561 Ok(thread) => {
562 let action_log = thread.read(cx).action_log().clone();
563
564 this.prompt_capabilities
565 .replace(thread.read(cx).prompt_capabilities());
566
567 let count = thread.read(cx).entries().len();
568 this.entry_view_state.update(cx, |view_state, cx| {
569 for ix in 0..count {
570 view_state.sync_entry(ix, &thread, window, cx);
571 }
572 this.list_state.splice_focusable(
573 0..0,
574 (0..count).map(|ix| view_state.entry(ix)?.focus_handle(cx)),
575 );
576 });
577
578 if let Some(resume) = resume_thread {
579 this.history_store.update(cx, |history, cx| {
580 history.push_recently_opened_entry(
581 HistoryEntryId::AcpThread(resume.id),
582 cx,
583 );
584 });
585 }
586
587 AgentDiff::set_active_thread(&workspace, thread.clone(), window, cx);
588
589 this.model_selector = thread
590 .read(cx)
591 .connection()
592 .model_selector(thread.read(cx).session_id())
593 .map(|selector| {
594 cx.new(|cx| {
595 AcpModelSelectorPopover::new(
596 selector,
597 PopoverMenuHandle::default(),
598 this.focus_handle(cx),
599 window,
600 cx,
601 )
602 })
603 });
604
605 let mode_selector = thread
606 .read(cx)
607 .connection()
608 .session_modes(thread.read(cx).session_id(), cx)
609 .map(|session_modes| {
610 let fs = this.project.read(cx).fs().clone();
611 let focus_handle = this.focus_handle(cx);
612 cx.new(|_cx| {
613 ModeSelector::new(
614 session_modes,
615 this.agent.clone(),
616 fs,
617 focus_handle,
618 )
619 })
620 });
621
622 let mut subscriptions = vec![
623 cx.subscribe_in(&thread, window, Self::handle_thread_event),
624 cx.observe(&action_log, |_, _, cx| cx.notify()),
625 ];
626
627 let title_editor =
628 if thread.update(cx, |thread, cx| thread.can_set_title(cx)) {
629 let editor = cx.new(|cx| {
630 let mut editor = Editor::single_line(window, cx);
631 editor.set_text(thread.read(cx).title(), window, cx);
632 editor
633 });
634 subscriptions.push(cx.subscribe_in(
635 &editor,
636 window,
637 Self::handle_title_editor_event,
638 ));
639 Some(editor)
640 } else {
641 None
642 };
643
644 this.thread_state = ThreadState::Ready {
645 thread,
646 title_editor,
647 mode_selector,
648 _subscriptions: subscriptions,
649 };
650 this.message_editor.focus_handle(cx).focus(window);
651
652 this.profile_selector = this.as_native_thread(cx).map(|thread| {
653 cx.new(|cx| {
654 ProfileSelector::new(
655 <dyn Fs>::global(cx),
656 Arc::new(thread.clone()),
657 this.focus_handle(cx),
658 cx,
659 )
660 })
661 });
662
663 cx.notify();
664 }
665 Err(err) => {
666 this.handle_load_error(err, window, cx);
667 }
668 };
669 })
670 .log_err();
671 });
672
673 cx.spawn(async move |this, cx| {
674 while let Ok(new_version) = new_version_available_rx.recv().await {
675 if let Some(new_version) = new_version {
676 this.update(cx, |this, cx| {
677 this.new_server_version_available = Some(new_version.into());
678 cx.notify();
679 })
680 .log_err();
681 }
682 }
683 })
684 .detach();
685
686 let loading_view = cx.new(|cx| {
687 let update_title_task = cx.spawn(async move |this, cx| {
688 loop {
689 let status = status_rx.recv().await?;
690 this.update(cx, |this: &mut LoadingView, cx| {
691 this.title = status;
692 cx.notify();
693 })?;
694 }
695 });
696
697 LoadingView {
698 title: "Loading…".into(),
699 _load_task: load_task,
700 _update_title_task: update_title_task,
701 }
702 });
703
704 ThreadState::Loading(loading_view)
705 }
706
707 fn handle_auth_required(
708 this: WeakEntity<Self>,
709 err: AuthRequired,
710 agent: Rc<dyn AgentServer>,
711 connection: Rc<dyn AgentConnection>,
712 window: &mut Window,
713 cx: &mut App,
714 ) {
715 let agent_name = agent.name();
716 let (configuration_view, subscription) = if let Some(provider_id) = err.provider_id {
717 let registry = LanguageModelRegistry::global(cx);
718
719 let sub = window.subscribe(®istry, cx, {
720 let provider_id = provider_id.clone();
721 let this = this.clone();
722 move |_, ev, window, cx| {
723 if let language_model::Event::ProviderStateChanged(updated_provider_id) = &ev
724 && &provider_id == updated_provider_id
725 && LanguageModelRegistry::global(cx)
726 .read(cx)
727 .provider(&provider_id)
728 .map_or(false, |provider| provider.is_authenticated(cx))
729 {
730 this.update(cx, |this, cx| {
731 this.reset(window, cx);
732 })
733 .ok();
734 }
735 }
736 });
737
738 let view = registry.read(cx).provider(&provider_id).map(|provider| {
739 provider.configuration_view(
740 language_model::ConfigurationViewTargetAgent::Other(agent_name.clone()),
741 window,
742 cx,
743 )
744 });
745
746 (view, Some(sub))
747 } else {
748 (None, None)
749 };
750
751 this.update(cx, |this, cx| {
752 this.thread_state = ThreadState::Unauthenticated {
753 pending_auth_method: None,
754 connection,
755 configuration_view,
756 description: err
757 .description
758 .clone()
759 .map(|desc| cx.new(|cx| Markdown::new(desc.into(), None, None, cx))),
760 _subscription: subscription,
761 };
762 if this.message_editor.focus_handle(cx).is_focused(window) {
763 this.focus_handle.focus(window)
764 }
765 cx.notify();
766 })
767 .ok();
768 }
769
770 fn handle_load_error(
771 &mut self,
772 err: anyhow::Error,
773 window: &mut Window,
774 cx: &mut Context<Self>,
775 ) {
776 if let Some(load_err) = err.downcast_ref::<LoadError>() {
777 self.thread_state = ThreadState::LoadError(load_err.clone());
778 } else {
779 self.thread_state =
780 ThreadState::LoadError(LoadError::Other(format!("{:#}", err).into()))
781 }
782 if self.message_editor.focus_handle(cx).is_focused(window) {
783 self.focus_handle.focus(window)
784 }
785 cx.notify();
786 }
787
788 fn handle_agent_servers_updated(
789 &mut self,
790 _agent_server_store: &Entity<project::AgentServerStore>,
791 _event: &project::AgentServersUpdated,
792 window: &mut Window,
793 cx: &mut Context<Self>,
794 ) {
795 // If we're in a LoadError state OR have a thread_error set (which can happen
796 // when agent.connect() fails during loading), retry loading the thread.
797 // This handles the case where a thread is restored before authentication completes.
798 let should_retry =
799 matches!(&self.thread_state, ThreadState::LoadError(_)) || self.thread_error.is_some();
800
801 if should_retry {
802 self.thread_error = None;
803 self.thread_error_markdown = None;
804 self.reset(window, cx);
805 }
806 }
807
808 pub fn workspace(&self) -> &WeakEntity<Workspace> {
809 &self.workspace
810 }
811
812 pub fn thread(&self) -> Option<&Entity<AcpThread>> {
813 match &self.thread_state {
814 ThreadState::Ready { thread, .. } => Some(thread),
815 ThreadState::Unauthenticated { .. }
816 | ThreadState::Loading { .. }
817 | ThreadState::LoadError { .. } => None,
818 }
819 }
820
821 pub fn mode_selector(&self) -> Option<&Entity<ModeSelector>> {
822 match &self.thread_state {
823 ThreadState::Ready { mode_selector, .. } => mode_selector.as_ref(),
824 ThreadState::Unauthenticated { .. }
825 | ThreadState::Loading { .. }
826 | ThreadState::LoadError { .. } => None,
827 }
828 }
829
830 pub fn title(&self, cx: &App) -> SharedString {
831 match &self.thread_state {
832 ThreadState::Ready { .. } | ThreadState::Unauthenticated { .. } => "New Thread".into(),
833 ThreadState::Loading(loading_view) => loading_view.read(cx).title.clone(),
834 ThreadState::LoadError(error) => match error {
835 LoadError::Unsupported { .. } => format!("Upgrade {}", self.agent.name()).into(),
836 LoadError::FailedToInstall(_) => {
837 format!("Failed to Install {}", self.agent.name()).into()
838 }
839 LoadError::Exited { .. } => format!("{} Exited", self.agent.name()).into(),
840 LoadError::Other(_) => format!("Error Loading {}", self.agent.name()).into(),
841 },
842 }
843 }
844
845 pub fn title_editor(&self) -> Option<Entity<Editor>> {
846 if let ThreadState::Ready { title_editor, .. } = &self.thread_state {
847 title_editor.clone()
848 } else {
849 None
850 }
851 }
852
853 pub fn cancel_generation(&mut self, cx: &mut Context<Self>) {
854 self.thread_error.take();
855 self.thread_retry_status.take();
856
857 if let Some(thread) = self.thread() {
858 self._cancel_task = Some(thread.update(cx, |thread, cx| thread.cancel(cx)));
859 }
860 }
861
862 pub fn expand_message_editor(
863 &mut self,
864 _: &ExpandMessageEditor,
865 _window: &mut Window,
866 cx: &mut Context<Self>,
867 ) {
868 self.set_editor_is_expanded(!self.editor_expanded, cx);
869 cx.stop_propagation();
870 cx.notify();
871 }
872
873 fn set_editor_is_expanded(&mut self, is_expanded: bool, cx: &mut Context<Self>) {
874 self.editor_expanded = is_expanded;
875 self.message_editor.update(cx, |editor, cx| {
876 if is_expanded {
877 editor.set_mode(
878 EditorMode::Full {
879 scale_ui_elements_with_buffer_font_size: false,
880 show_active_line_background: false,
881 sizing_behavior: SizingBehavior::ExcludeOverscrollMargin,
882 },
883 cx,
884 )
885 } else {
886 let agent_settings = AgentSettings::get_global(cx);
887 editor.set_mode(
888 EditorMode::AutoHeight {
889 min_lines: agent_settings.message_editor_min_lines,
890 max_lines: Some(agent_settings.set_message_editor_max_lines()),
891 },
892 cx,
893 )
894 }
895 });
896 cx.notify();
897 }
898
899 pub fn handle_title_editor_event(
900 &mut self,
901 title_editor: &Entity<Editor>,
902 event: &EditorEvent,
903 window: &mut Window,
904 cx: &mut Context<Self>,
905 ) {
906 let Some(thread) = self.thread() else { return };
907
908 match event {
909 EditorEvent::BufferEdited => {
910 let new_title = title_editor.read(cx).text(cx);
911 thread.update(cx, |thread, cx| {
912 thread
913 .set_title(new_title.into(), cx)
914 .detach_and_log_err(cx);
915 })
916 }
917 EditorEvent::Blurred => {
918 if title_editor.read(cx).text(cx).is_empty() {
919 title_editor.update(cx, |editor, cx| {
920 editor.set_text("New Thread", window, cx);
921 });
922 }
923 }
924 _ => {}
925 }
926 }
927
928 pub fn handle_message_editor_event(
929 &mut self,
930 _: &Entity<MessageEditor>,
931 event: &MessageEditorEvent,
932 window: &mut Window,
933 cx: &mut Context<Self>,
934 ) {
935 match event {
936 MessageEditorEvent::Send => self.send(window, cx),
937 MessageEditorEvent::Cancel => self.cancel_generation(cx),
938 MessageEditorEvent::Focus => {
939 self.cancel_editing(&Default::default(), window, cx);
940 }
941 MessageEditorEvent::LostFocus => {}
942 }
943 }
944
945 pub fn handle_entry_view_event(
946 &mut self,
947 _: &Entity<EntryViewState>,
948 event: &EntryViewEvent,
949 window: &mut Window,
950 cx: &mut Context<Self>,
951 ) {
952 match &event.view_event {
953 ViewEvent::NewDiff(tool_call_id) => {
954 if AgentSettings::get_global(cx).expand_edit_card {
955 self.expanded_tool_calls.insert(tool_call_id.clone());
956 }
957 }
958 ViewEvent::NewTerminal(tool_call_id) => {
959 if AgentSettings::get_global(cx).expand_terminal_card {
960 self.expanded_tool_calls.insert(tool_call_id.clone());
961 }
962 }
963 ViewEvent::TerminalMovedToBackground(tool_call_id) => {
964 self.expanded_tool_calls.remove(tool_call_id);
965 }
966 ViewEvent::MessageEditorEvent(_editor, MessageEditorEvent::Focus) => {
967 if let Some(thread) = self.thread()
968 && let Some(AgentThreadEntry::UserMessage(user_message)) =
969 thread.read(cx).entries().get(event.entry_index)
970 && user_message.id.is_some()
971 {
972 self.editing_message = Some(event.entry_index);
973 cx.notify();
974 }
975 }
976 ViewEvent::MessageEditorEvent(editor, MessageEditorEvent::LostFocus) => {
977 if let Some(thread) = self.thread()
978 && let Some(AgentThreadEntry::UserMessage(user_message)) =
979 thread.read(cx).entries().get(event.entry_index)
980 && user_message.id.is_some()
981 {
982 if editor.read(cx).text(cx).as_str() == user_message.content.to_markdown(cx) {
983 self.editing_message = None;
984 cx.notify();
985 }
986 }
987 }
988 ViewEvent::MessageEditorEvent(editor, MessageEditorEvent::Send) => {
989 self.regenerate(event.entry_index, editor.clone(), window, cx);
990 }
991 ViewEvent::MessageEditorEvent(_editor, MessageEditorEvent::Cancel) => {
992 self.cancel_editing(&Default::default(), window, cx);
993 }
994 }
995 }
996
997 fn resume_chat(&mut self, cx: &mut Context<Self>) {
998 self.thread_error.take();
999 let Some(thread) = self.thread() else {
1000 return;
1001 };
1002 if !thread.read(cx).can_resume(cx) {
1003 return;
1004 }
1005
1006 let task = thread.update(cx, |thread, cx| thread.resume(cx));
1007 cx.spawn(async move |this, cx| {
1008 let result = task.await;
1009
1010 this.update(cx, |this, cx| {
1011 if let Err(err) = result {
1012 this.handle_thread_error(err, cx);
1013 }
1014 })
1015 })
1016 .detach();
1017 }
1018
1019 fn send(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1020 let Some(thread) = self.thread() else { return };
1021
1022 if self.is_loading_contents {
1023 return;
1024 }
1025
1026 self.history_store.update(cx, |history, cx| {
1027 history.push_recently_opened_entry(
1028 HistoryEntryId::AcpThread(thread.read(cx).session_id().clone()),
1029 cx,
1030 );
1031 });
1032
1033 if thread.read(cx).status() != ThreadStatus::Idle {
1034 self.stop_current_and_send_new_message(window, cx);
1035 return;
1036 }
1037
1038 let text = self.message_editor.read(cx).text(cx);
1039 let text = text.trim();
1040 if text == "/login" || text == "/logout" {
1041 let ThreadState::Ready { thread, .. } = &self.thread_state else {
1042 return;
1043 };
1044
1045 let connection = thread.read(cx).connection().clone();
1046 let can_login = !connection.auth_methods().is_empty() || self.login.is_some();
1047 // Does the agent have a specific logout command? Prefer that in case they need to reset internal state.
1048 let logout_supported = text == "/logout"
1049 && self
1050 .available_commands
1051 .borrow()
1052 .iter()
1053 .any(|command| command.name == "logout");
1054 if can_login && !logout_supported {
1055 self.message_editor
1056 .update(cx, |editor, cx| editor.clear(window, cx));
1057
1058 let this = cx.weak_entity();
1059 let agent = self.agent.clone();
1060 window.defer(cx, |window, cx| {
1061 Self::handle_auth_required(
1062 this,
1063 AuthRequired {
1064 description: None,
1065 provider_id: None,
1066 },
1067 agent,
1068 connection,
1069 window,
1070 cx,
1071 );
1072 });
1073 cx.notify();
1074 return;
1075 }
1076 }
1077
1078 self.send_impl(self.message_editor.clone(), window, cx)
1079 }
1080
1081 fn stop_current_and_send_new_message(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1082 let Some(thread) = self.thread().cloned() else {
1083 return;
1084 };
1085
1086 let cancelled = thread.update(cx, |thread, cx| thread.cancel(cx));
1087
1088 cx.spawn_in(window, async move |this, cx| {
1089 cancelled.await;
1090
1091 this.update_in(cx, |this, window, cx| {
1092 this.send_impl(this.message_editor.clone(), window, cx);
1093 })
1094 .ok();
1095 })
1096 .detach();
1097 }
1098
1099 fn send_impl(
1100 &mut self,
1101 message_editor: Entity<MessageEditor>,
1102 window: &mut Window,
1103 cx: &mut Context<Self>,
1104 ) {
1105 let full_mention_content = self.as_native_thread(cx).is_some_and(|thread| {
1106 // Include full contents when using minimal profile
1107 let thread = thread.read(cx);
1108 AgentSettings::get_global(cx)
1109 .profiles
1110 .get(thread.profile())
1111 .is_some_and(|profile| profile.tools.is_empty())
1112 });
1113
1114 let contents = message_editor.update(cx, |message_editor, cx| {
1115 message_editor.contents(full_mention_content, cx)
1116 });
1117
1118 self.thread_error.take();
1119 self.editing_message.take();
1120 self.thread_feedback.clear();
1121
1122 let Some(thread) = self.thread() else {
1123 return;
1124 };
1125 let agent_telemetry_id = self.agent.telemetry_id();
1126 let session_id = thread.read(cx).session_id().clone();
1127 let thread = thread.downgrade();
1128 if self.should_be_following {
1129 self.workspace
1130 .update(cx, |workspace, cx| {
1131 workspace.follow(CollaboratorId::Agent, window, cx);
1132 })
1133 .ok();
1134 }
1135
1136 self.is_loading_contents = true;
1137 let model_id = self.current_model_id(cx);
1138 let guard = cx.new(|_| ());
1139 cx.observe_release(&guard, |this, _guard, cx| {
1140 this.is_loading_contents = false;
1141 cx.notify();
1142 })
1143 .detach();
1144
1145 let task = cx.spawn_in(window, async move |this, cx| {
1146 let (contents, tracked_buffers) = contents.await?;
1147
1148 if contents.is_empty() {
1149 return Ok(());
1150 }
1151
1152 this.update_in(cx, |this, window, cx| {
1153 this.set_editor_is_expanded(false, cx);
1154 this.scroll_to_bottom(cx);
1155 this.message_editor.update(cx, |message_editor, cx| {
1156 message_editor.clear(window, cx);
1157 });
1158 })?;
1159 let turn_start_time = Instant::now();
1160 let send = thread.update(cx, |thread, cx| {
1161 thread.action_log().update(cx, |action_log, cx| {
1162 for buffer in tracked_buffers {
1163 action_log.buffer_read(buffer, cx)
1164 }
1165 });
1166 drop(guard);
1167
1168 telemetry::event!(
1169 "Agent Message Sent",
1170 agent = agent_telemetry_id,
1171 session = session_id,
1172 model = model_id
1173 );
1174
1175 thread.send(contents, cx)
1176 })?;
1177 let res = send.await;
1178 let turn_time_ms = turn_start_time.elapsed().as_millis();
1179 let status = if res.is_ok() { "success" } else { "failure" };
1180 telemetry::event!(
1181 "Agent Turn Completed",
1182 agent = agent_telemetry_id,
1183 session = session_id,
1184 model = model_id,
1185 status,
1186 turn_time_ms,
1187 );
1188 res
1189 });
1190
1191 cx.spawn(async move |this, cx| {
1192 if let Err(err) = task.await {
1193 this.update(cx, |this, cx| {
1194 this.handle_thread_error(err, cx);
1195 })
1196 .ok();
1197 } else {
1198 this.update(cx, |this, cx| {
1199 this.should_be_following = this
1200 .workspace
1201 .update(cx, |workspace, _| {
1202 workspace.is_being_followed(CollaboratorId::Agent)
1203 })
1204 .unwrap_or_default();
1205 })
1206 .ok();
1207 }
1208 })
1209 .detach();
1210 }
1211
1212 fn cancel_editing(&mut self, _: &ClickEvent, window: &mut Window, cx: &mut Context<Self>) {
1213 let Some(thread) = self.thread().cloned() else {
1214 return;
1215 };
1216
1217 if let Some(index) = self.editing_message.take()
1218 && let Some(editor) = self
1219 .entry_view_state
1220 .read(cx)
1221 .entry(index)
1222 .and_then(|e| e.message_editor())
1223 .cloned()
1224 {
1225 editor.update(cx, |editor, cx| {
1226 if let Some(user_message) = thread
1227 .read(cx)
1228 .entries()
1229 .get(index)
1230 .and_then(|e| e.user_message())
1231 {
1232 editor.set_message(user_message.chunks.clone(), window, cx);
1233 }
1234 })
1235 };
1236 self.focus_handle(cx).focus(window);
1237 cx.notify();
1238 }
1239
1240 fn regenerate(
1241 &mut self,
1242 entry_ix: usize,
1243 message_editor: Entity<MessageEditor>,
1244 window: &mut Window,
1245 cx: &mut Context<Self>,
1246 ) {
1247 let Some(thread) = self.thread().cloned() else {
1248 return;
1249 };
1250 if self.is_loading_contents {
1251 return;
1252 }
1253
1254 let Some(user_message_id) = thread.update(cx, |thread, _| {
1255 thread.entries().get(entry_ix)?.user_message()?.id.clone()
1256 }) else {
1257 return;
1258 };
1259
1260 cx.spawn_in(window, async move |this, cx| {
1261 thread
1262 .update(cx, |thread, cx| thread.rewind(user_message_id, cx))?
1263 .await?;
1264 this.update_in(cx, |this, window, cx| {
1265 this.send_impl(message_editor, window, cx);
1266 this.focus_handle(cx).focus(window);
1267 })?;
1268 anyhow::Ok(())
1269 })
1270 .detach();
1271 }
1272
1273 fn open_edited_buffer(
1274 &mut self,
1275 buffer: &Entity<Buffer>,
1276 window: &mut Window,
1277 cx: &mut Context<Self>,
1278 ) {
1279 let Some(thread) = self.thread() else {
1280 return;
1281 };
1282
1283 let Some(diff) =
1284 AgentDiffPane::deploy(thread.clone(), self.workspace.clone(), window, cx).log_err()
1285 else {
1286 return;
1287 };
1288
1289 diff.update(cx, |diff, cx| {
1290 diff.move_to_path(PathKey::for_buffer(buffer, cx), window, cx)
1291 })
1292 }
1293
1294 fn handle_open_rules(&mut self, _: &ClickEvent, window: &mut Window, cx: &mut Context<Self>) {
1295 let Some(thread) = self.as_native_thread(cx) else {
1296 return;
1297 };
1298 let project_context = thread.read(cx).project_context().read(cx);
1299
1300 let project_entry_ids = project_context
1301 .worktrees
1302 .iter()
1303 .flat_map(|worktree| worktree.rules_file.as_ref())
1304 .map(|rules_file| ProjectEntryId::from_usize(rules_file.project_entry_id))
1305 .collect::<Vec<_>>();
1306
1307 self.workspace
1308 .update(cx, move |workspace, cx| {
1309 // TODO: Open a multibuffer instead? In some cases this doesn't make the set of rules
1310 // files clear. For example, if rules file 1 is already open but rules file 2 is not,
1311 // this would open and focus rules file 2 in a tab that is not next to rules file 1.
1312 let project = workspace.project().read(cx);
1313 let project_paths = project_entry_ids
1314 .into_iter()
1315 .flat_map(|entry_id| project.path_for_entry(entry_id, cx))
1316 .collect::<Vec<_>>();
1317 for project_path in project_paths {
1318 workspace
1319 .open_path(project_path, None, true, window, cx)
1320 .detach_and_log_err(cx);
1321 }
1322 })
1323 .ok();
1324 }
1325
1326 fn handle_thread_error(&mut self, error: anyhow::Error, cx: &mut Context<Self>) {
1327 self.thread_error = Some(ThreadError::from_err(error, &self.agent));
1328 cx.notify();
1329 }
1330
1331 fn clear_thread_error(&mut self, cx: &mut Context<Self>) {
1332 self.thread_error = None;
1333 self.thread_error_markdown = None;
1334 cx.notify();
1335 }
1336
1337 fn handle_thread_event(
1338 &mut self,
1339 thread: &Entity<AcpThread>,
1340 event: &AcpThreadEvent,
1341 window: &mut Window,
1342 cx: &mut Context<Self>,
1343 ) {
1344 match event {
1345 AcpThreadEvent::NewEntry => {
1346 let len = thread.read(cx).entries().len();
1347 let index = len - 1;
1348 self.entry_view_state.update(cx, |view_state, cx| {
1349 view_state.sync_entry(index, thread, window, cx);
1350 self.list_state.splice_focusable(
1351 index..index,
1352 [view_state
1353 .entry(index)
1354 .and_then(|entry| entry.focus_handle(cx))],
1355 );
1356 });
1357 }
1358 AcpThreadEvent::EntryUpdated(index) => {
1359 self.entry_view_state.update(cx, |view_state, cx| {
1360 view_state.sync_entry(*index, thread, window, cx)
1361 });
1362 }
1363 AcpThreadEvent::EntriesRemoved(range) => {
1364 self.entry_view_state
1365 .update(cx, |view_state, _cx| view_state.remove(range.clone()));
1366 self.list_state.splice(range.clone(), 0);
1367 }
1368 AcpThreadEvent::ToolAuthorizationRequired => {
1369 self.notify_with_sound("Waiting for tool confirmation", IconName::Info, window, cx);
1370 }
1371 AcpThreadEvent::Retry(retry) => {
1372 self.thread_retry_status = Some(retry.clone());
1373 }
1374 AcpThreadEvent::Stopped => {
1375 self.thread_retry_status.take();
1376 let used_tools = thread.read(cx).used_tools_since_last_user_message();
1377 self.notify_with_sound(
1378 if used_tools {
1379 "Finished running tools"
1380 } else {
1381 "New message"
1382 },
1383 IconName::ZedAssistant,
1384 window,
1385 cx,
1386 );
1387 }
1388 AcpThreadEvent::Refusal => {
1389 self.thread_retry_status.take();
1390 self.thread_error = Some(ThreadError::Refusal);
1391 let model_or_agent_name = self.current_model_name(cx);
1392 let notification_message =
1393 format!("{} refused to respond to this request", model_or_agent_name);
1394 self.notify_with_sound(¬ification_message, IconName::Warning, window, cx);
1395 }
1396 AcpThreadEvent::Error => {
1397 self.thread_retry_status.take();
1398 self.notify_with_sound(
1399 "Agent stopped due to an error",
1400 IconName::Warning,
1401 window,
1402 cx,
1403 );
1404 }
1405 AcpThreadEvent::LoadError(error) => {
1406 self.thread_retry_status.take();
1407 self.thread_state = ThreadState::LoadError(error.clone());
1408 if self.message_editor.focus_handle(cx).is_focused(window) {
1409 self.focus_handle.focus(window)
1410 }
1411 }
1412 AcpThreadEvent::TitleUpdated => {
1413 let title = thread.read(cx).title();
1414 if let Some(title_editor) = self.title_editor() {
1415 title_editor.update(cx, |editor, cx| {
1416 if editor.text(cx) != title {
1417 editor.set_text(title, window, cx);
1418 }
1419 });
1420 }
1421 }
1422 AcpThreadEvent::PromptCapabilitiesUpdated => {
1423 self.prompt_capabilities
1424 .replace(thread.read(cx).prompt_capabilities());
1425 }
1426 AcpThreadEvent::TokenUsageUpdated => {}
1427 AcpThreadEvent::AvailableCommandsUpdated(available_commands) => {
1428 let mut available_commands = available_commands.clone();
1429
1430 if thread
1431 .read(cx)
1432 .connection()
1433 .auth_methods()
1434 .iter()
1435 .any(|method| method.id.0.as_ref() == "claude-login")
1436 {
1437 available_commands.push(acp::AvailableCommand {
1438 name: "login".to_owned(),
1439 description: "Authenticate".to_owned(),
1440 input: None,
1441 meta: None,
1442 });
1443 available_commands.push(acp::AvailableCommand {
1444 name: "logout".to_owned(),
1445 description: "Authenticate".to_owned(),
1446 input: None,
1447 meta: None,
1448 });
1449 }
1450
1451 let has_commands = !available_commands.is_empty();
1452 self.available_commands.replace(available_commands);
1453
1454 let new_placeholder = placeholder_text(self.agent.name().as_ref(), has_commands);
1455
1456 self.message_editor.update(cx, |editor, cx| {
1457 editor.set_placeholder_text(&new_placeholder, window, cx);
1458 });
1459 }
1460 AcpThreadEvent::ModeUpdated(_mode) => {
1461 // The connection keeps track of the mode
1462 cx.notify();
1463 }
1464 }
1465 cx.notify();
1466 }
1467
1468 fn authenticate(
1469 &mut self,
1470 method: acp::AuthMethodId,
1471 window: &mut Window,
1472 cx: &mut Context<Self>,
1473 ) {
1474 let ThreadState::Unauthenticated {
1475 connection,
1476 pending_auth_method,
1477 configuration_view,
1478 ..
1479 } = &mut self.thread_state
1480 else {
1481 return;
1482 };
1483
1484 // Check for the experimental "terminal-auth" _meta field
1485 let auth_method = connection.auth_methods().iter().find(|m| m.id == method);
1486
1487 if let Some(auth_method) = auth_method {
1488 if let Some(meta) = &auth_method.meta {
1489 if let Some(terminal_auth) = meta.get("terminal-auth") {
1490 // Extract terminal auth details from meta
1491 if let (Some(command), Some(label)) = (
1492 terminal_auth.get("command").and_then(|v| v.as_str()),
1493 terminal_auth.get("label").and_then(|v| v.as_str()),
1494 ) {
1495 let args = terminal_auth
1496 .get("args")
1497 .and_then(|v| v.as_array())
1498 .map(|arr| {
1499 arr.iter()
1500 .filter_map(|v| v.as_str().map(String::from))
1501 .collect()
1502 })
1503 .unwrap_or_default();
1504
1505 let env = terminal_auth
1506 .get("env")
1507 .and_then(|v| v.as_object())
1508 .map(|obj| {
1509 obj.iter()
1510 .filter_map(|(k, v)| {
1511 v.as_str().map(|val| (k.clone(), val.to_string()))
1512 })
1513 .collect::<HashMap<String, String>>()
1514 })
1515 .unwrap_or_default();
1516
1517 // Run SpawnInTerminal in the same dir as the ACP server
1518 let cwd = connection
1519 .clone()
1520 .downcast::<agent_servers::AcpConnection>()
1521 .map(|acp_conn| acp_conn.root_dir().to_path_buf());
1522
1523 // Build SpawnInTerminal from _meta
1524 let login = task::SpawnInTerminal {
1525 id: task::TaskId(format!("external-agent-{}-login", label)),
1526 full_label: label.to_string(),
1527 label: label.to_string(),
1528 command: Some(command.to_string()),
1529 args,
1530 command_label: label.to_string(),
1531 cwd,
1532 env,
1533 use_new_terminal: true,
1534 allow_concurrent_runs: true,
1535 hide: task::HideStrategy::Always,
1536 ..Default::default()
1537 };
1538
1539 self.thread_error.take();
1540 configuration_view.take();
1541 pending_auth_method.replace(method.clone());
1542
1543 if let Some(workspace) = self.workspace.upgrade() {
1544 let project = self.project.clone();
1545 let authenticate = Self::spawn_external_agent_login(
1546 login, workspace, project, false, true, window, cx,
1547 );
1548 cx.notify();
1549 self.auth_task = Some(cx.spawn_in(window, {
1550 let agent = self.agent.clone();
1551 async move |this, cx| {
1552 let result = authenticate.await;
1553
1554 match &result {
1555 Ok(_) => telemetry::event!(
1556 "Authenticate Agent Succeeded",
1557 agent = agent.telemetry_id()
1558 ),
1559 Err(_) => {
1560 telemetry::event!(
1561 "Authenticate Agent Failed",
1562 agent = agent.telemetry_id(),
1563 )
1564 }
1565 }
1566
1567 this.update_in(cx, |this, window, cx| {
1568 if let Err(err) = result {
1569 if let ThreadState::Unauthenticated {
1570 pending_auth_method,
1571 ..
1572 } = &mut this.thread_state
1573 {
1574 pending_auth_method.take();
1575 }
1576 this.handle_thread_error(err, cx);
1577 } else {
1578 this.reset(window, cx);
1579 }
1580 this.auth_task.take()
1581 })
1582 .ok();
1583 }
1584 }));
1585 }
1586 return;
1587 }
1588 }
1589 }
1590 }
1591
1592 if method.0.as_ref() == "gemini-api-key" {
1593 let registry = LanguageModelRegistry::global(cx);
1594 let provider = registry
1595 .read(cx)
1596 .provider(&language_model::GOOGLE_PROVIDER_ID)
1597 .unwrap();
1598 if !provider.is_authenticated(cx) {
1599 let this = cx.weak_entity();
1600 let agent = self.agent.clone();
1601 let connection = connection.clone();
1602 window.defer(cx, |window, cx| {
1603 Self::handle_auth_required(
1604 this,
1605 AuthRequired {
1606 description: Some("GEMINI_API_KEY must be set".to_owned()),
1607 provider_id: Some(language_model::GOOGLE_PROVIDER_ID),
1608 },
1609 agent,
1610 connection,
1611 window,
1612 cx,
1613 );
1614 });
1615 return;
1616 }
1617 } else if method.0.as_ref() == "anthropic-api-key" {
1618 let registry = LanguageModelRegistry::global(cx);
1619 let provider = registry
1620 .read(cx)
1621 .provider(&language_model::ANTHROPIC_PROVIDER_ID)
1622 .unwrap();
1623 let this = cx.weak_entity();
1624 let agent = self.agent.clone();
1625 let connection = connection.clone();
1626 window.defer(cx, move |window, cx| {
1627 if !provider.is_authenticated(cx) {
1628 Self::handle_auth_required(
1629 this,
1630 AuthRequired {
1631 description: Some("ANTHROPIC_API_KEY must be set".to_owned()),
1632 provider_id: Some(language_model::ANTHROPIC_PROVIDER_ID),
1633 },
1634 agent,
1635 connection,
1636 window,
1637 cx,
1638 );
1639 } else {
1640 this.update(cx, |this, cx| {
1641 this.thread_state = Self::initial_state(
1642 agent,
1643 None,
1644 this.workspace.clone(),
1645 this.project.clone(),
1646 window,
1647 cx,
1648 )
1649 })
1650 .ok();
1651 }
1652 });
1653 return;
1654 } else if method.0.as_ref() == "vertex-ai"
1655 && std::env::var("GOOGLE_API_KEY").is_err()
1656 && (std::env::var("GOOGLE_CLOUD_PROJECT").is_err()
1657 || (std::env::var("GOOGLE_CLOUD_PROJECT").is_err()))
1658 {
1659 let this = cx.weak_entity();
1660 let agent = self.agent.clone();
1661 let connection = connection.clone();
1662
1663 window.defer(cx, |window, cx| {
1664 Self::handle_auth_required(
1665 this,
1666 AuthRequired {
1667 description: Some(
1668 "GOOGLE_API_KEY must be set in the environment to use Vertex AI authentication for Gemini CLI. Please export it and restart Zed."
1669 .to_owned(),
1670 ),
1671 provider_id: None,
1672 },
1673 agent,
1674 connection,
1675 window,
1676 cx,
1677 )
1678 });
1679 return;
1680 }
1681
1682 self.thread_error.take();
1683 configuration_view.take();
1684 pending_auth_method.replace(method.clone());
1685 let authenticate = if (method.0.as_ref() == "claude-login"
1686 || method.0.as_ref() == "spawn-gemini-cli")
1687 && let Some(login) = self.login.clone()
1688 {
1689 if let Some(workspace) = self.workspace.upgrade() {
1690 let project = self.project.clone();
1691 Self::spawn_external_agent_login(
1692 login, workspace, project, false, false, window, cx,
1693 )
1694 } else {
1695 Task::ready(Ok(()))
1696 }
1697 } else {
1698 connection.authenticate(method, cx)
1699 };
1700 cx.notify();
1701 self.auth_task =
1702 Some(cx.spawn_in(window, {
1703 let agent = self.agent.clone();
1704 async move |this, cx| {
1705 let result = authenticate.await;
1706
1707 match &result {
1708 Ok(_) => telemetry::event!(
1709 "Authenticate Agent Succeeded",
1710 agent = agent.telemetry_id()
1711 ),
1712 Err(_) => {
1713 telemetry::event!(
1714 "Authenticate Agent Failed",
1715 agent = agent.telemetry_id(),
1716 )
1717 }
1718 }
1719
1720 this.update_in(cx, |this, window, cx| {
1721 if let Err(err) = result {
1722 if let ThreadState::Unauthenticated {
1723 pending_auth_method,
1724 ..
1725 } = &mut this.thread_state
1726 {
1727 pending_auth_method.take();
1728 }
1729 this.handle_thread_error(err, cx);
1730 } else {
1731 this.reset(window, cx);
1732 }
1733 this.auth_task.take()
1734 })
1735 .ok();
1736 }
1737 }));
1738 }
1739
1740 fn spawn_external_agent_login(
1741 login: task::SpawnInTerminal,
1742 workspace: Entity<Workspace>,
1743 project: Entity<Project>,
1744 previous_attempt: bool,
1745 check_exit_code: bool,
1746 window: &mut Window,
1747 cx: &mut App,
1748 ) -> Task<Result<()>> {
1749 let Some(terminal_panel) = workspace.read(cx).panel::<TerminalPanel>(cx) else {
1750 return Task::ready(Ok(()));
1751 };
1752
1753 window.spawn(cx, async move |cx| {
1754 let mut task = login.clone();
1755 if let Some(cmd) = &task.command {
1756 // Have "node" command use Zed's managed Node runtime by default
1757 if cmd == "node" {
1758 let resolved_node_runtime = project
1759 .update(cx, |project, cx| {
1760 let agent_server_store = project.agent_server_store().clone();
1761 agent_server_store.update(cx, |store, cx| {
1762 store.node_runtime().map(|node_runtime| {
1763 cx.background_spawn(async move {
1764 node_runtime.binary_path().await
1765 })
1766 })
1767 })
1768 });
1769
1770 if let Ok(Some(resolve_task)) = resolved_node_runtime {
1771 if let Ok(node_path) = resolve_task.await {
1772 task.command = Some(node_path.to_string_lossy().to_string());
1773 }
1774 }
1775 }
1776 }
1777 task.shell = task::Shell::WithArguments {
1778 program: task.command.take().expect("login command should be set"),
1779 args: std::mem::take(&mut task.args),
1780 title_override: None
1781 };
1782 task.full_label = task.label.clone();
1783 task.id = task::TaskId(format!("external-agent-{}-login", task.label));
1784 task.command_label = task.label.clone();
1785 task.use_new_terminal = true;
1786 task.allow_concurrent_runs = true;
1787 task.hide = task::HideStrategy::Always;
1788
1789 let terminal = terminal_panel.update_in(cx, |terminal_panel, window, cx| {
1790 terminal_panel.spawn_task(&task, window, cx)
1791 })?;
1792
1793 let terminal = terminal.await?;
1794
1795 if check_exit_code {
1796 // For extension-based auth, wait for the process to exit and check exit code
1797 let exit_status = terminal
1798 .read_with(cx, |terminal, cx| terminal.wait_for_completed_task(cx))?
1799 .await;
1800
1801 match exit_status {
1802 Some(status) if status.success() => {
1803 Ok(())
1804 }
1805 Some(status) => {
1806 Err(anyhow!("Login command failed with exit code: {:?}", status.code()))
1807 }
1808 None => {
1809 Err(anyhow!("Login command terminated without exit status"))
1810 }
1811 }
1812 } else {
1813 // For hardcoded agents (claude-login, gemini-cli): look for specific output
1814 let mut exit_status = terminal
1815 .read_with(cx, |terminal, cx| terminal.wait_for_completed_task(cx))?
1816 .fuse();
1817
1818 let logged_in = cx
1819 .spawn({
1820 let terminal = terminal.clone();
1821 async move |cx| {
1822 loop {
1823 cx.background_executor().timer(Duration::from_secs(1)).await;
1824 let content =
1825 terminal.update(cx, |terminal, _cx| terminal.get_content())?;
1826 if content.contains("Login successful")
1827 || content.contains("Type your message")
1828 {
1829 return anyhow::Ok(());
1830 }
1831 }
1832 }
1833 })
1834 .fuse();
1835 futures::pin_mut!(logged_in);
1836 futures::select_biased! {
1837 result = logged_in => {
1838 if let Err(e) = result {
1839 log::error!("{e}");
1840 return Err(anyhow!("exited before logging in"));
1841 }
1842 }
1843 _ = exit_status => {
1844 if !previous_attempt && project.read_with(cx, |project, _| project.is_via_remote_server())? && login.label.contains("gemini") {
1845 return cx.update(|window, cx| Self::spawn_external_agent_login(login, workspace, project.clone(), true, false, window, cx))?.await
1846 }
1847 return Err(anyhow!("exited before logging in"));
1848 }
1849 }
1850 terminal.update(cx, |terminal, _| terminal.kill_active_task())?;
1851 Ok(())
1852 }
1853 })
1854 }
1855
1856 fn authorize_tool_call(
1857 &mut self,
1858 tool_call_id: acp::ToolCallId,
1859 option_id: acp::PermissionOptionId,
1860 option_kind: acp::PermissionOptionKind,
1861 window: &mut Window,
1862 cx: &mut Context<Self>,
1863 ) {
1864 let Some(thread) = self.thread() else {
1865 return;
1866 };
1867
1868 telemetry::event!(
1869 "Agent Tool Call Authorized",
1870 agent = self.agent.telemetry_id(),
1871 session = thread.read(cx).session_id(),
1872 option = option_kind
1873 );
1874
1875 thread.update(cx, |thread, cx| {
1876 thread.authorize_tool_call(tool_call_id, option_id, option_kind, cx);
1877 });
1878 if self.should_be_following {
1879 self.workspace
1880 .update(cx, |workspace, cx| {
1881 workspace.follow(CollaboratorId::Agent, window, cx);
1882 })
1883 .ok();
1884 }
1885 cx.notify();
1886 }
1887
1888 fn restore_checkpoint(&mut self, message_id: &UserMessageId, cx: &mut Context<Self>) {
1889 let Some(thread) = self.thread() else {
1890 return;
1891 };
1892
1893 thread
1894 .update(cx, |thread, cx| {
1895 thread.restore_checkpoint(message_id.clone(), cx)
1896 })
1897 .detach_and_log_err(cx);
1898 }
1899
1900 fn render_entry(
1901 &self,
1902 entry_ix: usize,
1903 total_entries: usize,
1904 entry: &AgentThreadEntry,
1905 window: &mut Window,
1906 cx: &Context<Self>,
1907 ) -> AnyElement {
1908 let primary = match &entry {
1909 AgentThreadEntry::UserMessage(message) => {
1910 let Some(editor) = self
1911 .entry_view_state
1912 .read(cx)
1913 .entry(entry_ix)
1914 .and_then(|entry| entry.message_editor())
1915 .cloned()
1916 else {
1917 return Empty.into_any_element();
1918 };
1919
1920 let editing = self.editing_message == Some(entry_ix);
1921 let editor_focus = editor.focus_handle(cx).is_focused(window);
1922 let focus_border = cx.theme().colors().border_focused;
1923
1924 let rules_item = if entry_ix == 0 {
1925 self.render_rules_item(cx)
1926 } else {
1927 None
1928 };
1929
1930 let has_checkpoint_button = message
1931 .checkpoint
1932 .as_ref()
1933 .is_some_and(|checkpoint| checkpoint.show);
1934
1935 let agent_name = self.agent.name();
1936
1937 v_flex()
1938 .id(("user_message", entry_ix))
1939 .map(|this| {
1940 if entry_ix == 0 && !has_checkpoint_button && rules_item.is_none() {
1941 this.pt(rems_from_px(18.))
1942 } else if rules_item.is_some() {
1943 this.pt_3()
1944 } else {
1945 this.pt_2()
1946 }
1947 })
1948 .pb_3()
1949 .px_2()
1950 .gap_1p5()
1951 .w_full()
1952 .children(rules_item)
1953 .children(message.id.clone().and_then(|message_id| {
1954 message.checkpoint.as_ref()?.show.then(|| {
1955 h_flex()
1956 .px_3()
1957 .gap_2()
1958 .child(Divider::horizontal())
1959 .child(
1960 Button::new("restore-checkpoint", "Restore Checkpoint")
1961 .icon(IconName::Undo)
1962 .icon_size(IconSize::XSmall)
1963 .icon_position(IconPosition::Start)
1964 .label_size(LabelSize::XSmall)
1965 .icon_color(Color::Muted)
1966 .color(Color::Muted)
1967 .tooltip(Tooltip::text("Restores all files in the project to the content they had at this point in the conversation."))
1968 .on_click(cx.listener(move |this, _, _window, cx| {
1969 this.restore_checkpoint(&message_id, cx);
1970 }))
1971 )
1972 .child(Divider::horizontal())
1973 })
1974 }))
1975 .child(
1976 div()
1977 .relative()
1978 .child(
1979 div()
1980 .py_3()
1981 .px_2()
1982 .rounded_md()
1983 .shadow_md()
1984 .bg(cx.theme().colors().editor_background)
1985 .border_1()
1986 .when(editing && !editor_focus, |this| this.border_dashed())
1987 .border_color(cx.theme().colors().border)
1988 .map(|this|{
1989 if editing && editor_focus {
1990 this.border_color(focus_border)
1991 } else if message.id.is_some() {
1992 this.hover(|s| s.border_color(focus_border.opacity(0.8)))
1993 } else {
1994 this
1995 }
1996 })
1997 .text_xs()
1998 .child(editor.clone().into_any_element()),
1999 )
2000 .when(editor_focus, |this| {
2001 let base_container = h_flex()
2002 .absolute()
2003 .top_neg_3p5()
2004 .right_3()
2005 .gap_1()
2006 .rounded_sm()
2007 .border_1()
2008 .border_color(cx.theme().colors().border)
2009 .bg(cx.theme().colors().editor_background)
2010 .overflow_hidden();
2011
2012 if message.id.is_some() {
2013 this.child(
2014 base_container
2015 .child(
2016 IconButton::new("cancel", IconName::Close)
2017 .disabled(self.is_loading_contents)
2018 .icon_color(Color::Error)
2019 .icon_size(IconSize::XSmall)
2020 .on_click(cx.listener(Self::cancel_editing))
2021 )
2022 .child(
2023 if self.is_loading_contents {
2024 div()
2025 .id("loading-edited-message-content")
2026 .tooltip(Tooltip::text("Loading Added Context…"))
2027 .child(loading_contents_spinner(IconSize::XSmall))
2028 .into_any_element()
2029 } else {
2030 IconButton::new("regenerate", IconName::Return)
2031 .icon_color(Color::Muted)
2032 .icon_size(IconSize::XSmall)
2033 .tooltip(Tooltip::text(
2034 "Editing will restart the thread from this point."
2035 ))
2036 .on_click(cx.listener({
2037 let editor = editor.clone();
2038 move |this, _, window, cx| {
2039 this.regenerate(
2040 entry_ix, editor.clone(), window, cx,
2041 );
2042 }
2043 })).into_any_element()
2044 }
2045 )
2046 )
2047 } else {
2048 this.child(
2049 base_container
2050 .border_dashed()
2051 .child(
2052 IconButton::new("editing_unavailable", IconName::PencilUnavailable)
2053 .icon_size(IconSize::Small)
2054 .icon_color(Color::Muted)
2055 .style(ButtonStyle::Transparent)
2056 .tooltip(move |_window, cx| {
2057 cx.new(|_| UnavailableEditingTooltip::new(agent_name.clone()))
2058 .into()
2059 })
2060 )
2061 )
2062 }
2063 }),
2064 )
2065 .into_any()
2066 }
2067 AgentThreadEntry::AssistantMessage(AssistantMessage { chunks }) => {
2068 let is_last = entry_ix + 1 == total_entries;
2069
2070 let style = default_markdown_style(false, false, window, cx);
2071 let message_body = v_flex()
2072 .w_full()
2073 .gap_3()
2074 .children(chunks.iter().enumerate().filter_map(
2075 |(chunk_ix, chunk)| match chunk {
2076 AssistantMessageChunk::Message { block } => {
2077 block.markdown().map(|md| {
2078 self.render_markdown(md.clone(), style.clone())
2079 .into_any_element()
2080 })
2081 }
2082 AssistantMessageChunk::Thought { block } => {
2083 block.markdown().map(|md| {
2084 self.render_thinking_block(
2085 entry_ix,
2086 chunk_ix,
2087 md.clone(),
2088 window,
2089 cx,
2090 )
2091 .into_any_element()
2092 })
2093 }
2094 },
2095 ))
2096 .into_any();
2097
2098 v_flex()
2099 .px_5()
2100 .py_1p5()
2101 .when(is_last, |this| this.pb_4())
2102 .w_full()
2103 .text_ui(cx)
2104 .child(message_body)
2105 .into_any()
2106 }
2107 AgentThreadEntry::ToolCall(tool_call) => {
2108 let has_terminals = tool_call.terminals().next().is_some();
2109
2110 div().w_full().map(|this| {
2111 if has_terminals {
2112 this.children(tool_call.terminals().map(|terminal| {
2113 self.render_terminal_tool_call(
2114 entry_ix, terminal, tool_call, window, cx,
2115 )
2116 }))
2117 } else {
2118 this.child(self.render_tool_call(entry_ix, tool_call, window, cx))
2119 }
2120 })
2121 }
2122 .into_any(),
2123 };
2124
2125 let needs_confirmation = if let AgentThreadEntry::ToolCall(tool_call) = entry {
2126 matches!(
2127 tool_call.status,
2128 ToolCallStatus::WaitingForConfirmation { .. }
2129 )
2130 } else {
2131 false
2132 };
2133
2134 let Some(thread) = self.thread() else {
2135 return primary;
2136 };
2137
2138 let primary = if entry_ix == total_entries - 1 {
2139 v_flex()
2140 .w_full()
2141 .child(primary)
2142 .map(|this| {
2143 if needs_confirmation {
2144 this.child(self.render_generating(true))
2145 } else {
2146 this.child(self.render_thread_controls(&thread, cx))
2147 }
2148 })
2149 .when_some(
2150 self.thread_feedback.comments_editor.clone(),
2151 |this, editor| this.child(Self::render_feedback_feedback_editor(editor, cx)),
2152 )
2153 .into_any_element()
2154 } else {
2155 primary
2156 };
2157
2158 if let Some(editing_index) = self.editing_message.as_ref()
2159 && *editing_index < entry_ix
2160 {
2161 let backdrop = div()
2162 .id(("backdrop", entry_ix))
2163 .size_full()
2164 .absolute()
2165 .inset_0()
2166 .bg(cx.theme().colors().panel_background)
2167 .opacity(0.8)
2168 .block_mouse_except_scroll()
2169 .on_click(cx.listener(Self::cancel_editing));
2170
2171 div()
2172 .relative()
2173 .child(primary)
2174 .child(backdrop)
2175 .into_any_element()
2176 } else {
2177 primary
2178 }
2179 }
2180
2181 fn tool_card_header_bg(&self, cx: &Context<Self>) -> Hsla {
2182 cx.theme()
2183 .colors()
2184 .element_background
2185 .blend(cx.theme().colors().editor_foreground.opacity(0.025))
2186 }
2187
2188 fn tool_card_border_color(&self, cx: &Context<Self>) -> Hsla {
2189 cx.theme().colors().border.opacity(0.8)
2190 }
2191
2192 fn tool_name_font_size(&self) -> Rems {
2193 rems_from_px(13.)
2194 }
2195
2196 fn render_thinking_block(
2197 &self,
2198 entry_ix: usize,
2199 chunk_ix: usize,
2200 chunk: Entity<Markdown>,
2201 window: &Window,
2202 cx: &Context<Self>,
2203 ) -> AnyElement {
2204 let header_id = SharedString::from(format!("thinking-block-header-{}", entry_ix));
2205 let card_header_id = SharedString::from("inner-card-header");
2206
2207 let key = (entry_ix, chunk_ix);
2208
2209 let is_open = self.expanded_thinking_blocks.contains(&key);
2210
2211 let scroll_handle = self
2212 .entry_view_state
2213 .read(cx)
2214 .entry(entry_ix)
2215 .and_then(|entry| entry.scroll_handle_for_assistant_message_chunk(chunk_ix));
2216
2217 let thinking_content = {
2218 div()
2219 .id(("thinking-content", chunk_ix))
2220 .when_some(scroll_handle, |this, scroll_handle| {
2221 this.track_scroll(&scroll_handle)
2222 })
2223 .text_ui_sm(cx)
2224 .overflow_hidden()
2225 .child(
2226 self.render_markdown(chunk, default_markdown_style(false, false, window, cx)),
2227 )
2228 };
2229
2230 v_flex()
2231 .gap_1()
2232 .child(
2233 h_flex()
2234 .id(header_id)
2235 .group(&card_header_id)
2236 .relative()
2237 .w_full()
2238 .pr_1()
2239 .justify_between()
2240 .child(
2241 h_flex()
2242 .h(window.line_height() - px(2.))
2243 .gap_1p5()
2244 .overflow_hidden()
2245 .child(
2246 Icon::new(IconName::ToolThink)
2247 .size(IconSize::Small)
2248 .color(Color::Muted),
2249 )
2250 .child(
2251 div()
2252 .text_size(self.tool_name_font_size())
2253 .text_color(cx.theme().colors().text_muted)
2254 .child("Thinking"),
2255 ),
2256 )
2257 .child(
2258 Disclosure::new(("expand", entry_ix), is_open)
2259 .opened_icon(IconName::ChevronUp)
2260 .closed_icon(IconName::ChevronDown)
2261 .visible_on_hover(&card_header_id)
2262 .on_click(cx.listener({
2263 move |this, _event, _window, cx| {
2264 if is_open {
2265 this.expanded_thinking_blocks.remove(&key);
2266 } else {
2267 this.expanded_thinking_blocks.insert(key);
2268 }
2269 cx.notify();
2270 }
2271 })),
2272 )
2273 .on_click(cx.listener({
2274 move |this, _event, _window, cx| {
2275 if is_open {
2276 this.expanded_thinking_blocks.remove(&key);
2277 } else {
2278 this.expanded_thinking_blocks.insert(key);
2279 }
2280 cx.notify();
2281 }
2282 })),
2283 )
2284 .when(is_open, |this| {
2285 this.child(
2286 div()
2287 .ml_1p5()
2288 .pl_3p5()
2289 .border_l_1()
2290 .border_color(self.tool_card_border_color(cx))
2291 .child(thinking_content),
2292 )
2293 })
2294 .into_any_element()
2295 }
2296
2297 fn render_tool_call(
2298 &self,
2299 entry_ix: usize,
2300 tool_call: &ToolCall,
2301 window: &Window,
2302 cx: &Context<Self>,
2303 ) -> Div {
2304 let has_location = tool_call.locations.len() == 1;
2305 let card_header_id = SharedString::from("inner-tool-call-header");
2306
2307 let failed_or_canceled = match &tool_call.status {
2308 ToolCallStatus::Rejected | ToolCallStatus::Canceled | ToolCallStatus::Failed => true,
2309 _ => false,
2310 };
2311
2312 let needs_confirmation = matches!(
2313 tool_call.status,
2314 ToolCallStatus::WaitingForConfirmation { .. }
2315 );
2316 let is_terminal_tool = matches!(tool_call.kind, acp::ToolKind::Execute);
2317 let is_edit =
2318 matches!(tool_call.kind, acp::ToolKind::Edit) || tool_call.diffs().next().is_some();
2319
2320 let use_card_layout = needs_confirmation || is_edit || is_terminal_tool;
2321
2322 let is_collapsible = !tool_call.content.is_empty() && !needs_confirmation;
2323
2324 let is_open = needs_confirmation || self.expanded_tool_calls.contains(&tool_call.id);
2325
2326 let tool_output_display =
2327 if is_open {
2328 match &tool_call.status {
2329 ToolCallStatus::WaitingForConfirmation { options, .. } => v_flex()
2330 .w_full()
2331 .children(tool_call.content.iter().enumerate().map(
2332 |(content_ix, content)| {
2333 div()
2334 .child(self.render_tool_call_content(
2335 entry_ix,
2336 content,
2337 content_ix,
2338 tool_call,
2339 use_card_layout,
2340 window,
2341 cx,
2342 ))
2343 .into_any_element()
2344 },
2345 ))
2346 .child(self.render_permission_buttons(
2347 tool_call.kind,
2348 options,
2349 entry_ix,
2350 tool_call.id.clone(),
2351 cx,
2352 ))
2353 .into_any(),
2354 ToolCallStatus::Pending | ToolCallStatus::InProgress
2355 if is_edit
2356 && tool_call.content.is_empty()
2357 && self.as_native_connection(cx).is_some() =>
2358 {
2359 self.render_diff_loading(cx).into_any()
2360 }
2361 ToolCallStatus::Pending
2362 | ToolCallStatus::InProgress
2363 | ToolCallStatus::Completed
2364 | ToolCallStatus::Failed
2365 | ToolCallStatus::Canceled => v_flex()
2366 .w_full()
2367 .children(tool_call.content.iter().enumerate().map(
2368 |(content_ix, content)| {
2369 div().child(self.render_tool_call_content(
2370 entry_ix,
2371 content,
2372 content_ix,
2373 tool_call,
2374 use_card_layout,
2375 window,
2376 cx,
2377 ))
2378 },
2379 ))
2380 .into_any(),
2381 ToolCallStatus::Rejected => Empty.into_any(),
2382 }
2383 .into()
2384 } else {
2385 None
2386 };
2387
2388 v_flex()
2389 .map(|this| {
2390 if use_card_layout {
2391 this.my_1p5()
2392 .rounded_md()
2393 .border_1()
2394 .border_color(self.tool_card_border_color(cx))
2395 .bg(cx.theme().colors().editor_background)
2396 .overflow_hidden()
2397 } else {
2398 this.my_1()
2399 }
2400 })
2401 .map(|this| {
2402 if has_location && !use_card_layout {
2403 this.ml_4()
2404 } else {
2405 this.ml_5()
2406 }
2407 })
2408 .mr_5()
2409 .map(|this| {
2410 if is_terminal_tool {
2411 this.child(
2412 v_flex()
2413 .p_1p5()
2414 .gap_0p5()
2415 .text_ui_sm(cx)
2416 .bg(self.tool_card_header_bg(cx))
2417 .child(
2418 Label::new("Run Command")
2419 .buffer_font(cx)
2420 .size(LabelSize::XSmall)
2421 .color(Color::Muted),
2422 )
2423 .child(
2424 MarkdownElement::new(
2425 tool_call.label.clone(),
2426 terminal_command_markdown_style(window, cx),
2427 )
2428 .code_block_renderer(
2429 markdown::CodeBlockRenderer::Default {
2430 copy_button: false,
2431 copy_button_on_hover: false,
2432 border: false,
2433 },
2434 )
2435 ),
2436 )
2437 } else {
2438 this.child(
2439 h_flex()
2440 .group(&card_header_id)
2441 .relative()
2442 .w_full()
2443 .gap_1()
2444 .justify_between()
2445 .when(use_card_layout, |this| {
2446 this.p_0p5()
2447 .rounded_t(rems_from_px(5.))
2448 .bg(self.tool_card_header_bg(cx))
2449 })
2450 .child(self.render_tool_call_label(
2451 entry_ix,
2452 tool_call,
2453 is_edit,
2454 use_card_layout,
2455 window,
2456 cx,
2457 ))
2458 .when(is_collapsible || failed_or_canceled, |this| {
2459 this.child(
2460 h_flex()
2461 .px_1()
2462 .gap_px()
2463 .when(is_collapsible, |this| {
2464 this.child(
2465 Disclosure::new(("expand", entry_ix), is_open)
2466 .opened_icon(IconName::ChevronUp)
2467 .closed_icon(IconName::ChevronDown)
2468 .visible_on_hover(&card_header_id)
2469 .on_click(cx.listener({
2470 let id = tool_call.id.clone();
2471 move |this: &mut Self, _, _, cx: &mut Context<Self>| {
2472 if is_open {
2473 this.expanded_tool_calls.remove(&id);
2474 } else {
2475 this.expanded_tool_calls.insert(id.clone());
2476 }
2477 cx.notify();
2478 }
2479 })),
2480 )
2481 })
2482 .when(failed_or_canceled, |this| {
2483 this.child(
2484 Icon::new(IconName::Close)
2485 .color(Color::Error)
2486 .size(IconSize::Small),
2487 )
2488 }),
2489 )
2490 }),
2491 )
2492 }
2493 })
2494 .children(tool_output_display)
2495 }
2496
2497 fn render_tool_call_label(
2498 &self,
2499 entry_ix: usize,
2500 tool_call: &ToolCall,
2501 is_edit: bool,
2502 use_card_layout: bool,
2503 window: &Window,
2504 cx: &Context<Self>,
2505 ) -> Div {
2506 let has_location = tool_call.locations.len() == 1;
2507
2508 let tool_icon = if tool_call.kind == acp::ToolKind::Edit && has_location {
2509 FileIcons::get_icon(&tool_call.locations[0].path, cx)
2510 .map(Icon::from_path)
2511 .unwrap_or(Icon::new(IconName::ToolPencil))
2512 } else {
2513 Icon::new(match tool_call.kind {
2514 acp::ToolKind::Read => IconName::ToolSearch,
2515 acp::ToolKind::Edit => IconName::ToolPencil,
2516 acp::ToolKind::Delete => IconName::ToolDeleteFile,
2517 acp::ToolKind::Move => IconName::ArrowRightLeft,
2518 acp::ToolKind::Search => IconName::ToolSearch,
2519 acp::ToolKind::Execute => IconName::ToolTerminal,
2520 acp::ToolKind::Think => IconName::ToolThink,
2521 acp::ToolKind::Fetch => IconName::ToolWeb,
2522 acp::ToolKind::SwitchMode => IconName::ArrowRightLeft,
2523 acp::ToolKind::Other => IconName::ToolHammer,
2524 })
2525 }
2526 .size(IconSize::Small)
2527 .color(Color::Muted);
2528
2529 let gradient_overlay = {
2530 div()
2531 .absolute()
2532 .top_0()
2533 .right_0()
2534 .w_12()
2535 .h_full()
2536 .map(|this| {
2537 if use_card_layout {
2538 this.bg(linear_gradient(
2539 90.,
2540 linear_color_stop(self.tool_card_header_bg(cx), 1.),
2541 linear_color_stop(self.tool_card_header_bg(cx).opacity(0.2), 0.),
2542 ))
2543 } else {
2544 this.bg(linear_gradient(
2545 90.,
2546 linear_color_stop(cx.theme().colors().panel_background, 1.),
2547 linear_color_stop(
2548 cx.theme().colors().panel_background.opacity(0.2),
2549 0.,
2550 ),
2551 ))
2552 }
2553 })
2554 };
2555
2556 h_flex()
2557 .relative()
2558 .w_full()
2559 .h(window.line_height() - px(2.))
2560 .text_size(self.tool_name_font_size())
2561 .gap_1p5()
2562 .when(has_location || use_card_layout, |this| this.px_1())
2563 .when(has_location, |this| {
2564 this.cursor(CursorStyle::PointingHand)
2565 .rounded(rems_from_px(3.)) // Concentric border radius
2566 .hover(|s| s.bg(cx.theme().colors().element_hover.opacity(0.5)))
2567 })
2568 .overflow_hidden()
2569 .child(tool_icon)
2570 .child(if has_location {
2571 h_flex()
2572 .id(("open-tool-call-location", entry_ix))
2573 .w_full()
2574 .map(|this| {
2575 if use_card_layout {
2576 this.text_color(cx.theme().colors().text)
2577 } else {
2578 this.text_color(cx.theme().colors().text_muted)
2579 }
2580 })
2581 .child(self.render_markdown(
2582 tool_call.label.clone(),
2583 MarkdownStyle {
2584 prevent_mouse_interaction: true,
2585 ..default_markdown_style(false, true, window, cx)
2586 },
2587 ))
2588 .tooltip(Tooltip::text("Jump to File"))
2589 .on_click(cx.listener(move |this, _, window, cx| {
2590 this.open_tool_call_location(entry_ix, 0, window, cx);
2591 }))
2592 .into_any_element()
2593 } else {
2594 h_flex()
2595 .w_full()
2596 .child(self.render_markdown(
2597 tool_call.label.clone(),
2598 default_markdown_style(false, true, window, cx),
2599 ))
2600 .into_any()
2601 })
2602 .when(!is_edit, |this| this.child(gradient_overlay))
2603 }
2604
2605 fn render_tool_call_content(
2606 &self,
2607 entry_ix: usize,
2608 content: &ToolCallContent,
2609 context_ix: usize,
2610 tool_call: &ToolCall,
2611 card_layout: bool,
2612 window: &Window,
2613 cx: &Context<Self>,
2614 ) -> AnyElement {
2615 match content {
2616 ToolCallContent::ContentBlock(content) => {
2617 if let Some(resource_link) = content.resource_link() {
2618 self.render_resource_link(resource_link, cx)
2619 } else if let Some(markdown) = content.markdown() {
2620 self.render_markdown_output(
2621 markdown.clone(),
2622 tool_call.id.clone(),
2623 context_ix,
2624 card_layout,
2625 window,
2626 cx,
2627 )
2628 } else {
2629 Empty.into_any_element()
2630 }
2631 }
2632 ToolCallContent::Diff(diff) => self.render_diff_editor(entry_ix, diff, tool_call, cx),
2633 ToolCallContent::Terminal(terminal) => {
2634 self.render_terminal_tool_call(entry_ix, terminal, tool_call, window, cx)
2635 }
2636 }
2637 }
2638
2639 fn render_markdown_output(
2640 &self,
2641 markdown: Entity<Markdown>,
2642 tool_call_id: acp::ToolCallId,
2643 context_ix: usize,
2644 card_layout: bool,
2645 window: &Window,
2646 cx: &Context<Self>,
2647 ) -> AnyElement {
2648 let button_id = SharedString::from(format!("tool_output-{:?}", tool_call_id));
2649
2650 v_flex()
2651 .mt_1p5()
2652 .gap_2()
2653 .when(!card_layout, |this| {
2654 this.ml(rems(0.4))
2655 .px_3p5()
2656 .border_l_1()
2657 .border_color(self.tool_card_border_color(cx))
2658 })
2659 .when(card_layout, |this| {
2660 this.px_2().pb_2().when(context_ix > 0, |this| {
2661 this.border_t_1()
2662 .pt_2()
2663 .border_color(self.tool_card_border_color(cx))
2664 })
2665 })
2666 .text_xs()
2667 .text_color(cx.theme().colors().text_muted)
2668 .child(self.render_markdown(markdown, default_markdown_style(false, false, window, cx)))
2669 .when(!card_layout, |this| {
2670 this.child(
2671 IconButton::new(button_id, IconName::ChevronUp)
2672 .full_width()
2673 .style(ButtonStyle::Outlined)
2674 .icon_color(Color::Muted)
2675 .on_click(cx.listener({
2676 move |this: &mut Self, _, _, cx: &mut Context<Self>| {
2677 this.expanded_tool_calls.remove(&tool_call_id);
2678 cx.notify();
2679 }
2680 })),
2681 )
2682 })
2683 .into_any_element()
2684 }
2685
2686 fn render_resource_link(
2687 &self,
2688 resource_link: &acp::ResourceLink,
2689 cx: &Context<Self>,
2690 ) -> AnyElement {
2691 let uri: SharedString = resource_link.uri.clone().into();
2692 let is_file = resource_link.uri.strip_prefix("file://");
2693
2694 let label: SharedString = if let Some(abs_path) = is_file {
2695 if let Some(project_path) = self
2696 .project
2697 .read(cx)
2698 .project_path_for_absolute_path(&Path::new(abs_path), cx)
2699 && let Some(worktree) = self
2700 .project
2701 .read(cx)
2702 .worktree_for_id(project_path.worktree_id, cx)
2703 {
2704 worktree
2705 .read(cx)
2706 .full_path(&project_path.path)
2707 .to_string_lossy()
2708 .to_string()
2709 .into()
2710 } else {
2711 abs_path.to_string().into()
2712 }
2713 } else {
2714 uri.clone()
2715 };
2716
2717 let button_id = SharedString::from(format!("item-{}", uri));
2718
2719 div()
2720 .ml(rems(0.4))
2721 .pl_2p5()
2722 .border_l_1()
2723 .border_color(self.tool_card_border_color(cx))
2724 .overflow_hidden()
2725 .child(
2726 Button::new(button_id, label)
2727 .label_size(LabelSize::Small)
2728 .color(Color::Muted)
2729 .truncate(true)
2730 .when(is_file.is_none(), |this| {
2731 this.icon(IconName::ArrowUpRight)
2732 .icon_size(IconSize::XSmall)
2733 .icon_color(Color::Muted)
2734 })
2735 .on_click(cx.listener({
2736 let workspace = self.workspace.clone();
2737 move |_, _, window, cx: &mut Context<Self>| {
2738 Self::open_link(uri.clone(), &workspace, window, cx);
2739 }
2740 })),
2741 )
2742 .into_any_element()
2743 }
2744
2745 fn render_permission_buttons(
2746 &self,
2747 kind: acp::ToolKind,
2748 options: &[acp::PermissionOption],
2749 entry_ix: usize,
2750 tool_call_id: acp::ToolCallId,
2751 cx: &Context<Self>,
2752 ) -> Div {
2753 let is_first = self.thread().is_some_and(|thread| {
2754 thread
2755 .read(cx)
2756 .first_tool_awaiting_confirmation()
2757 .is_some_and(|call| call.id == tool_call_id)
2758 });
2759 let mut seen_kinds: ArrayVec<acp::PermissionOptionKind, 3> = ArrayVec::new();
2760
2761 div()
2762 .p_1()
2763 .border_t_1()
2764 .border_color(self.tool_card_border_color(cx))
2765 .w_full()
2766 .map(|this| {
2767 if kind == acp::ToolKind::SwitchMode {
2768 this.v_flex()
2769 } else {
2770 this.h_flex().justify_end().flex_wrap()
2771 }
2772 })
2773 .gap_0p5()
2774 .children(options.iter().map(move |option| {
2775 let option_id = SharedString::from(option.id.0.clone());
2776 Button::new((option_id, entry_ix), option.name.clone())
2777 .map(|this| {
2778 let (this, action) = match option.kind {
2779 acp::PermissionOptionKind::AllowOnce => (
2780 this.icon(IconName::Check).icon_color(Color::Success),
2781 Some(&AllowOnce as &dyn Action),
2782 ),
2783 acp::PermissionOptionKind::AllowAlways => (
2784 this.icon(IconName::CheckDouble).icon_color(Color::Success),
2785 Some(&AllowAlways as &dyn Action),
2786 ),
2787 acp::PermissionOptionKind::RejectOnce => (
2788 this.icon(IconName::Close).icon_color(Color::Error),
2789 Some(&RejectOnce as &dyn Action),
2790 ),
2791 acp::PermissionOptionKind::RejectAlways => {
2792 (this.icon(IconName::Close).icon_color(Color::Error), None)
2793 }
2794 };
2795
2796 let Some(action) = action else {
2797 return this;
2798 };
2799
2800 if !is_first || seen_kinds.contains(&option.kind) {
2801 return this;
2802 }
2803
2804 seen_kinds.push(option.kind);
2805
2806 this.key_binding(
2807 KeyBinding::for_action_in(action, &self.focus_handle, cx)
2808 .map(|kb| kb.size(rems_from_px(10.))),
2809 )
2810 })
2811 .icon_position(IconPosition::Start)
2812 .icon_size(IconSize::XSmall)
2813 .label_size(LabelSize::Small)
2814 .on_click(cx.listener({
2815 let tool_call_id = tool_call_id.clone();
2816 let option_id = option.id.clone();
2817 let option_kind = option.kind;
2818 move |this, _, window, cx| {
2819 this.authorize_tool_call(
2820 tool_call_id.clone(),
2821 option_id.clone(),
2822 option_kind,
2823 window,
2824 cx,
2825 );
2826 }
2827 }))
2828 }))
2829 }
2830
2831 fn render_diff_loading(&self, cx: &Context<Self>) -> AnyElement {
2832 let bar = |n: u64, width_class: &str| {
2833 let bg_color = cx.theme().colors().element_active;
2834 let base = h_flex().h_1().rounded_full();
2835
2836 let modified = match width_class {
2837 "w_4_5" => base.w_3_4(),
2838 "w_1_4" => base.w_1_4(),
2839 "w_2_4" => base.w_2_4(),
2840 "w_3_5" => base.w_3_5(),
2841 "w_2_5" => base.w_2_5(),
2842 _ => base.w_1_2(),
2843 };
2844
2845 modified.with_animation(
2846 ElementId::Integer(n),
2847 Animation::new(Duration::from_secs(2)).repeat(),
2848 move |tab, delta| {
2849 let delta = (delta - 0.15 * n as f32) / 0.7;
2850 let delta = 1.0 - (0.5 - delta).abs() * 2.;
2851 let delta = ease_in_out(delta.clamp(0., 1.));
2852 let delta = 0.1 + 0.9 * delta;
2853
2854 tab.bg(bg_color.opacity(delta))
2855 },
2856 )
2857 };
2858
2859 v_flex()
2860 .p_3()
2861 .gap_1()
2862 .rounded_b_md()
2863 .bg(cx.theme().colors().editor_background)
2864 .child(bar(0, "w_4_5"))
2865 .child(bar(1, "w_1_4"))
2866 .child(bar(2, "w_2_4"))
2867 .child(bar(3, "w_3_5"))
2868 .child(bar(4, "w_2_5"))
2869 .into_any_element()
2870 }
2871
2872 fn render_diff_editor(
2873 &self,
2874 entry_ix: usize,
2875 diff: &Entity<acp_thread::Diff>,
2876 tool_call: &ToolCall,
2877 cx: &Context<Self>,
2878 ) -> AnyElement {
2879 let tool_progress = matches!(
2880 &tool_call.status,
2881 ToolCallStatus::InProgress | ToolCallStatus::Pending
2882 );
2883
2884 v_flex()
2885 .h_full()
2886 .border_t_1()
2887 .border_color(self.tool_card_border_color(cx))
2888 .child(
2889 if let Some(entry) = self.entry_view_state.read(cx).entry(entry_ix)
2890 && let Some(editor) = entry.editor_for_diff(diff)
2891 && diff.read(cx).has_revealed_range(cx)
2892 {
2893 editor.into_any_element()
2894 } else if tool_progress && self.as_native_connection(cx).is_some() {
2895 self.render_diff_loading(cx)
2896 } else {
2897 Empty.into_any()
2898 },
2899 )
2900 .into_any()
2901 }
2902
2903 fn render_terminal_tool_call(
2904 &self,
2905 entry_ix: usize,
2906 terminal: &Entity<acp_thread::Terminal>,
2907 tool_call: &ToolCall,
2908 window: &Window,
2909 cx: &Context<Self>,
2910 ) -> AnyElement {
2911 let terminal_data = terminal.read(cx);
2912 let working_dir = terminal_data.working_dir();
2913 let command = terminal_data.command();
2914 let started_at = terminal_data.started_at();
2915
2916 let tool_failed = matches!(
2917 &tool_call.status,
2918 ToolCallStatus::Rejected | ToolCallStatus::Canceled | ToolCallStatus::Failed
2919 );
2920
2921 let output = terminal_data.output();
2922 let command_finished = output.is_some();
2923 let truncated_output =
2924 output.is_some_and(|output| output.original_content_len > output.content.len());
2925 let output_line_count = output.map(|output| output.content_line_count).unwrap_or(0);
2926
2927 let command_failed = command_finished
2928 && output.is_some_and(|o| o.exit_status.is_some_and(|status| !status.success()));
2929
2930 let time_elapsed = if let Some(output) = output {
2931 output.ended_at.duration_since(started_at)
2932 } else {
2933 started_at.elapsed()
2934 };
2935
2936 let header_id =
2937 SharedString::from(format!("terminal-tool-header-{}", terminal.entity_id()));
2938 let header_group = SharedString::from(format!(
2939 "terminal-tool-header-group-{}",
2940 terminal.entity_id()
2941 ));
2942 let header_bg = cx
2943 .theme()
2944 .colors()
2945 .element_background
2946 .blend(cx.theme().colors().editor_foreground.opacity(0.025));
2947 let border_color = cx.theme().colors().border.opacity(0.6);
2948
2949 let working_dir = working_dir
2950 .as_ref()
2951 .map(|path| path.display().to_string())
2952 .unwrap_or_else(|| "current directory".to_string());
2953
2954 let is_expanded = self.expanded_tool_calls.contains(&tool_call.id);
2955
2956 let header = h_flex()
2957 .id(header_id)
2958 .flex_none()
2959 .gap_1()
2960 .justify_between()
2961 .rounded_t_md()
2962 .child(
2963 div()
2964 .id(("command-target-path", terminal.entity_id()))
2965 .w_full()
2966 .max_w_full()
2967 .overflow_x_scroll()
2968 .child(
2969 Label::new(working_dir)
2970 .buffer_font(cx)
2971 .size(LabelSize::XSmall)
2972 .color(Color::Muted),
2973 ),
2974 )
2975 .when(!command_finished, |header| {
2976 header
2977 .gap_1p5()
2978 .child(
2979 Button::new(
2980 SharedString::from(format!("stop-terminal-{}", terminal.entity_id())),
2981 "Stop",
2982 )
2983 .icon(IconName::Stop)
2984 .icon_position(IconPosition::Start)
2985 .icon_size(IconSize::Small)
2986 .icon_color(Color::Error)
2987 .label_size(LabelSize::Small)
2988 .tooltip(move |_window, cx| {
2989 Tooltip::with_meta(
2990 "Stop This Command",
2991 None,
2992 "Also possible by placing your cursor inside the terminal and using regular terminal bindings.",
2993 cx,
2994 )
2995 })
2996 .on_click({
2997 let terminal = terminal.clone();
2998 cx.listener(move |_this, _event, _window, cx| {
2999 let inner_terminal = terminal.read(cx).inner().clone();
3000 inner_terminal.update(cx, |inner_terminal, _cx| {
3001 inner_terminal.kill_active_task();
3002 });
3003 })
3004 }),
3005 )
3006 .child(Divider::vertical())
3007 .child(
3008 Icon::new(IconName::ArrowCircle)
3009 .size(IconSize::XSmall)
3010 .color(Color::Info)
3011 .with_rotate_animation(2)
3012 )
3013 })
3014 .when(truncated_output, |header| {
3015 let tooltip = if let Some(output) = output {
3016 if output_line_count + 10 > terminal::MAX_SCROLL_HISTORY_LINES {
3017 format!("Output exceeded terminal max lines and was \
3018 truncated, the model received the first {}.", format_file_size(output.content.len() as u64, true))
3019 } else {
3020 format!(
3021 "Output is {} long, and to avoid unexpected token usage, \
3022 only {} was sent back to the agent.",
3023 format_file_size(output.original_content_len as u64, true),
3024 format_file_size(output.content.len() as u64, true)
3025 )
3026 }
3027 } else {
3028 "Output was truncated".to_string()
3029 };
3030
3031 header.child(
3032 h_flex()
3033 .id(("terminal-tool-truncated-label", terminal.entity_id()))
3034 .gap_1()
3035 .child(
3036 Icon::new(IconName::Info)
3037 .size(IconSize::XSmall)
3038 .color(Color::Ignored),
3039 )
3040 .child(
3041 Label::new("Truncated")
3042 .color(Color::Muted)
3043 .size(LabelSize::XSmall),
3044 )
3045 .tooltip(Tooltip::text(tooltip)),
3046 )
3047 })
3048 .when(time_elapsed > Duration::from_secs(10), |header| {
3049 header.child(
3050 Label::new(format!("({})", duration_alt_display(time_elapsed)))
3051 .buffer_font(cx)
3052 .color(Color::Muted)
3053 .size(LabelSize::XSmall),
3054 )
3055 })
3056 .when(tool_failed || command_failed, |header| {
3057 header.child(
3058 div()
3059 .id(("terminal-tool-error-code-indicator", terminal.entity_id()))
3060 .child(
3061 Icon::new(IconName::Close)
3062 .size(IconSize::Small)
3063 .color(Color::Error),
3064 )
3065 .when_some(output.and_then(|o| o.exit_status), |this, status| {
3066 this.tooltip(Tooltip::text(format!(
3067 "Exited with code {}",
3068 status.code().unwrap_or(-1),
3069 )))
3070 }),
3071 )
3072 })
3073 .child(
3074 Disclosure::new(
3075 SharedString::from(format!(
3076 "terminal-tool-disclosure-{}",
3077 terminal.entity_id()
3078 )),
3079 is_expanded,
3080 )
3081 .opened_icon(IconName::ChevronUp)
3082 .closed_icon(IconName::ChevronDown)
3083 .visible_on_hover(&header_group)
3084 .on_click(cx.listener({
3085 let id = tool_call.id.clone();
3086 move |this, _event, _window, _cx| {
3087 if is_expanded {
3088 this.expanded_tool_calls.remove(&id);
3089 } else {
3090 this.expanded_tool_calls.insert(id.clone());
3091 }
3092 }
3093 })),
3094 );
3095
3096 let terminal_view = self
3097 .entry_view_state
3098 .read(cx)
3099 .entry(entry_ix)
3100 .and_then(|entry| entry.terminal(terminal));
3101 let show_output = is_expanded && terminal_view.is_some();
3102
3103 v_flex()
3104 .my_1p5()
3105 .mx_5()
3106 .border_1()
3107 .when(tool_failed || command_failed, |card| card.border_dashed())
3108 .border_color(border_color)
3109 .rounded_md()
3110 .overflow_hidden()
3111 .child(
3112 v_flex()
3113 .group(&header_group)
3114 .py_1p5()
3115 .pr_1p5()
3116 .pl_2()
3117 .gap_0p5()
3118 .bg(header_bg)
3119 .text_xs()
3120 .child(header)
3121 .child(
3122 MarkdownElement::new(
3123 command.clone(),
3124 terminal_command_markdown_style(window, cx),
3125 )
3126 .code_block_renderer(
3127 markdown::CodeBlockRenderer::Default {
3128 copy_button: false,
3129 copy_button_on_hover: true,
3130 border: false,
3131 },
3132 ),
3133 ),
3134 )
3135 .when(show_output, |this| {
3136 this.child(
3137 div()
3138 .pt_2()
3139 .border_t_1()
3140 .when(tool_failed || command_failed, |card| card.border_dashed())
3141 .border_color(border_color)
3142 .bg(cx.theme().colors().editor_background)
3143 .rounded_b_md()
3144 .text_ui_sm(cx)
3145 .h_full()
3146 .children(terminal_view.map(|terminal_view| {
3147 if terminal_view
3148 .read(cx)
3149 .content_mode(window, cx)
3150 .is_scrollable()
3151 {
3152 div().h_72().child(terminal_view).into_any_element()
3153 } else {
3154 terminal_view.into_any_element()
3155 }
3156 })),
3157 )
3158 })
3159 .into_any()
3160 }
3161
3162 fn render_rules_item(&self, cx: &Context<Self>) -> Option<AnyElement> {
3163 let project_context = self
3164 .as_native_thread(cx)?
3165 .read(cx)
3166 .project_context()
3167 .read(cx);
3168
3169 let user_rules_text = if project_context.user_rules.is_empty() {
3170 None
3171 } else if project_context.user_rules.len() == 1 {
3172 let user_rules = &project_context.user_rules[0];
3173
3174 match user_rules.title.as_ref() {
3175 Some(title) => Some(format!("Using \"{title}\" user rule")),
3176 None => Some("Using user rule".into()),
3177 }
3178 } else {
3179 Some(format!(
3180 "Using {} user rules",
3181 project_context.user_rules.len()
3182 ))
3183 };
3184
3185 let first_user_rules_id = project_context
3186 .user_rules
3187 .first()
3188 .map(|user_rules| user_rules.uuid.0);
3189
3190 let rules_files = project_context
3191 .worktrees
3192 .iter()
3193 .filter_map(|worktree| worktree.rules_file.as_ref())
3194 .collect::<Vec<_>>();
3195
3196 let rules_file_text = match rules_files.as_slice() {
3197 &[] => None,
3198 &[rules_file] => Some(format!(
3199 "Using project {:?} file",
3200 rules_file.path_in_worktree
3201 )),
3202 rules_files => Some(format!("Using {} project rules files", rules_files.len())),
3203 };
3204
3205 if user_rules_text.is_none() && rules_file_text.is_none() {
3206 return None;
3207 }
3208
3209 let has_both = user_rules_text.is_some() && rules_file_text.is_some();
3210
3211 Some(
3212 h_flex()
3213 .px_2p5()
3214 .child(
3215 Icon::new(IconName::Attach)
3216 .size(IconSize::XSmall)
3217 .color(Color::Disabled),
3218 )
3219 .when_some(user_rules_text, |parent, user_rules_text| {
3220 parent.child(
3221 h_flex()
3222 .id("user-rules")
3223 .ml_1()
3224 .mr_1p5()
3225 .child(
3226 Label::new(user_rules_text)
3227 .size(LabelSize::XSmall)
3228 .color(Color::Muted)
3229 .truncate(),
3230 )
3231 .hover(|s| s.bg(cx.theme().colors().element_hover))
3232 .tooltip(Tooltip::text("View User Rules"))
3233 .on_click(move |_event, window, cx| {
3234 window.dispatch_action(
3235 Box::new(OpenRulesLibrary {
3236 prompt_to_select: first_user_rules_id,
3237 }),
3238 cx,
3239 )
3240 }),
3241 )
3242 })
3243 .when(has_both, |this| {
3244 this.child(
3245 Label::new("•")
3246 .size(LabelSize::XSmall)
3247 .color(Color::Disabled),
3248 )
3249 })
3250 .when_some(rules_file_text, |parent, rules_file_text| {
3251 parent.child(
3252 h_flex()
3253 .id("project-rules")
3254 .ml_1p5()
3255 .child(
3256 Label::new(rules_file_text)
3257 .size(LabelSize::XSmall)
3258 .color(Color::Muted),
3259 )
3260 .hover(|s| s.bg(cx.theme().colors().element_hover))
3261 .tooltip(Tooltip::text("View Project Rules"))
3262 .on_click(cx.listener(Self::handle_open_rules)),
3263 )
3264 })
3265 .into_any(),
3266 )
3267 }
3268
3269 fn render_empty_state_section_header(
3270 &self,
3271 label: impl Into<SharedString>,
3272 action_slot: Option<AnyElement>,
3273 cx: &mut Context<Self>,
3274 ) -> impl IntoElement {
3275 div().pl_1().pr_1p5().child(
3276 h_flex()
3277 .mt_2()
3278 .pl_1p5()
3279 .pb_1()
3280 .w_full()
3281 .justify_between()
3282 .border_b_1()
3283 .border_color(cx.theme().colors().border_variant)
3284 .child(
3285 Label::new(label.into())
3286 .size(LabelSize::Small)
3287 .color(Color::Muted),
3288 )
3289 .children(action_slot),
3290 )
3291 }
3292
3293 fn render_recent_history(&self, cx: &mut Context<Self>) -> AnyElement {
3294 let render_history = self
3295 .agent
3296 .clone()
3297 .downcast::<agent::NativeAgentServer>()
3298 .is_some()
3299 && self
3300 .history_store
3301 .update(cx, |history_store, cx| !history_store.is_empty(cx));
3302
3303 v_flex()
3304 .size_full()
3305 .when(render_history, |this| {
3306 let recent_history: Vec<_> = self.history_store.update(cx, |history_store, _| {
3307 history_store.entries().take(3).collect()
3308 });
3309 this.justify_end().child(
3310 v_flex()
3311 .child(
3312 self.render_empty_state_section_header(
3313 "Recent",
3314 Some(
3315 Button::new("view-history", "View All")
3316 .style(ButtonStyle::Subtle)
3317 .label_size(LabelSize::Small)
3318 .key_binding(
3319 KeyBinding::for_action_in(
3320 &OpenHistory,
3321 &self.focus_handle(cx),
3322 cx,
3323 )
3324 .map(|kb| kb.size(rems_from_px(12.))),
3325 )
3326 .on_click(move |_event, window, cx| {
3327 window.dispatch_action(OpenHistory.boxed_clone(), cx);
3328 })
3329 .into_any_element(),
3330 ),
3331 cx,
3332 ),
3333 )
3334 .child(
3335 v_flex().p_1().pr_1p5().gap_1().children(
3336 recent_history
3337 .into_iter()
3338 .enumerate()
3339 .map(|(index, entry)| {
3340 // TODO: Add keyboard navigation.
3341 let is_hovered =
3342 self.hovered_recent_history_item == Some(index);
3343 crate::acp::thread_history::AcpHistoryEntryElement::new(
3344 entry,
3345 cx.entity().downgrade(),
3346 )
3347 .hovered(is_hovered)
3348 .on_hover(cx.listener(
3349 move |this, is_hovered, _window, cx| {
3350 if *is_hovered {
3351 this.hovered_recent_history_item = Some(index);
3352 } else if this.hovered_recent_history_item
3353 == Some(index)
3354 {
3355 this.hovered_recent_history_item = None;
3356 }
3357 cx.notify();
3358 },
3359 ))
3360 .into_any_element()
3361 }),
3362 ),
3363 ),
3364 )
3365 })
3366 .into_any()
3367 }
3368
3369 fn render_auth_required_state(
3370 &self,
3371 connection: &Rc<dyn AgentConnection>,
3372 description: Option<&Entity<Markdown>>,
3373 configuration_view: Option<&AnyView>,
3374 pending_auth_method: Option<&acp::AuthMethodId>,
3375 window: &mut Window,
3376 cx: &Context<Self>,
3377 ) -> Div {
3378 let show_description =
3379 configuration_view.is_none() && description.is_none() && pending_auth_method.is_none();
3380
3381 let auth_methods = connection.auth_methods();
3382
3383 v_flex().flex_1().size_full().justify_end().child(
3384 v_flex()
3385 .p_2()
3386 .pr_3()
3387 .w_full()
3388 .gap_1()
3389 .border_t_1()
3390 .border_color(cx.theme().colors().border)
3391 .bg(cx.theme().status().warning.opacity(0.04))
3392 .child(
3393 h_flex()
3394 .gap_1p5()
3395 .child(
3396 Icon::new(IconName::Warning)
3397 .color(Color::Warning)
3398 .size(IconSize::Small),
3399 )
3400 .child(Label::new("Authentication Required").size(LabelSize::Small)),
3401 )
3402 .children(description.map(|desc| {
3403 div().text_ui(cx).child(self.render_markdown(
3404 desc.clone(),
3405 default_markdown_style(false, false, window, cx),
3406 ))
3407 }))
3408 .children(
3409 configuration_view
3410 .cloned()
3411 .map(|view| div().w_full().child(view)),
3412 )
3413 .when(show_description, |el| {
3414 el.child(
3415 Label::new(format!(
3416 "You are not currently authenticated with {}.{}",
3417 self.agent.name(),
3418 if auth_methods.len() > 1 {
3419 " Please choose one of the following options:"
3420 } else {
3421 ""
3422 }
3423 ))
3424 .size(LabelSize::Small)
3425 .color(Color::Muted)
3426 .mb_1()
3427 .ml_5(),
3428 )
3429 })
3430 .when_some(pending_auth_method, |el, _| {
3431 el.child(
3432 h_flex()
3433 .py_4()
3434 .w_full()
3435 .justify_center()
3436 .gap_1()
3437 .child(
3438 Icon::new(IconName::ArrowCircle)
3439 .size(IconSize::Small)
3440 .color(Color::Muted)
3441 .with_rotate_animation(2),
3442 )
3443 .child(Label::new("Authenticating…").size(LabelSize::Small)),
3444 )
3445 })
3446 .when(!auth_methods.is_empty(), |this| {
3447 this.child(
3448 h_flex()
3449 .justify_end()
3450 .flex_wrap()
3451 .gap_1()
3452 .when(!show_description, |this| {
3453 this.border_t_1()
3454 .mt_1()
3455 .pt_2()
3456 .border_color(cx.theme().colors().border.opacity(0.8))
3457 })
3458 .children(connection.auth_methods().iter().enumerate().rev().map(
3459 |(ix, method)| {
3460 let (method_id, name) = if self
3461 .project
3462 .read(cx)
3463 .is_via_remote_server()
3464 && method.id.0.as_ref() == "oauth-personal"
3465 && method.name == "Log in with Google"
3466 {
3467 ("spawn-gemini-cli".into(), "Log in with Gemini CLI".into())
3468 } else {
3469 (method.id.0.clone(), method.name.clone())
3470 };
3471
3472 Button::new(SharedString::from(method_id.clone()), name)
3473 .label_size(LabelSize::Small)
3474 .map(|this| {
3475 if ix == 0 {
3476 this.style(ButtonStyle::Tinted(TintColor::Warning))
3477 } else {
3478 this.style(ButtonStyle::Outlined)
3479 }
3480 })
3481 .when_some(
3482 method.description.clone(),
3483 |this, description| {
3484 this.tooltip(Tooltip::text(description))
3485 },
3486 )
3487 .on_click({
3488 cx.listener(move |this, _, window, cx| {
3489 telemetry::event!(
3490 "Authenticate Agent Started",
3491 agent = this.agent.telemetry_id(),
3492 method = method_id
3493 );
3494
3495 this.authenticate(
3496 acp::AuthMethodId(method_id.clone()),
3497 window,
3498 cx,
3499 )
3500 })
3501 })
3502 },
3503 )),
3504 )
3505 }),
3506 )
3507 }
3508
3509 fn render_load_error(
3510 &self,
3511 e: &LoadError,
3512 window: &mut Window,
3513 cx: &mut Context<Self>,
3514 ) -> AnyElement {
3515 let (title, message, action_slot): (_, SharedString, _) = match e {
3516 LoadError::Unsupported {
3517 command: path,
3518 current_version,
3519 minimum_version,
3520 } => {
3521 return self.render_unsupported(path, current_version, minimum_version, window, cx);
3522 }
3523 LoadError::FailedToInstall(msg) => (
3524 "Failed to Install",
3525 msg.into(),
3526 Some(self.create_copy_button(msg.to_string()).into_any_element()),
3527 ),
3528 LoadError::Exited { status } => (
3529 "Failed to Launch",
3530 format!("Server exited with status {status}").into(),
3531 None,
3532 ),
3533 LoadError::Other(msg) => (
3534 "Failed to Launch",
3535 msg.into(),
3536 Some(self.create_copy_button(msg.to_string()).into_any_element()),
3537 ),
3538 };
3539
3540 Callout::new()
3541 .severity(Severity::Error)
3542 .icon(IconName::XCircleFilled)
3543 .title(title)
3544 .description(message)
3545 .actions_slot(div().children(action_slot))
3546 .into_any_element()
3547 }
3548
3549 fn render_unsupported(
3550 &self,
3551 path: &SharedString,
3552 version: &SharedString,
3553 minimum_version: &SharedString,
3554 _window: &mut Window,
3555 cx: &mut Context<Self>,
3556 ) -> AnyElement {
3557 let (heading_label, description_label) = (
3558 format!("Upgrade {} to work with Zed", self.agent.name()),
3559 if version.is_empty() {
3560 format!(
3561 "Currently using {}, which does not report a valid --version",
3562 path,
3563 )
3564 } else {
3565 format!(
3566 "Currently using {}, which is only version {} (need at least {minimum_version})",
3567 path, version
3568 )
3569 },
3570 );
3571
3572 v_flex()
3573 .w_full()
3574 .p_3p5()
3575 .gap_2p5()
3576 .border_t_1()
3577 .border_color(cx.theme().colors().border)
3578 .bg(linear_gradient(
3579 180.,
3580 linear_color_stop(cx.theme().colors().editor_background.opacity(0.4), 4.),
3581 linear_color_stop(cx.theme().status().info_background.opacity(0.), 0.),
3582 ))
3583 .child(
3584 v_flex().gap_0p5().child(Label::new(heading_label)).child(
3585 Label::new(description_label)
3586 .size(LabelSize::Small)
3587 .color(Color::Muted),
3588 ),
3589 )
3590 .into_any_element()
3591 }
3592
3593 fn activity_bar_bg(&self, cx: &Context<Self>) -> Hsla {
3594 let editor_bg_color = cx.theme().colors().editor_background;
3595 let active_color = cx.theme().colors().element_selected;
3596 editor_bg_color.blend(active_color.opacity(0.3))
3597 }
3598
3599 fn render_activity_bar(
3600 &self,
3601 thread_entity: &Entity<AcpThread>,
3602 window: &mut Window,
3603 cx: &Context<Self>,
3604 ) -> Option<AnyElement> {
3605 let thread = thread_entity.read(cx);
3606 let action_log = thread.action_log();
3607 let telemetry = ActionLogTelemetry::from(thread);
3608 let changed_buffers = action_log.read(cx).changed_buffers(cx);
3609 let plan = thread.plan();
3610
3611 if changed_buffers.is_empty() && plan.is_empty() {
3612 return None;
3613 }
3614
3615 // Temporarily always enable ACP edit controls. This is temporary, to lessen the
3616 // impact of a nasty bug that causes them to sometimes be disabled when they shouldn't
3617 // be, which blocks you from being able to accept or reject edits. This switches the
3618 // bug to be that sometimes it's enabled when it shouldn't be, which at least doesn't
3619 // block you from using the panel.
3620 let pending_edits = false;
3621
3622 v_flex()
3623 .mt_1()
3624 .mx_2()
3625 .bg(self.activity_bar_bg(cx))
3626 .border_1()
3627 .border_b_0()
3628 .border_color(cx.theme().colors().border)
3629 .rounded_t_md()
3630 .shadow(vec![gpui::BoxShadow {
3631 color: gpui::black().opacity(0.15),
3632 offset: point(px(1.), px(-1.)),
3633 blur_radius: px(3.),
3634 spread_radius: px(0.),
3635 }])
3636 .when(!plan.is_empty(), |this| {
3637 this.child(self.render_plan_summary(plan, window, cx))
3638 .when(self.plan_expanded, |parent| {
3639 parent.child(self.render_plan_entries(plan, window, cx))
3640 })
3641 })
3642 .when(!plan.is_empty() && !changed_buffers.is_empty(), |this| {
3643 this.child(Divider::horizontal().color(DividerColor::Border))
3644 })
3645 .when(!changed_buffers.is_empty(), |this| {
3646 this.child(self.render_edits_summary(
3647 &changed_buffers,
3648 self.edits_expanded,
3649 pending_edits,
3650 cx,
3651 ))
3652 .when(self.edits_expanded, |parent| {
3653 parent.child(self.render_edited_files(
3654 action_log,
3655 telemetry,
3656 &changed_buffers,
3657 pending_edits,
3658 cx,
3659 ))
3660 })
3661 })
3662 .into_any()
3663 .into()
3664 }
3665
3666 fn render_plan_summary(
3667 &self,
3668 plan: &Plan,
3669 window: &mut Window,
3670 cx: &Context<Self>,
3671 ) -> impl IntoElement {
3672 let stats = plan.stats();
3673
3674 let title = if let Some(entry) = stats.in_progress_entry
3675 && !self.plan_expanded
3676 {
3677 h_flex()
3678 .cursor_default()
3679 .relative()
3680 .w_full()
3681 .gap_1()
3682 .truncate()
3683 .child(
3684 Label::new("Current:")
3685 .size(LabelSize::Small)
3686 .color(Color::Muted),
3687 )
3688 .child(
3689 div()
3690 .text_xs()
3691 .text_color(cx.theme().colors().text_muted)
3692 .line_clamp(1)
3693 .child(MarkdownElement::new(
3694 entry.content.clone(),
3695 plan_label_markdown_style(&entry.status, window, cx),
3696 )),
3697 )
3698 .when(stats.pending > 0, |this| {
3699 this.child(
3700 h_flex()
3701 .absolute()
3702 .top_0()
3703 .right_0()
3704 .h_full()
3705 .child(div().min_w_8().h_full().bg(linear_gradient(
3706 90.,
3707 linear_color_stop(self.activity_bar_bg(cx), 1.),
3708 linear_color_stop(self.activity_bar_bg(cx).opacity(0.2), 0.),
3709 )))
3710 .child(
3711 div().pr_0p5().bg(self.activity_bar_bg(cx)).child(
3712 Label::new(format!("{} left", stats.pending))
3713 .size(LabelSize::Small)
3714 .color(Color::Muted),
3715 ),
3716 ),
3717 )
3718 })
3719 } else {
3720 let status_label = if stats.pending == 0 {
3721 "All Done".to_string()
3722 } else if stats.completed == 0 {
3723 format!("{} Tasks", plan.entries.len())
3724 } else {
3725 format!("{}/{}", stats.completed, plan.entries.len())
3726 };
3727
3728 h_flex()
3729 .w_full()
3730 .gap_1()
3731 .justify_between()
3732 .child(
3733 Label::new("Plan")
3734 .size(LabelSize::Small)
3735 .color(Color::Muted),
3736 )
3737 .child(
3738 Label::new(status_label)
3739 .size(LabelSize::Small)
3740 .color(Color::Muted)
3741 .mr_1(),
3742 )
3743 };
3744
3745 h_flex()
3746 .id("plan_summary")
3747 .p_1()
3748 .w_full()
3749 .gap_1()
3750 .when(self.plan_expanded, |this| {
3751 this.border_b_1().border_color(cx.theme().colors().border)
3752 })
3753 .child(Disclosure::new("plan_disclosure", self.plan_expanded))
3754 .child(title)
3755 .on_click(cx.listener(|this, _, _, cx| {
3756 this.plan_expanded = !this.plan_expanded;
3757 cx.notify();
3758 }))
3759 }
3760
3761 fn render_plan_entries(&self, plan: &Plan, window: &mut Window, cx: &Context<Self>) -> Div {
3762 v_flex().children(plan.entries.iter().enumerate().flat_map(|(index, entry)| {
3763 let element = h_flex()
3764 .py_1()
3765 .px_2()
3766 .gap_2()
3767 .justify_between()
3768 .bg(cx.theme().colors().editor_background)
3769 .when(index < plan.entries.len() - 1, |parent| {
3770 parent.border_color(cx.theme().colors().border).border_b_1()
3771 })
3772 .child(
3773 h_flex()
3774 .id(("plan_entry", index))
3775 .gap_1p5()
3776 .max_w_full()
3777 .overflow_x_scroll()
3778 .text_xs()
3779 .text_color(cx.theme().colors().text_muted)
3780 .child(match entry.status {
3781 acp::PlanEntryStatus::Pending => Icon::new(IconName::TodoPending)
3782 .size(IconSize::Small)
3783 .color(Color::Muted)
3784 .into_any_element(),
3785 acp::PlanEntryStatus::InProgress => Icon::new(IconName::TodoProgress)
3786 .size(IconSize::Small)
3787 .color(Color::Accent)
3788 .with_rotate_animation(2)
3789 .into_any_element(),
3790 acp::PlanEntryStatus::Completed => Icon::new(IconName::TodoComplete)
3791 .size(IconSize::Small)
3792 .color(Color::Success)
3793 .into_any_element(),
3794 })
3795 .child(MarkdownElement::new(
3796 entry.content.clone(),
3797 plan_label_markdown_style(&entry.status, window, cx),
3798 )),
3799 );
3800
3801 Some(element)
3802 }))
3803 }
3804
3805 fn render_edits_summary(
3806 &self,
3807 changed_buffers: &BTreeMap<Entity<Buffer>, Entity<BufferDiff>>,
3808 expanded: bool,
3809 pending_edits: bool,
3810 cx: &Context<Self>,
3811 ) -> Div {
3812 const EDIT_NOT_READY_TOOLTIP_LABEL: &str = "Wait until file edits are complete.";
3813
3814 let focus_handle = self.focus_handle(cx);
3815
3816 h_flex()
3817 .p_1()
3818 .justify_between()
3819 .flex_wrap()
3820 .when(expanded, |this| {
3821 this.border_b_1().border_color(cx.theme().colors().border)
3822 })
3823 .child(
3824 h_flex()
3825 .id("edits-container")
3826 .cursor_pointer()
3827 .gap_1()
3828 .child(Disclosure::new("edits-disclosure", expanded))
3829 .map(|this| {
3830 if pending_edits {
3831 this.child(
3832 Label::new(format!(
3833 "Editing {} {}…",
3834 changed_buffers.len(),
3835 if changed_buffers.len() == 1 {
3836 "file"
3837 } else {
3838 "files"
3839 }
3840 ))
3841 .color(Color::Muted)
3842 .size(LabelSize::Small)
3843 .with_animation(
3844 "edit-label",
3845 Animation::new(Duration::from_secs(2))
3846 .repeat()
3847 .with_easing(pulsating_between(0.3, 0.7)),
3848 |label, delta| label.alpha(delta),
3849 ),
3850 )
3851 } else {
3852 this.child(
3853 Label::new("Edits")
3854 .size(LabelSize::Small)
3855 .color(Color::Muted),
3856 )
3857 .child(Label::new("•").size(LabelSize::XSmall).color(Color::Muted))
3858 .child(
3859 Label::new(format!(
3860 "{} {}",
3861 changed_buffers.len(),
3862 if changed_buffers.len() == 1 {
3863 "file"
3864 } else {
3865 "files"
3866 }
3867 ))
3868 .size(LabelSize::Small)
3869 .color(Color::Muted),
3870 )
3871 }
3872 })
3873 .on_click(cx.listener(|this, _, _, cx| {
3874 this.edits_expanded = !this.edits_expanded;
3875 cx.notify();
3876 })),
3877 )
3878 .child(
3879 h_flex()
3880 .gap_1()
3881 .child(
3882 IconButton::new("review-changes", IconName::ListTodo)
3883 .icon_size(IconSize::Small)
3884 .tooltip({
3885 let focus_handle = focus_handle.clone();
3886 move |_window, cx| {
3887 Tooltip::for_action_in(
3888 "Review Changes",
3889 &OpenAgentDiff,
3890 &focus_handle,
3891 cx,
3892 )
3893 }
3894 })
3895 .on_click(cx.listener(|_, _, window, cx| {
3896 window.dispatch_action(OpenAgentDiff.boxed_clone(), cx);
3897 })),
3898 )
3899 .child(Divider::vertical().color(DividerColor::Border))
3900 .child(
3901 Button::new("reject-all-changes", "Reject All")
3902 .label_size(LabelSize::Small)
3903 .disabled(pending_edits)
3904 .when(pending_edits, |this| {
3905 this.tooltip(Tooltip::text(EDIT_NOT_READY_TOOLTIP_LABEL))
3906 })
3907 .key_binding(
3908 KeyBinding::for_action_in(&RejectAll, &focus_handle.clone(), cx)
3909 .map(|kb| kb.size(rems_from_px(10.))),
3910 )
3911 .on_click(cx.listener(move |this, _, window, cx| {
3912 this.reject_all(&RejectAll, window, cx);
3913 })),
3914 )
3915 .child(
3916 Button::new("keep-all-changes", "Keep All")
3917 .label_size(LabelSize::Small)
3918 .disabled(pending_edits)
3919 .when(pending_edits, |this| {
3920 this.tooltip(Tooltip::text(EDIT_NOT_READY_TOOLTIP_LABEL))
3921 })
3922 .key_binding(
3923 KeyBinding::for_action_in(&KeepAll, &focus_handle, cx)
3924 .map(|kb| kb.size(rems_from_px(10.))),
3925 )
3926 .on_click(cx.listener(move |this, _, window, cx| {
3927 this.keep_all(&KeepAll, window, cx);
3928 })),
3929 ),
3930 )
3931 }
3932
3933 fn render_edited_files(
3934 &self,
3935 action_log: &Entity<ActionLog>,
3936 telemetry: ActionLogTelemetry,
3937 changed_buffers: &BTreeMap<Entity<Buffer>, Entity<BufferDiff>>,
3938 pending_edits: bool,
3939 cx: &Context<Self>,
3940 ) -> Div {
3941 let editor_bg_color = cx.theme().colors().editor_background;
3942
3943 v_flex().children(changed_buffers.iter().enumerate().flat_map(
3944 |(index, (buffer, _diff))| {
3945 let file = buffer.read(cx).file()?;
3946 let path = file.path();
3947 let path_style = file.path_style(cx);
3948 let separator = file.path_style(cx).separator();
3949
3950 let file_path = path.parent().and_then(|parent| {
3951 if parent.is_empty() {
3952 None
3953 } else {
3954 Some(
3955 Label::new(format!("{}{separator}", parent.display(path_style)))
3956 .color(Color::Muted)
3957 .size(LabelSize::XSmall)
3958 .buffer_font(cx),
3959 )
3960 }
3961 });
3962
3963 let file_name = path.file_name().map(|name| {
3964 Label::new(name.to_string())
3965 .size(LabelSize::XSmall)
3966 .buffer_font(cx)
3967 .ml_1p5()
3968 });
3969
3970 let file_icon = FileIcons::get_icon(path.as_std_path(), cx)
3971 .map(Icon::from_path)
3972 .map(|icon| icon.color(Color::Muted).size(IconSize::Small))
3973 .unwrap_or_else(|| {
3974 Icon::new(IconName::File)
3975 .color(Color::Muted)
3976 .size(IconSize::Small)
3977 });
3978
3979 let overlay_gradient = linear_gradient(
3980 90.,
3981 linear_color_stop(editor_bg_color, 1.),
3982 linear_color_stop(editor_bg_color.opacity(0.2), 0.),
3983 );
3984
3985 let element = h_flex()
3986 .group("edited-code")
3987 .id(("file-container", index))
3988 .py_1()
3989 .pl_2()
3990 .pr_1()
3991 .gap_2()
3992 .justify_between()
3993 .bg(editor_bg_color)
3994 .when(index < changed_buffers.len() - 1, |parent| {
3995 parent.border_color(cx.theme().colors().border).border_b_1()
3996 })
3997 .child(
3998 h_flex()
3999 .id(("file-name-row", index))
4000 .relative()
4001 .pr_8()
4002 .w_full()
4003 .overflow_x_scroll()
4004 .child(
4005 h_flex()
4006 .id(("file-name-path", index))
4007 .cursor_pointer()
4008 .pr_0p5()
4009 .gap_0p5()
4010 .hover(|s| s.bg(cx.theme().colors().element_hover))
4011 .rounded_xs()
4012 .child(file_icon)
4013 .children(file_name)
4014 .children(file_path)
4015 .tooltip(Tooltip::text("Go to File"))
4016 .on_click({
4017 let buffer = buffer.clone();
4018 cx.listener(move |this, _, window, cx| {
4019 this.open_edited_buffer(&buffer, window, cx);
4020 })
4021 }),
4022 )
4023 .child(
4024 div()
4025 .absolute()
4026 .h_full()
4027 .w_12()
4028 .top_0()
4029 .bottom_0()
4030 .right_0()
4031 .bg(overlay_gradient),
4032 ),
4033 )
4034 .child(
4035 h_flex()
4036 .gap_1()
4037 .visible_on_hover("edited-code")
4038 .child(
4039 Button::new("review", "Review")
4040 .label_size(LabelSize::Small)
4041 .on_click({
4042 let buffer = buffer.clone();
4043 cx.listener(move |this, _, window, cx| {
4044 this.open_edited_buffer(&buffer, window, cx);
4045 })
4046 }),
4047 )
4048 .child(Divider::vertical().color(DividerColor::BorderVariant))
4049 .child(
4050 Button::new("reject-file", "Reject")
4051 .label_size(LabelSize::Small)
4052 .disabled(pending_edits)
4053 .on_click({
4054 let buffer = buffer.clone();
4055 let action_log = action_log.clone();
4056 let telemetry = telemetry.clone();
4057 move |_, _, cx| {
4058 action_log.update(cx, |action_log, cx| {
4059 action_log
4060 .reject_edits_in_ranges(
4061 buffer.clone(),
4062 vec![Anchor::MIN..Anchor::MAX],
4063 Some(telemetry.clone()),
4064 cx,
4065 )
4066 .detach_and_log_err(cx);
4067 })
4068 }
4069 }),
4070 )
4071 .child(
4072 Button::new("keep-file", "Keep")
4073 .label_size(LabelSize::Small)
4074 .disabled(pending_edits)
4075 .on_click({
4076 let buffer = buffer.clone();
4077 let action_log = action_log.clone();
4078 let telemetry = telemetry.clone();
4079 move |_, _, cx| {
4080 action_log.update(cx, |action_log, cx| {
4081 action_log.keep_edits_in_range(
4082 buffer.clone(),
4083 Anchor::MIN..Anchor::MAX,
4084 Some(telemetry.clone()),
4085 cx,
4086 );
4087 })
4088 }
4089 }),
4090 ),
4091 );
4092
4093 Some(element)
4094 },
4095 ))
4096 }
4097
4098 fn render_message_editor(&mut self, window: &mut Window, cx: &mut Context<Self>) -> AnyElement {
4099 let focus_handle = self.message_editor.focus_handle(cx);
4100 let editor_bg_color = cx.theme().colors().editor_background;
4101 let (expand_icon, expand_tooltip) = if self.editor_expanded {
4102 (IconName::Minimize, "Minimize Message Editor")
4103 } else {
4104 (IconName::Maximize, "Expand Message Editor")
4105 };
4106
4107 let backdrop = div()
4108 .size_full()
4109 .absolute()
4110 .inset_0()
4111 .bg(cx.theme().colors().panel_background)
4112 .opacity(0.8)
4113 .block_mouse_except_scroll();
4114
4115 let enable_editor = match self.thread_state {
4116 ThreadState::Loading { .. } | ThreadState::Ready { .. } => true,
4117 ThreadState::Unauthenticated { .. } | ThreadState::LoadError(..) => false,
4118 };
4119
4120 v_flex()
4121 .on_action(cx.listener(Self::expand_message_editor))
4122 .on_action(cx.listener(|this, _: &ToggleProfileSelector, window, cx| {
4123 if let Some(profile_selector) = this.profile_selector.as_ref() {
4124 profile_selector.read(cx).menu_handle().toggle(window, cx);
4125 } else if let Some(mode_selector) = this.mode_selector() {
4126 mode_selector.read(cx).menu_handle().toggle(window, cx);
4127 }
4128 }))
4129 .on_action(cx.listener(|this, _: &CycleModeSelector, window, cx| {
4130 if let Some(mode_selector) = this.mode_selector() {
4131 mode_selector.update(cx, |mode_selector, cx| {
4132 mode_selector.cycle_mode(window, cx);
4133 });
4134 }
4135 }))
4136 .on_action(cx.listener(|this, _: &ToggleModelSelector, window, cx| {
4137 if let Some(model_selector) = this.model_selector.as_ref() {
4138 model_selector
4139 .update(cx, |model_selector, cx| model_selector.toggle(window, cx));
4140 }
4141 }))
4142 .p_2()
4143 .gap_2()
4144 .border_t_1()
4145 .border_color(cx.theme().colors().border)
4146 .bg(editor_bg_color)
4147 .when(self.editor_expanded, |this| {
4148 this.h(vh(0.8, window)).size_full().justify_between()
4149 })
4150 .child(
4151 v_flex()
4152 .relative()
4153 .size_full()
4154 .pt_1()
4155 .pr_2p5()
4156 .child(self.message_editor.clone())
4157 .child(
4158 h_flex()
4159 .absolute()
4160 .top_0()
4161 .right_0()
4162 .opacity(0.5)
4163 .hover(|this| this.opacity(1.0))
4164 .child(
4165 IconButton::new("toggle-height", expand_icon)
4166 .icon_size(IconSize::Small)
4167 .icon_color(Color::Muted)
4168 .tooltip({
4169 move |_window, cx| {
4170 Tooltip::for_action_in(
4171 expand_tooltip,
4172 &ExpandMessageEditor,
4173 &focus_handle,
4174 cx,
4175 )
4176 }
4177 })
4178 .on_click(cx.listener(|this, _, window, cx| {
4179 this.expand_message_editor(
4180 &ExpandMessageEditor,
4181 window,
4182 cx,
4183 );
4184 })),
4185 ),
4186 ),
4187 )
4188 .child(
4189 h_flex()
4190 .flex_none()
4191 .flex_wrap()
4192 .justify_between()
4193 .child(
4194 h_flex()
4195 .gap_0p5()
4196 .child(self.render_add_context_button(cx))
4197 .child(self.render_follow_toggle(cx))
4198 .children(self.render_burn_mode_toggle(cx)),
4199 )
4200 .child(
4201 h_flex()
4202 .gap_1()
4203 .children(self.render_token_usage(cx))
4204 .children(self.profile_selector.clone())
4205 .children(self.mode_selector().cloned())
4206 .children(self.model_selector.clone())
4207 .child(self.render_send_button(cx)),
4208 ),
4209 )
4210 .when(!enable_editor, |this| this.child(backdrop))
4211 .into_any()
4212 }
4213
4214 pub(crate) fn as_native_connection(
4215 &self,
4216 cx: &App,
4217 ) -> Option<Rc<agent::NativeAgentConnection>> {
4218 let acp_thread = self.thread()?.read(cx);
4219 acp_thread.connection().clone().downcast()
4220 }
4221
4222 pub(crate) fn as_native_thread(&self, cx: &App) -> Option<Entity<agent::Thread>> {
4223 let acp_thread = self.thread()?.read(cx);
4224 self.as_native_connection(cx)?
4225 .thread(acp_thread.session_id(), cx)
4226 }
4227
4228 fn is_using_zed_ai_models(&self, cx: &App) -> bool {
4229 self.as_native_thread(cx)
4230 .and_then(|thread| thread.read(cx).model())
4231 .is_some_and(|model| model.provider_id() == language_model::ZED_CLOUD_PROVIDER_ID)
4232 }
4233
4234 fn render_token_usage(&self, cx: &mut Context<Self>) -> Option<Div> {
4235 let thread = self.thread()?.read(cx);
4236 let usage = thread.token_usage()?;
4237 let is_generating = thread.status() != ThreadStatus::Idle;
4238
4239 let used = crate::text_thread_editor::humanize_token_count(usage.used_tokens);
4240 let max = crate::text_thread_editor::humanize_token_count(usage.max_tokens);
4241
4242 Some(
4243 h_flex()
4244 .flex_shrink_0()
4245 .gap_0p5()
4246 .mr_1p5()
4247 .child(
4248 Label::new(used)
4249 .size(LabelSize::Small)
4250 .color(Color::Muted)
4251 .map(|label| {
4252 if is_generating {
4253 label
4254 .with_animation(
4255 "used-tokens-label",
4256 Animation::new(Duration::from_secs(2))
4257 .repeat()
4258 .with_easing(pulsating_between(0.3, 0.8)),
4259 |label, delta| label.alpha(delta),
4260 )
4261 .into_any()
4262 } else {
4263 label.into_any_element()
4264 }
4265 }),
4266 )
4267 .child(
4268 Label::new("/")
4269 .size(LabelSize::Small)
4270 .color(Color::Custom(cx.theme().colors().text_muted.opacity(0.5))),
4271 )
4272 .child(Label::new(max).size(LabelSize::Small).color(Color::Muted)),
4273 )
4274 }
4275
4276 fn toggle_burn_mode(
4277 &mut self,
4278 _: &ToggleBurnMode,
4279 _window: &mut Window,
4280 cx: &mut Context<Self>,
4281 ) {
4282 let Some(thread) = self.as_native_thread(cx) else {
4283 return;
4284 };
4285
4286 thread.update(cx, |thread, cx| {
4287 let current_mode = thread.completion_mode();
4288 thread.set_completion_mode(
4289 match current_mode {
4290 CompletionMode::Burn => CompletionMode::Normal,
4291 CompletionMode::Normal => CompletionMode::Burn,
4292 },
4293 cx,
4294 );
4295 });
4296 }
4297
4298 fn keep_all(&mut self, _: &KeepAll, _window: &mut Window, cx: &mut Context<Self>) {
4299 let Some(thread) = self.thread() else {
4300 return;
4301 };
4302 let telemetry = ActionLogTelemetry::from(thread.read(cx));
4303 let action_log = thread.read(cx).action_log().clone();
4304 action_log.update(cx, |action_log, cx| {
4305 action_log.keep_all_edits(Some(telemetry), cx)
4306 });
4307 }
4308
4309 fn reject_all(&mut self, _: &RejectAll, _window: &mut Window, cx: &mut Context<Self>) {
4310 let Some(thread) = self.thread() else {
4311 return;
4312 };
4313 let telemetry = ActionLogTelemetry::from(thread.read(cx));
4314 let action_log = thread.read(cx).action_log().clone();
4315 action_log
4316 .update(cx, |action_log, cx| {
4317 action_log.reject_all_edits(Some(telemetry), cx)
4318 })
4319 .detach();
4320 }
4321
4322 fn allow_always(&mut self, _: &AllowAlways, window: &mut Window, cx: &mut Context<Self>) {
4323 self.authorize_pending_tool_call(acp::PermissionOptionKind::AllowAlways, window, cx);
4324 }
4325
4326 fn allow_once(&mut self, _: &AllowOnce, window: &mut Window, cx: &mut Context<Self>) {
4327 self.authorize_pending_tool_call(acp::PermissionOptionKind::AllowOnce, window, cx);
4328 }
4329
4330 fn reject_once(&mut self, _: &RejectOnce, window: &mut Window, cx: &mut Context<Self>) {
4331 self.authorize_pending_tool_call(acp::PermissionOptionKind::RejectOnce, window, cx);
4332 }
4333
4334 fn authorize_pending_tool_call(
4335 &mut self,
4336 kind: acp::PermissionOptionKind,
4337 window: &mut Window,
4338 cx: &mut Context<Self>,
4339 ) -> Option<()> {
4340 let thread = self.thread()?.read(cx);
4341 let tool_call = thread.first_tool_awaiting_confirmation()?;
4342 let ToolCallStatus::WaitingForConfirmation { options, .. } = &tool_call.status else {
4343 return None;
4344 };
4345 let option = options.iter().find(|o| o.kind == kind)?;
4346
4347 self.authorize_tool_call(
4348 tool_call.id.clone(),
4349 option.id.clone(),
4350 option.kind,
4351 window,
4352 cx,
4353 );
4354
4355 Some(())
4356 }
4357
4358 fn render_burn_mode_toggle(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
4359 let thread = self.as_native_thread(cx)?.read(cx);
4360
4361 if thread
4362 .model()
4363 .is_none_or(|model| !model.supports_burn_mode())
4364 {
4365 return None;
4366 }
4367
4368 let active_completion_mode = thread.completion_mode();
4369 let burn_mode_enabled = active_completion_mode == CompletionMode::Burn;
4370 let icon = if burn_mode_enabled {
4371 IconName::ZedBurnModeOn
4372 } else {
4373 IconName::ZedBurnMode
4374 };
4375
4376 Some(
4377 IconButton::new("burn-mode", icon)
4378 .icon_size(IconSize::Small)
4379 .icon_color(Color::Muted)
4380 .toggle_state(burn_mode_enabled)
4381 .selected_icon_color(Color::Error)
4382 .on_click(cx.listener(|this, _event, window, cx| {
4383 this.toggle_burn_mode(&ToggleBurnMode, window, cx);
4384 }))
4385 .tooltip(move |_window, cx| {
4386 cx.new(|_| BurnModeTooltip::new().selected(burn_mode_enabled))
4387 .into()
4388 })
4389 .into_any_element(),
4390 )
4391 }
4392
4393 fn render_send_button(&self, cx: &mut Context<Self>) -> AnyElement {
4394 let is_editor_empty = self.message_editor.read(cx).is_empty(cx);
4395 let is_generating = self
4396 .thread()
4397 .is_some_and(|thread| thread.read(cx).status() != ThreadStatus::Idle);
4398
4399 if self.is_loading_contents {
4400 div()
4401 .id("loading-message-content")
4402 .px_1()
4403 .tooltip(Tooltip::text("Loading Added Context…"))
4404 .child(loading_contents_spinner(IconSize::default()))
4405 .into_any_element()
4406 } else if is_generating && is_editor_empty {
4407 IconButton::new("stop-generation", IconName::Stop)
4408 .icon_color(Color::Error)
4409 .style(ButtonStyle::Tinted(ui::TintColor::Error))
4410 .tooltip(move |_window, cx| {
4411 Tooltip::for_action("Stop Generation", &editor::actions::Cancel, cx)
4412 })
4413 .on_click(cx.listener(|this, _event, _, cx| this.cancel_generation(cx)))
4414 .into_any_element()
4415 } else {
4416 let send_btn_tooltip = if is_editor_empty && !is_generating {
4417 "Type to Send"
4418 } else if is_generating {
4419 "Stop and Send Message"
4420 } else {
4421 "Send"
4422 };
4423
4424 IconButton::new("send-message", IconName::Send)
4425 .style(ButtonStyle::Filled)
4426 .map(|this| {
4427 if is_editor_empty && !is_generating {
4428 this.disabled(true).icon_color(Color::Muted)
4429 } else {
4430 this.icon_color(Color::Accent)
4431 }
4432 })
4433 .tooltip(move |_window, cx| Tooltip::for_action(send_btn_tooltip, &Chat, cx))
4434 .on_click(cx.listener(|this, _, window, cx| {
4435 this.send(window, cx);
4436 }))
4437 .into_any_element()
4438 }
4439 }
4440
4441 fn is_following(&self, cx: &App) -> bool {
4442 match self.thread().map(|thread| thread.read(cx).status()) {
4443 Some(ThreadStatus::Generating) => self
4444 .workspace
4445 .read_with(cx, |workspace, _| {
4446 workspace.is_being_followed(CollaboratorId::Agent)
4447 })
4448 .unwrap_or(false),
4449 _ => self.should_be_following,
4450 }
4451 }
4452
4453 fn toggle_following(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4454 let following = self.is_following(cx);
4455
4456 self.should_be_following = !following;
4457 if self.thread().map(|thread| thread.read(cx).status()) == Some(ThreadStatus::Generating) {
4458 self.workspace
4459 .update(cx, |workspace, cx| {
4460 if following {
4461 workspace.unfollow(CollaboratorId::Agent, window, cx);
4462 } else {
4463 workspace.follow(CollaboratorId::Agent, window, cx);
4464 }
4465 })
4466 .ok();
4467 }
4468
4469 telemetry::event!("Follow Agent Selected", following = !following);
4470 }
4471
4472 fn render_follow_toggle(&self, cx: &mut Context<Self>) -> impl IntoElement {
4473 let following = self.is_following(cx);
4474
4475 let tooltip_label = if following {
4476 if self.agent.name() == "Zed Agent" {
4477 format!("Stop Following the {}", self.agent.name())
4478 } else {
4479 format!("Stop Following {}", self.agent.name())
4480 }
4481 } else {
4482 if self.agent.name() == "Zed Agent" {
4483 format!("Follow the {}", self.agent.name())
4484 } else {
4485 format!("Follow {}", self.agent.name())
4486 }
4487 };
4488
4489 IconButton::new("follow-agent", IconName::Crosshair)
4490 .icon_size(IconSize::Small)
4491 .icon_color(Color::Muted)
4492 .toggle_state(following)
4493 .selected_icon_color(Some(Color::Custom(cx.theme().players().agent().cursor)))
4494 .tooltip(move |_window, cx| {
4495 if following {
4496 Tooltip::for_action(tooltip_label.clone(), &Follow, cx)
4497 } else {
4498 Tooltip::with_meta(
4499 tooltip_label.clone(),
4500 Some(&Follow),
4501 "Track the agent's location as it reads and edits files.",
4502 cx,
4503 )
4504 }
4505 })
4506 .on_click(cx.listener(move |this, _, window, cx| {
4507 this.toggle_following(window, cx);
4508 }))
4509 }
4510
4511 fn render_add_context_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
4512 let message_editor = self.message_editor.clone();
4513 let menu_visible = message_editor.read(cx).is_completions_menu_visible(cx);
4514
4515 IconButton::new("add-context", IconName::AtSign)
4516 .icon_size(IconSize::Small)
4517 .icon_color(Color::Muted)
4518 .when(!menu_visible, |this| {
4519 this.tooltip(move |_window, cx| {
4520 Tooltip::with_meta("Add Context", None, "Or type @ to include context", cx)
4521 })
4522 })
4523 .on_click(cx.listener(move |_this, _, window, cx| {
4524 let message_editor_clone = message_editor.clone();
4525
4526 window.defer(cx, move |window, cx| {
4527 message_editor_clone.update(cx, |message_editor, cx| {
4528 message_editor.trigger_completion_menu(window, cx);
4529 });
4530 });
4531 }))
4532 }
4533
4534 fn render_markdown(&self, markdown: Entity<Markdown>, style: MarkdownStyle) -> MarkdownElement {
4535 let workspace = self.workspace.clone();
4536 MarkdownElement::new(markdown, style).on_url_click(move |text, window, cx| {
4537 Self::open_link(text, &workspace, window, cx);
4538 })
4539 }
4540
4541 fn open_link(
4542 url: SharedString,
4543 workspace: &WeakEntity<Workspace>,
4544 window: &mut Window,
4545 cx: &mut App,
4546 ) {
4547 let Some(workspace) = workspace.upgrade() else {
4548 cx.open_url(&url);
4549 return;
4550 };
4551
4552 if let Some(mention) = MentionUri::parse(&url, workspace.read(cx).path_style(cx)).log_err()
4553 {
4554 workspace.update(cx, |workspace, cx| match mention {
4555 MentionUri::File { abs_path } => {
4556 let project = workspace.project();
4557 let Some(path) =
4558 project.update(cx, |project, cx| project.find_project_path(abs_path, cx))
4559 else {
4560 return;
4561 };
4562
4563 workspace
4564 .open_path(path, None, true, window, cx)
4565 .detach_and_log_err(cx);
4566 }
4567 MentionUri::PastedImage => {}
4568 MentionUri::Directory { abs_path } => {
4569 let project = workspace.project();
4570 let Some(entry_id) = project.update(cx, |project, cx| {
4571 let path = project.find_project_path(abs_path, cx)?;
4572 project.entry_for_path(&path, cx).map(|entry| entry.id)
4573 }) else {
4574 return;
4575 };
4576
4577 project.update(cx, |_, cx| {
4578 cx.emit(project::Event::RevealInProjectPanel(entry_id));
4579 });
4580 }
4581 MentionUri::Symbol {
4582 abs_path: path,
4583 line_range,
4584 ..
4585 }
4586 | MentionUri::Selection {
4587 abs_path: Some(path),
4588 line_range,
4589 } => {
4590 let project = workspace.project();
4591 let Some(path) =
4592 project.update(cx, |project, cx| project.find_project_path(path, cx))
4593 else {
4594 return;
4595 };
4596
4597 let item = workspace.open_path(path, None, true, window, cx);
4598 window
4599 .spawn(cx, async move |cx| {
4600 let Some(editor) = item.await?.downcast::<Editor>() else {
4601 return Ok(());
4602 };
4603 let range = Point::new(*line_range.start(), 0)
4604 ..Point::new(*line_range.start(), 0);
4605 editor
4606 .update_in(cx, |editor, window, cx| {
4607 editor.change_selections(
4608 SelectionEffects::scroll(Autoscroll::center()),
4609 window,
4610 cx,
4611 |s| s.select_ranges(vec![range]),
4612 );
4613 })
4614 .ok();
4615 anyhow::Ok(())
4616 })
4617 .detach_and_log_err(cx);
4618 }
4619 MentionUri::Selection { abs_path: None, .. } => {}
4620 MentionUri::Thread { id, name } => {
4621 if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
4622 panel.update(cx, |panel, cx| {
4623 panel.load_agent_thread(
4624 DbThreadMetadata {
4625 id,
4626 title: name.into(),
4627 updated_at: Default::default(),
4628 },
4629 window,
4630 cx,
4631 )
4632 });
4633 }
4634 }
4635 MentionUri::TextThread { path, .. } => {
4636 if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
4637 panel.update(cx, |panel, cx| {
4638 panel
4639 .open_saved_text_thread(path.as_path().into(), window, cx)
4640 .detach_and_log_err(cx);
4641 });
4642 }
4643 }
4644 MentionUri::Rule { id, .. } => {
4645 let PromptId::User { uuid } = id else {
4646 return;
4647 };
4648 window.dispatch_action(
4649 Box::new(OpenRulesLibrary {
4650 prompt_to_select: Some(uuid.0),
4651 }),
4652 cx,
4653 )
4654 }
4655 MentionUri::Fetch { url } => {
4656 cx.open_url(url.as_str());
4657 }
4658 })
4659 } else {
4660 cx.open_url(&url);
4661 }
4662 }
4663
4664 fn open_tool_call_location(
4665 &self,
4666 entry_ix: usize,
4667 location_ix: usize,
4668 window: &mut Window,
4669 cx: &mut Context<Self>,
4670 ) -> Option<()> {
4671 let (tool_call_location, agent_location) = self
4672 .thread()?
4673 .read(cx)
4674 .entries()
4675 .get(entry_ix)?
4676 .location(location_ix)?;
4677
4678 let project_path = self
4679 .project
4680 .read(cx)
4681 .find_project_path(&tool_call_location.path, cx)?;
4682
4683 let open_task = self
4684 .workspace
4685 .update(cx, |workspace, cx| {
4686 workspace.open_path(project_path, None, true, window, cx)
4687 })
4688 .log_err()?;
4689 window
4690 .spawn(cx, async move |cx| {
4691 let item = open_task.await?;
4692
4693 let Some(active_editor) = item.downcast::<Editor>() else {
4694 return anyhow::Ok(());
4695 };
4696
4697 active_editor.update_in(cx, |editor, window, cx| {
4698 let multibuffer = editor.buffer().read(cx);
4699 let buffer = multibuffer.as_singleton();
4700 if agent_location.buffer.upgrade() == buffer {
4701 let excerpt_id = multibuffer.excerpt_ids().first().cloned();
4702 let anchor = editor::Anchor::in_buffer(
4703 excerpt_id.unwrap(),
4704 buffer.unwrap().read(cx).remote_id(),
4705 agent_location.position,
4706 );
4707 editor.change_selections(Default::default(), window, cx, |selections| {
4708 selections.select_anchor_ranges([anchor..anchor]);
4709 })
4710 } else {
4711 let row = tool_call_location.line.unwrap_or_default();
4712 editor.change_selections(Default::default(), window, cx, |selections| {
4713 selections.select_ranges([Point::new(row, 0)..Point::new(row, 0)]);
4714 })
4715 }
4716 })?;
4717
4718 anyhow::Ok(())
4719 })
4720 .detach_and_log_err(cx);
4721
4722 None
4723 }
4724
4725 pub fn open_thread_as_markdown(
4726 &self,
4727 workspace: Entity<Workspace>,
4728 window: &mut Window,
4729 cx: &mut App,
4730 ) -> Task<Result<()>> {
4731 let markdown_language_task = workspace
4732 .read(cx)
4733 .app_state()
4734 .languages
4735 .language_for_name("Markdown");
4736
4737 let (thread_title, markdown) = if let Some(thread) = self.thread() {
4738 let thread = thread.read(cx);
4739 (thread.title().to_string(), thread.to_markdown(cx))
4740 } else {
4741 return Task::ready(Ok(()));
4742 };
4743
4744 let project = workspace.read(cx).project().clone();
4745 window.spawn(cx, async move |cx| {
4746 let markdown_language = markdown_language_task.await?;
4747
4748 let buffer = project
4749 .update(cx, |project, cx| project.create_buffer(false, cx))?
4750 .await?;
4751
4752 buffer.update(cx, |buffer, cx| {
4753 buffer.set_text(markdown, cx);
4754 buffer.set_language(Some(markdown_language), cx);
4755 buffer.set_capability(language::Capability::ReadOnly, cx);
4756 })?;
4757
4758 workspace.update_in(cx, |workspace, window, cx| {
4759 let buffer = cx
4760 .new(|cx| MultiBuffer::singleton(buffer, cx).with_title(thread_title.clone()));
4761
4762 workspace.add_item_to_active_pane(
4763 Box::new(cx.new(|cx| {
4764 let mut editor =
4765 Editor::for_multibuffer(buffer, Some(project.clone()), window, cx);
4766 editor.set_breadcrumb_header(thread_title);
4767 editor
4768 })),
4769 None,
4770 true,
4771 window,
4772 cx,
4773 );
4774 })?;
4775 anyhow::Ok(())
4776 })
4777 }
4778
4779 fn scroll_to_top(&mut self, cx: &mut Context<Self>) {
4780 self.list_state.scroll_to(ListOffset::default());
4781 cx.notify();
4782 }
4783
4784 pub fn scroll_to_bottom(&mut self, cx: &mut Context<Self>) {
4785 if let Some(thread) = self.thread() {
4786 let entry_count = thread.read(cx).entries().len();
4787 self.list_state.reset(entry_count);
4788 cx.notify();
4789 }
4790 }
4791
4792 fn notify_with_sound(
4793 &mut self,
4794 caption: impl Into<SharedString>,
4795 icon: IconName,
4796 window: &mut Window,
4797 cx: &mut Context<Self>,
4798 ) {
4799 self.play_notification_sound(window, cx);
4800 self.show_notification(caption, icon, window, cx);
4801 }
4802
4803 fn play_notification_sound(&self, window: &Window, cx: &mut App) {
4804 let settings = AgentSettings::get_global(cx);
4805 if settings.play_sound_when_agent_done && !window.is_window_active() {
4806 Audio::play_sound(Sound::AgentDone, cx);
4807 }
4808 }
4809
4810 fn show_notification(
4811 &mut self,
4812 caption: impl Into<SharedString>,
4813 icon: IconName,
4814 window: &mut Window,
4815 cx: &mut Context<Self>,
4816 ) {
4817 if !self.notifications.is_empty() {
4818 return;
4819 }
4820
4821 let settings = AgentSettings::get_global(cx);
4822
4823 let window_is_inactive = !window.is_window_active();
4824 let panel_is_hidden = self
4825 .workspace
4826 .upgrade()
4827 .map(|workspace| AgentPanel::is_hidden(&workspace, cx))
4828 .unwrap_or(true);
4829
4830 let should_notify = window_is_inactive || panel_is_hidden;
4831
4832 if !should_notify {
4833 return;
4834 }
4835
4836 // TODO: Change this once we have title summarization for external agents.
4837 let title = self.agent.name();
4838
4839 match settings.notify_when_agent_waiting {
4840 NotifyWhenAgentWaiting::PrimaryScreen => {
4841 if let Some(primary) = cx.primary_display() {
4842 self.pop_up(icon, caption.into(), title, window, primary, cx);
4843 }
4844 }
4845 NotifyWhenAgentWaiting::AllScreens => {
4846 let caption = caption.into();
4847 for screen in cx.displays() {
4848 self.pop_up(icon, caption.clone(), title.clone(), window, screen, cx);
4849 }
4850 }
4851 NotifyWhenAgentWaiting::Never => {
4852 // Don't show anything
4853 }
4854 }
4855 }
4856
4857 fn pop_up(
4858 &mut self,
4859 icon: IconName,
4860 caption: SharedString,
4861 title: SharedString,
4862 window: &mut Window,
4863 screen: Rc<dyn PlatformDisplay>,
4864 cx: &mut Context<Self>,
4865 ) {
4866 let options = AgentNotification::window_options(screen, cx);
4867
4868 let project_name = self.workspace.upgrade().and_then(|workspace| {
4869 workspace
4870 .read(cx)
4871 .project()
4872 .read(cx)
4873 .visible_worktrees(cx)
4874 .next()
4875 .map(|worktree| worktree.read(cx).root_name_str().to_string())
4876 });
4877
4878 if let Some(screen_window) = cx
4879 .open_window(options, |_, cx| {
4880 cx.new(|_| {
4881 AgentNotification::new(title.clone(), caption.clone(), icon, project_name)
4882 })
4883 })
4884 .log_err()
4885 && let Some(pop_up) = screen_window.entity(cx).log_err()
4886 {
4887 self.notification_subscriptions
4888 .entry(screen_window)
4889 .or_insert_with(Vec::new)
4890 .push(cx.subscribe_in(&pop_up, window, {
4891 |this, _, event, window, cx| match event {
4892 AgentNotificationEvent::Accepted => {
4893 let handle = window.window_handle();
4894 cx.activate(true);
4895
4896 let workspace_handle = this.workspace.clone();
4897
4898 // If there are multiple Zed windows, activate the correct one.
4899 cx.defer(move |cx| {
4900 handle
4901 .update(cx, |_view, window, _cx| {
4902 window.activate_window();
4903
4904 if let Some(workspace) = workspace_handle.upgrade() {
4905 workspace.update(_cx, |workspace, cx| {
4906 workspace.focus_panel::<AgentPanel>(window, cx);
4907 });
4908 }
4909 })
4910 .log_err();
4911 });
4912
4913 this.dismiss_notifications(cx);
4914 }
4915 AgentNotificationEvent::Dismissed => {
4916 this.dismiss_notifications(cx);
4917 }
4918 }
4919 }));
4920
4921 self.notifications.push(screen_window);
4922
4923 // If the user manually refocuses the original window, dismiss the popup.
4924 self.notification_subscriptions
4925 .entry(screen_window)
4926 .or_insert_with(Vec::new)
4927 .push({
4928 let pop_up_weak = pop_up.downgrade();
4929
4930 cx.observe_window_activation(window, move |_, window, cx| {
4931 if window.is_window_active()
4932 && let Some(pop_up) = pop_up_weak.upgrade()
4933 {
4934 pop_up.update(cx, |_, cx| {
4935 cx.emit(AgentNotificationEvent::Dismissed);
4936 });
4937 }
4938 })
4939 });
4940 }
4941 }
4942
4943 fn dismiss_notifications(&mut self, cx: &mut Context<Self>) {
4944 for window in self.notifications.drain(..) {
4945 window
4946 .update(cx, |_, window, _| {
4947 window.remove_window();
4948 })
4949 .ok();
4950
4951 self.notification_subscriptions.remove(&window);
4952 }
4953 }
4954
4955 fn render_generating(&self, confirmation: bool) -> impl IntoElement {
4956 h_flex()
4957 .id("generating-spinner")
4958 .py_2()
4959 .px(rems_from_px(22.))
4960 .map(|this| {
4961 if confirmation {
4962 this.gap_2()
4963 .child(
4964 h_flex()
4965 .w_2()
4966 .child(SpinnerLabel::sand().size(LabelSize::Small)),
4967 )
4968 .child(
4969 LoadingLabel::new("Waiting Confirmation")
4970 .size(LabelSize::Small)
4971 .color(Color::Muted),
4972 )
4973 } else {
4974 this.child(SpinnerLabel::new().size(LabelSize::Small))
4975 }
4976 })
4977 .into_any_element()
4978 }
4979
4980 fn render_thread_controls(
4981 &self,
4982 thread: &Entity<AcpThread>,
4983 cx: &Context<Self>,
4984 ) -> impl IntoElement {
4985 let is_generating = matches!(thread.read(cx).status(), ThreadStatus::Generating);
4986 if is_generating {
4987 return self.render_generating(false).into_any_element();
4988 }
4989
4990 let open_as_markdown = IconButton::new("open-as-markdown", IconName::FileMarkdown)
4991 .shape(ui::IconButtonShape::Square)
4992 .icon_size(IconSize::Small)
4993 .icon_color(Color::Ignored)
4994 .tooltip(Tooltip::text("Open Thread as Markdown"))
4995 .on_click(cx.listener(move |this, _, window, cx| {
4996 if let Some(workspace) = this.workspace.upgrade() {
4997 this.open_thread_as_markdown(workspace, window, cx)
4998 .detach_and_log_err(cx);
4999 }
5000 }));
5001
5002 let scroll_to_top = IconButton::new("scroll_to_top", IconName::ArrowUp)
5003 .shape(ui::IconButtonShape::Square)
5004 .icon_size(IconSize::Small)
5005 .icon_color(Color::Ignored)
5006 .tooltip(Tooltip::text("Scroll To Top"))
5007 .on_click(cx.listener(move |this, _, _, cx| {
5008 this.scroll_to_top(cx);
5009 }));
5010
5011 let mut container = h_flex()
5012 .id("thread-controls-container")
5013 .group("thread-controls-container")
5014 .w_full()
5015 .py_2()
5016 .px_5()
5017 .gap_px()
5018 .opacity(0.6)
5019 .hover(|style| style.opacity(1.))
5020 .flex_wrap()
5021 .justify_end();
5022
5023 if AgentSettings::get_global(cx).enable_feedback
5024 && self
5025 .thread()
5026 .is_some_and(|thread| thread.read(cx).connection().telemetry().is_some())
5027 {
5028 let feedback = self.thread_feedback.feedback;
5029
5030 container = container
5031 .child(
5032 div().visible_on_hover("thread-controls-container").child(
5033 Label::new(match feedback {
5034 Some(ThreadFeedback::Positive) => "Thanks for your feedback!",
5035 Some(ThreadFeedback::Negative) => {
5036 "We appreciate your feedback and will use it to improve."
5037 }
5038 None => {
5039 "Rating the thread sends all of your current conversation to the Zed team."
5040 }
5041 })
5042 .color(Color::Muted)
5043 .size(LabelSize::XSmall)
5044 .truncate(),
5045 ),
5046 )
5047 .child(
5048 IconButton::new("feedback-thumbs-up", IconName::ThumbsUp)
5049 .shape(ui::IconButtonShape::Square)
5050 .icon_size(IconSize::Small)
5051 .icon_color(match feedback {
5052 Some(ThreadFeedback::Positive) => Color::Accent,
5053 _ => Color::Ignored,
5054 })
5055 .tooltip(Tooltip::text("Helpful Response"))
5056 .on_click(cx.listener(move |this, _, window, cx| {
5057 this.handle_feedback_click(ThreadFeedback::Positive, window, cx);
5058 })),
5059 )
5060 .child(
5061 IconButton::new("feedback-thumbs-down", IconName::ThumbsDown)
5062 .shape(ui::IconButtonShape::Square)
5063 .icon_size(IconSize::Small)
5064 .icon_color(match feedback {
5065 Some(ThreadFeedback::Negative) => Color::Accent,
5066 _ => Color::Ignored,
5067 })
5068 .tooltip(Tooltip::text("Not Helpful"))
5069 .on_click(cx.listener(move |this, _, window, cx| {
5070 this.handle_feedback_click(ThreadFeedback::Negative, window, cx);
5071 })),
5072 );
5073 }
5074
5075 container
5076 .child(open_as_markdown)
5077 .child(scroll_to_top)
5078 .into_any_element()
5079 }
5080
5081 fn render_feedback_feedback_editor(editor: Entity<Editor>, cx: &Context<Self>) -> Div {
5082 h_flex()
5083 .key_context("AgentFeedbackMessageEditor")
5084 .on_action(cx.listener(move |this, _: &menu::Cancel, _, cx| {
5085 this.thread_feedback.dismiss_comments();
5086 cx.notify();
5087 }))
5088 .on_action(cx.listener(move |this, _: &menu::Confirm, _window, cx| {
5089 this.submit_feedback_message(cx);
5090 }))
5091 .p_2()
5092 .mb_2()
5093 .mx_5()
5094 .gap_1()
5095 .rounded_md()
5096 .border_1()
5097 .border_color(cx.theme().colors().border)
5098 .bg(cx.theme().colors().editor_background)
5099 .child(div().w_full().child(editor))
5100 .child(
5101 h_flex()
5102 .child(
5103 IconButton::new("dismiss-feedback-message", IconName::Close)
5104 .icon_color(Color::Error)
5105 .icon_size(IconSize::XSmall)
5106 .shape(ui::IconButtonShape::Square)
5107 .on_click(cx.listener(move |this, _, _window, cx| {
5108 this.thread_feedback.dismiss_comments();
5109 cx.notify();
5110 })),
5111 )
5112 .child(
5113 IconButton::new("submit-feedback-message", IconName::Return)
5114 .icon_size(IconSize::XSmall)
5115 .shape(ui::IconButtonShape::Square)
5116 .on_click(cx.listener(move |this, _, _window, cx| {
5117 this.submit_feedback_message(cx);
5118 })),
5119 ),
5120 )
5121 }
5122
5123 fn handle_feedback_click(
5124 &mut self,
5125 feedback: ThreadFeedback,
5126 window: &mut Window,
5127 cx: &mut Context<Self>,
5128 ) {
5129 let Some(thread) = self.thread().cloned() else {
5130 return;
5131 };
5132
5133 self.thread_feedback.submit(thread, feedback, window, cx);
5134 cx.notify();
5135 }
5136
5137 fn submit_feedback_message(&mut self, cx: &mut Context<Self>) {
5138 let Some(thread) = self.thread().cloned() else {
5139 return;
5140 };
5141
5142 self.thread_feedback.submit_comments(thread, cx);
5143 cx.notify();
5144 }
5145
5146 fn render_token_limit_callout(
5147 &self,
5148 line_height: Pixels,
5149 cx: &mut Context<Self>,
5150 ) -> Option<Callout> {
5151 let token_usage = self.thread()?.read(cx).token_usage()?;
5152 let ratio = token_usage.ratio();
5153
5154 let (severity, title) = match ratio {
5155 acp_thread::TokenUsageRatio::Normal => return None,
5156 acp_thread::TokenUsageRatio::Warning => {
5157 (Severity::Warning, "Thread reaching the token limit soon")
5158 }
5159 acp_thread::TokenUsageRatio::Exceeded => {
5160 (Severity::Error, "Thread reached the token limit")
5161 }
5162 };
5163
5164 let burn_mode_available = self.as_native_thread(cx).is_some_and(|thread| {
5165 thread.read(cx).completion_mode() == CompletionMode::Normal
5166 && thread
5167 .read(cx)
5168 .model()
5169 .is_some_and(|model| model.supports_burn_mode())
5170 });
5171
5172 let description = if burn_mode_available {
5173 "To continue, start a new thread from a summary or turn Burn Mode on."
5174 } else {
5175 "To continue, start a new thread from a summary."
5176 };
5177
5178 Some(
5179 Callout::new()
5180 .severity(severity)
5181 .line_height(line_height)
5182 .title(title)
5183 .description(description)
5184 .actions_slot(
5185 h_flex()
5186 .gap_0p5()
5187 .child(
5188 Button::new("start-new-thread", "Start New Thread")
5189 .label_size(LabelSize::Small)
5190 .on_click(cx.listener(|this, _, window, cx| {
5191 let Some(thread) = this.thread() else {
5192 return;
5193 };
5194 let session_id = thread.read(cx).session_id().clone();
5195 window.dispatch_action(
5196 crate::NewNativeAgentThreadFromSummary {
5197 from_session_id: session_id,
5198 }
5199 .boxed_clone(),
5200 cx,
5201 );
5202 })),
5203 )
5204 .when(burn_mode_available, |this| {
5205 this.child(
5206 IconButton::new("burn-mode-callout", IconName::ZedBurnMode)
5207 .icon_size(IconSize::XSmall)
5208 .on_click(cx.listener(|this, _event, window, cx| {
5209 this.toggle_burn_mode(&ToggleBurnMode, window, cx);
5210 })),
5211 )
5212 }),
5213 ),
5214 )
5215 }
5216
5217 fn render_usage_callout(&self, line_height: Pixels, cx: &mut Context<Self>) -> Option<Div> {
5218 if !self.is_using_zed_ai_models(cx) {
5219 return None;
5220 }
5221
5222 let user_store = self.project.read(cx).user_store().read(cx);
5223 if user_store.is_usage_based_billing_enabled() {
5224 return None;
5225 }
5226
5227 let plan = user_store
5228 .plan()
5229 .unwrap_or(cloud_llm_client::Plan::V1(PlanV1::ZedFree));
5230
5231 let usage = user_store.model_request_usage()?;
5232
5233 Some(
5234 div()
5235 .child(UsageCallout::new(plan, usage))
5236 .line_height(line_height),
5237 )
5238 }
5239
5240 fn agent_ui_font_size_changed(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
5241 self.entry_view_state.update(cx, |entry_view_state, cx| {
5242 entry_view_state.agent_ui_font_size_changed(cx);
5243 });
5244 }
5245
5246 pub(crate) fn insert_dragged_files(
5247 &self,
5248 paths: Vec<project::ProjectPath>,
5249 added_worktrees: Vec<Entity<project::Worktree>>,
5250 window: &mut Window,
5251 cx: &mut Context<Self>,
5252 ) {
5253 self.message_editor.update(cx, |message_editor, cx| {
5254 message_editor.insert_dragged_files(paths, added_worktrees, window, cx);
5255 })
5256 }
5257
5258 /// Inserts the selected text into the message editor or the message being
5259 /// edited, if any.
5260 pub(crate) fn insert_selections(&self, window: &mut Window, cx: &mut Context<Self>) {
5261 self.active_editor(cx).update(cx, |editor, cx| {
5262 editor.insert_selections(window, cx);
5263 });
5264 }
5265
5266 fn render_thread_retry_status_callout(
5267 &self,
5268 _window: &mut Window,
5269 _cx: &mut Context<Self>,
5270 ) -> Option<Callout> {
5271 let state = self.thread_retry_status.as_ref()?;
5272
5273 let next_attempt_in = state
5274 .duration
5275 .saturating_sub(Instant::now().saturating_duration_since(state.started_at));
5276 if next_attempt_in.is_zero() {
5277 return None;
5278 }
5279
5280 let next_attempt_in_secs = next_attempt_in.as_secs() + 1;
5281
5282 let retry_message = if state.max_attempts == 1 {
5283 if next_attempt_in_secs == 1 {
5284 "Retrying. Next attempt in 1 second.".to_string()
5285 } else {
5286 format!("Retrying. Next attempt in {next_attempt_in_secs} seconds.")
5287 }
5288 } else if next_attempt_in_secs == 1 {
5289 format!(
5290 "Retrying. Next attempt in 1 second (Attempt {} of {}).",
5291 state.attempt, state.max_attempts,
5292 )
5293 } else {
5294 format!(
5295 "Retrying. Next attempt in {next_attempt_in_secs} seconds (Attempt {} of {}).",
5296 state.attempt, state.max_attempts,
5297 )
5298 };
5299
5300 Some(
5301 Callout::new()
5302 .severity(Severity::Warning)
5303 .title(state.last_error.clone())
5304 .description(retry_message),
5305 )
5306 }
5307
5308 fn render_codex_windows_warning(&self, cx: &mut Context<Self>) -> Option<Callout> {
5309 if self.show_codex_windows_warning {
5310 Some(
5311 Callout::new()
5312 .icon(IconName::Warning)
5313 .severity(Severity::Warning)
5314 .title("Codex on Windows")
5315 .description(
5316 "For best performance, run Codex in Windows Subsystem for Linux (WSL2)",
5317 )
5318 .actions_slot(
5319 Button::new("open-wsl-modal", "Open in WSL")
5320 .icon_size(IconSize::Small)
5321 .icon_color(Color::Muted)
5322 .on_click(cx.listener({
5323 move |_, _, _window, cx| {
5324 #[cfg(windows)]
5325 _window.dispatch_action(
5326 zed_actions::wsl_actions::OpenWsl::default().boxed_clone(),
5327 cx,
5328 );
5329 cx.notify();
5330 }
5331 })),
5332 )
5333 .dismiss_action(
5334 IconButton::new("dismiss", IconName::Close)
5335 .icon_size(IconSize::Small)
5336 .icon_color(Color::Muted)
5337 .tooltip(Tooltip::text("Dismiss Warning"))
5338 .on_click(cx.listener({
5339 move |this, _, _, cx| {
5340 this.show_codex_windows_warning = false;
5341 cx.notify();
5342 }
5343 })),
5344 ),
5345 )
5346 } else {
5347 None
5348 }
5349 }
5350
5351 fn render_thread_error(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<Div> {
5352 let content = match self.thread_error.as_ref()? {
5353 ThreadError::Other(error) => self.render_any_thread_error(error.clone(), window, cx),
5354 ThreadError::Refusal => self.render_refusal_error(cx),
5355 ThreadError::AuthenticationRequired(error) => {
5356 self.render_authentication_required_error(error.clone(), cx)
5357 }
5358 ThreadError::PaymentRequired => self.render_payment_required_error(cx),
5359 ThreadError::ModelRequestLimitReached(plan) => {
5360 self.render_model_request_limit_reached_error(*plan, cx)
5361 }
5362 ThreadError::ToolUseLimitReached => self.render_tool_use_limit_reached_error(cx)?,
5363 };
5364
5365 Some(div().child(content))
5366 }
5367
5368 fn render_new_version_callout(&self, version: &SharedString, cx: &mut Context<Self>) -> Div {
5369 v_flex().w_full().justify_end().child(
5370 h_flex()
5371 .p_2()
5372 .pr_3()
5373 .w_full()
5374 .gap_1p5()
5375 .border_t_1()
5376 .border_color(cx.theme().colors().border)
5377 .bg(cx.theme().colors().element_background)
5378 .child(
5379 h_flex()
5380 .flex_1()
5381 .gap_1p5()
5382 .child(
5383 Icon::new(IconName::Download)
5384 .color(Color::Accent)
5385 .size(IconSize::Small),
5386 )
5387 .child(Label::new("New version available").size(LabelSize::Small)),
5388 )
5389 .child(
5390 Button::new("update-button", format!("Update to v{}", version))
5391 .label_size(LabelSize::Small)
5392 .style(ButtonStyle::Tinted(TintColor::Accent))
5393 .on_click(cx.listener(|this, _, window, cx| {
5394 this.reset(window, cx);
5395 })),
5396 ),
5397 )
5398 }
5399
5400 fn current_model_id(&self, cx: &App) -> Option<String> {
5401 self.model_selector
5402 .as_ref()
5403 .and_then(|selector| selector.read(cx).active_model(cx).map(|m| m.id.to_string()))
5404 }
5405
5406 fn current_model_name(&self, cx: &App) -> SharedString {
5407 // For native agent (Zed Agent), use the specific model name (e.g., "Claude 3.5 Sonnet")
5408 // For ACP agents, use the agent name (e.g., "Claude Code", "Gemini CLI")
5409 // This provides better clarity about what refused the request
5410 if self.as_native_connection(cx).is_some() {
5411 self.model_selector
5412 .as_ref()
5413 .and_then(|selector| selector.read(cx).active_model(cx))
5414 .map(|model| model.name.clone())
5415 .unwrap_or_else(|| SharedString::from("The model"))
5416 } else {
5417 // ACP agent - use the agent name (e.g., "Claude Code", "Gemini CLI")
5418 self.agent.name()
5419 }
5420 }
5421
5422 fn render_refusal_error(&self, cx: &mut Context<'_, Self>) -> Callout {
5423 let model_or_agent_name = self.current_model_name(cx);
5424 let refusal_message = format!(
5425 "{} refused to respond to this prompt. This can happen when a model believes the prompt violates its content policy or safety guidelines, so rephrasing it can sometimes address the issue.",
5426 model_or_agent_name
5427 );
5428
5429 Callout::new()
5430 .severity(Severity::Error)
5431 .title("Request Refused")
5432 .icon(IconName::XCircle)
5433 .description(refusal_message.clone())
5434 .actions_slot(self.create_copy_button(&refusal_message))
5435 .dismiss_action(self.dismiss_error_button(cx))
5436 }
5437
5438 fn render_any_thread_error(
5439 &mut self,
5440 error: SharedString,
5441 window: &mut Window,
5442 cx: &mut Context<'_, Self>,
5443 ) -> Callout {
5444 let can_resume = self
5445 .thread()
5446 .map_or(false, |thread| thread.read(cx).can_resume(cx));
5447
5448 let can_enable_burn_mode = self.as_native_thread(cx).map_or(false, |thread| {
5449 let thread = thread.read(cx);
5450 let supports_burn_mode = thread
5451 .model()
5452 .map_or(false, |model| model.supports_burn_mode());
5453 supports_burn_mode && thread.completion_mode() == CompletionMode::Normal
5454 });
5455
5456 let markdown = if let Some(markdown) = &self.thread_error_markdown {
5457 markdown.clone()
5458 } else {
5459 let markdown = cx.new(|cx| Markdown::new(error.clone(), None, None, cx));
5460 self.thread_error_markdown = Some(markdown.clone());
5461 markdown
5462 };
5463
5464 let markdown_style = default_markdown_style(false, true, window, cx);
5465 let description = self
5466 .render_markdown(markdown, markdown_style)
5467 .into_any_element();
5468
5469 Callout::new()
5470 .severity(Severity::Error)
5471 .icon(IconName::XCircle)
5472 .title("An Error Happened")
5473 .description_slot(description)
5474 .actions_slot(
5475 h_flex()
5476 .gap_0p5()
5477 .when(can_resume && can_enable_burn_mode, |this| {
5478 this.child(
5479 Button::new("enable-burn-mode-and-retry", "Enable Burn Mode and Retry")
5480 .icon(IconName::ZedBurnMode)
5481 .icon_position(IconPosition::Start)
5482 .icon_size(IconSize::Small)
5483 .label_size(LabelSize::Small)
5484 .on_click(cx.listener(|this, _, window, cx| {
5485 this.toggle_burn_mode(&ToggleBurnMode, window, cx);
5486 this.resume_chat(cx);
5487 })),
5488 )
5489 })
5490 .when(can_resume, |this| {
5491 this.child(
5492 IconButton::new("retry", IconName::RotateCw)
5493 .icon_size(IconSize::Small)
5494 .tooltip(Tooltip::text("Retry Generation"))
5495 .on_click(cx.listener(|this, _, _window, cx| {
5496 this.resume_chat(cx);
5497 })),
5498 )
5499 })
5500 .child(self.create_copy_button(error.to_string())),
5501 )
5502 .dismiss_action(self.dismiss_error_button(cx))
5503 }
5504
5505 fn render_payment_required_error(&self, cx: &mut Context<Self>) -> Callout {
5506 const ERROR_MESSAGE: &str =
5507 "You reached your free usage limit. Upgrade to Zed Pro for more prompts.";
5508
5509 Callout::new()
5510 .severity(Severity::Error)
5511 .icon(IconName::XCircle)
5512 .title("Free Usage Exceeded")
5513 .description(ERROR_MESSAGE)
5514 .actions_slot(
5515 h_flex()
5516 .gap_0p5()
5517 .child(self.upgrade_button(cx))
5518 .child(self.create_copy_button(ERROR_MESSAGE)),
5519 )
5520 .dismiss_action(self.dismiss_error_button(cx))
5521 }
5522
5523 fn render_authentication_required_error(
5524 &self,
5525 error: SharedString,
5526 cx: &mut Context<Self>,
5527 ) -> Callout {
5528 Callout::new()
5529 .severity(Severity::Error)
5530 .title("Authentication Required")
5531 .icon(IconName::XCircle)
5532 .description(error.clone())
5533 .actions_slot(
5534 h_flex()
5535 .gap_0p5()
5536 .child(self.authenticate_button(cx))
5537 .child(self.create_copy_button(error)),
5538 )
5539 .dismiss_action(self.dismiss_error_button(cx))
5540 }
5541
5542 fn render_model_request_limit_reached_error(
5543 &self,
5544 plan: cloud_llm_client::Plan,
5545 cx: &mut Context<Self>,
5546 ) -> Callout {
5547 let error_message = match plan {
5548 cloud_llm_client::Plan::V1(PlanV1::ZedPro) => {
5549 "Upgrade to usage-based billing for more prompts."
5550 }
5551 cloud_llm_client::Plan::V1(PlanV1::ZedProTrial)
5552 | cloud_llm_client::Plan::V1(PlanV1::ZedFree) => "Upgrade to Zed Pro for more prompts.",
5553 cloud_llm_client::Plan::V2(_) => "",
5554 };
5555
5556 Callout::new()
5557 .severity(Severity::Error)
5558 .title("Model Prompt Limit Reached")
5559 .icon(IconName::XCircle)
5560 .description(error_message)
5561 .actions_slot(
5562 h_flex()
5563 .gap_0p5()
5564 .child(self.upgrade_button(cx))
5565 .child(self.create_copy_button(error_message)),
5566 )
5567 .dismiss_action(self.dismiss_error_button(cx))
5568 }
5569
5570 fn render_tool_use_limit_reached_error(&self, cx: &mut Context<Self>) -> Option<Callout> {
5571 let thread = self.as_native_thread(cx)?;
5572 let supports_burn_mode = thread
5573 .read(cx)
5574 .model()
5575 .is_some_and(|model| model.supports_burn_mode());
5576
5577 let focus_handle = self.focus_handle(cx);
5578
5579 Some(
5580 Callout::new()
5581 .icon(IconName::Info)
5582 .title("Consecutive tool use limit reached.")
5583 .actions_slot(
5584 h_flex()
5585 .gap_0p5()
5586 .when(supports_burn_mode, |this| {
5587 this.child(
5588 Button::new("continue-burn-mode", "Continue with Burn Mode")
5589 .style(ButtonStyle::Filled)
5590 .style(ButtonStyle::Tinted(ui::TintColor::Accent))
5591 .layer(ElevationIndex::ModalSurface)
5592 .label_size(LabelSize::Small)
5593 .key_binding(
5594 KeyBinding::for_action_in(
5595 &ContinueWithBurnMode,
5596 &focus_handle,
5597 cx,
5598 )
5599 .map(|kb| kb.size(rems_from_px(10.))),
5600 )
5601 .tooltip(Tooltip::text(
5602 "Enable Burn Mode for unlimited tool use.",
5603 ))
5604 .on_click({
5605 cx.listener(move |this, _, _window, cx| {
5606 thread.update(cx, |thread, cx| {
5607 thread
5608 .set_completion_mode(CompletionMode::Burn, cx);
5609 });
5610 this.resume_chat(cx);
5611 })
5612 }),
5613 )
5614 })
5615 .child(
5616 Button::new("continue-conversation", "Continue")
5617 .layer(ElevationIndex::ModalSurface)
5618 .label_size(LabelSize::Small)
5619 .key_binding(
5620 KeyBinding::for_action_in(&ContinueThread, &focus_handle, cx)
5621 .map(|kb| kb.size(rems_from_px(10.))),
5622 )
5623 .on_click(cx.listener(|this, _, _window, cx| {
5624 this.resume_chat(cx);
5625 })),
5626 ),
5627 ),
5628 )
5629 }
5630
5631 fn create_copy_button(&self, message: impl Into<String>) -> impl IntoElement {
5632 let message = message.into();
5633
5634 IconButton::new("copy", IconName::Copy)
5635 .icon_size(IconSize::Small)
5636 .tooltip(Tooltip::text("Copy Error Message"))
5637 .on_click(move |_, _, cx| {
5638 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
5639 })
5640 }
5641
5642 fn dismiss_error_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
5643 IconButton::new("dismiss", IconName::Close)
5644 .icon_size(IconSize::Small)
5645 .tooltip(Tooltip::text("Dismiss Error"))
5646 .on_click(cx.listener({
5647 move |this, _, _, cx| {
5648 this.clear_thread_error(cx);
5649 cx.notify();
5650 }
5651 }))
5652 }
5653
5654 fn authenticate_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
5655 Button::new("authenticate", "Authenticate")
5656 .label_size(LabelSize::Small)
5657 .style(ButtonStyle::Filled)
5658 .on_click(cx.listener({
5659 move |this, _, window, cx| {
5660 let agent = this.agent.clone();
5661 let ThreadState::Ready { thread, .. } = &this.thread_state else {
5662 return;
5663 };
5664
5665 let connection = thread.read(cx).connection().clone();
5666 let err = AuthRequired {
5667 description: None,
5668 provider_id: None,
5669 };
5670 this.clear_thread_error(cx);
5671 let this = cx.weak_entity();
5672 window.defer(cx, |window, cx| {
5673 Self::handle_auth_required(this, err, agent, connection, window, cx);
5674 })
5675 }
5676 }))
5677 }
5678
5679 pub(crate) fn reauthenticate(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5680 let agent = self.agent.clone();
5681 let ThreadState::Ready { thread, .. } = &self.thread_state else {
5682 return;
5683 };
5684
5685 let connection = thread.read(cx).connection().clone();
5686 let err = AuthRequired {
5687 description: None,
5688 provider_id: None,
5689 };
5690 self.clear_thread_error(cx);
5691 let this = cx.weak_entity();
5692 window.defer(cx, |window, cx| {
5693 Self::handle_auth_required(this, err, agent, connection, window, cx);
5694 })
5695 }
5696
5697 fn upgrade_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
5698 Button::new("upgrade", "Upgrade")
5699 .label_size(LabelSize::Small)
5700 .style(ButtonStyle::Tinted(ui::TintColor::Accent))
5701 .on_click(cx.listener({
5702 move |this, _, _, cx| {
5703 this.clear_thread_error(cx);
5704 cx.open_url(&zed_urls::upgrade_to_zed_pro_url(cx));
5705 }
5706 }))
5707 }
5708
5709 pub fn delete_history_entry(&mut self, entry: HistoryEntry, cx: &mut Context<Self>) {
5710 let task = match entry {
5711 HistoryEntry::AcpThread(thread) => self.history_store.update(cx, |history, cx| {
5712 history.delete_thread(thread.id.clone(), cx)
5713 }),
5714 HistoryEntry::TextThread(text_thread) => {
5715 self.history_store.update(cx, |history, cx| {
5716 history.delete_text_thread(text_thread.path.clone(), cx)
5717 })
5718 }
5719 };
5720 task.detach_and_log_err(cx);
5721 }
5722
5723 /// Returns the currently active editor, either for a message that is being
5724 /// edited or the editor for a new message.
5725 fn active_editor(&self, cx: &App) -> Entity<MessageEditor> {
5726 if let Some(index) = self.editing_message
5727 && let Some(editor) = self
5728 .entry_view_state
5729 .read(cx)
5730 .entry(index)
5731 .and_then(|e| e.message_editor())
5732 .cloned()
5733 {
5734 editor
5735 } else {
5736 self.message_editor.clone()
5737 }
5738 }
5739}
5740
5741fn loading_contents_spinner(size: IconSize) -> AnyElement {
5742 Icon::new(IconName::LoadCircle)
5743 .size(size)
5744 .color(Color::Accent)
5745 .with_rotate_animation(3)
5746 .into_any_element()
5747}
5748
5749fn placeholder_text(agent_name: &str, has_commands: bool) -> String {
5750 if agent_name == "Zed Agent" {
5751 format!("Message the {} — @ to include context", agent_name)
5752 } else if has_commands {
5753 format!(
5754 "Message {} — @ to include context, / for commands",
5755 agent_name
5756 )
5757 } else {
5758 format!("Message {} — @ to include context", agent_name)
5759 }
5760}
5761
5762impl Focusable for AcpThreadView {
5763 fn focus_handle(&self, cx: &App) -> FocusHandle {
5764 match self.thread_state {
5765 ThreadState::Loading { .. } | ThreadState::Ready { .. } => {
5766 self.active_editor(cx).focus_handle(cx)
5767 }
5768 ThreadState::LoadError(_) | ThreadState::Unauthenticated { .. } => {
5769 self.focus_handle.clone()
5770 }
5771 }
5772 }
5773}
5774
5775impl Render for AcpThreadView {
5776 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
5777 let has_messages = self.list_state.item_count() > 0;
5778 let line_height = TextSize::Small.rems(cx).to_pixels(window.rem_size()) * 1.5;
5779
5780 v_flex()
5781 .size_full()
5782 .key_context("AcpThread")
5783 .on_action(cx.listener(Self::toggle_burn_mode))
5784 .on_action(cx.listener(Self::keep_all))
5785 .on_action(cx.listener(Self::reject_all))
5786 .on_action(cx.listener(Self::allow_always))
5787 .on_action(cx.listener(Self::allow_once))
5788 .on_action(cx.listener(Self::reject_once))
5789 .track_focus(&self.focus_handle)
5790 .bg(cx.theme().colors().panel_background)
5791 .child(match &self.thread_state {
5792 ThreadState::Unauthenticated {
5793 connection,
5794 description,
5795 configuration_view,
5796 pending_auth_method,
5797 ..
5798 } => self
5799 .render_auth_required_state(
5800 connection,
5801 description.as_ref(),
5802 configuration_view.as_ref(),
5803 pending_auth_method.as_ref(),
5804 window,
5805 cx,
5806 )
5807 .into_any(),
5808 ThreadState::Loading { .. } => v_flex()
5809 .flex_1()
5810 .child(self.render_recent_history(cx))
5811 .into_any(),
5812 ThreadState::LoadError(e) => v_flex()
5813 .flex_1()
5814 .size_full()
5815 .items_center()
5816 .justify_end()
5817 .child(self.render_load_error(e, window, cx))
5818 .into_any(),
5819 ThreadState::Ready { .. } => v_flex().flex_1().map(|this| {
5820 if has_messages {
5821 this.child(
5822 list(
5823 self.list_state.clone(),
5824 cx.processor(|this, index: usize, window, cx| {
5825 let Some((entry, len)) = this.thread().and_then(|thread| {
5826 let entries = &thread.read(cx).entries();
5827 Some((entries.get(index)?, entries.len()))
5828 }) else {
5829 return Empty.into_any();
5830 };
5831 this.render_entry(index, len, entry, window, cx)
5832 }),
5833 )
5834 .with_sizing_behavior(gpui::ListSizingBehavior::Auto)
5835 .flex_grow()
5836 .into_any(),
5837 )
5838 .vertical_scrollbar_for(self.list_state.clone(), window, cx)
5839 .into_any()
5840 } else {
5841 this.child(self.render_recent_history(cx)).into_any()
5842 }
5843 }),
5844 })
5845 // The activity bar is intentionally rendered outside of the ThreadState::Ready match
5846 // above so that the scrollbar doesn't render behind it. The current setup allows
5847 // the scrollbar to stop exactly at the activity bar start.
5848 .when(has_messages, |this| match &self.thread_state {
5849 ThreadState::Ready { thread, .. } => {
5850 this.children(self.render_activity_bar(thread, window, cx))
5851 }
5852 _ => this,
5853 })
5854 .children(self.render_thread_retry_status_callout(window, cx))
5855 .children({
5856 if cfg!(windows) && self.project.read(cx).is_local() {
5857 self.render_codex_windows_warning(cx)
5858 } else {
5859 None
5860 }
5861 })
5862 .children(self.render_thread_error(window, cx))
5863 .when_some(
5864 self.new_server_version_available.as_ref().filter(|_| {
5865 !has_messages || !matches!(self.thread_state, ThreadState::Ready { .. })
5866 }),
5867 |this, version| this.child(self.render_new_version_callout(&version, cx)),
5868 )
5869 .children(
5870 if let Some(usage_callout) = self.render_usage_callout(line_height, cx) {
5871 Some(usage_callout.into_any_element())
5872 } else {
5873 self.render_token_limit_callout(line_height, cx)
5874 .map(|token_limit_callout| token_limit_callout.into_any_element())
5875 },
5876 )
5877 .child(self.render_message_editor(window, cx))
5878 }
5879}
5880
5881fn default_markdown_style(
5882 buffer_font: bool,
5883 muted_text: bool,
5884 window: &Window,
5885 cx: &App,
5886) -> MarkdownStyle {
5887 let theme_settings = ThemeSettings::get_global(cx);
5888 let colors = cx.theme().colors();
5889
5890 let buffer_font_size = theme_settings.agent_buffer_font_size(cx);
5891
5892 let mut text_style = window.text_style();
5893 let line_height = buffer_font_size * 1.75;
5894
5895 let font_family = if buffer_font {
5896 theme_settings.buffer_font.family.clone()
5897 } else {
5898 theme_settings.ui_font.family.clone()
5899 };
5900
5901 let font_size = if buffer_font {
5902 theme_settings.agent_buffer_font_size(cx)
5903 } else {
5904 theme_settings.agent_ui_font_size(cx)
5905 };
5906
5907 let text_color = if muted_text {
5908 colors.text_muted
5909 } else {
5910 colors.text
5911 };
5912
5913 text_style.refine(&TextStyleRefinement {
5914 font_family: Some(font_family),
5915 font_fallbacks: theme_settings.ui_font.fallbacks.clone(),
5916 font_features: Some(theme_settings.ui_font.features.clone()),
5917 font_size: Some(font_size.into()),
5918 line_height: Some(line_height.into()),
5919 color: Some(text_color),
5920 ..Default::default()
5921 });
5922
5923 MarkdownStyle {
5924 base_text_style: text_style.clone(),
5925 syntax: cx.theme().syntax().clone(),
5926 selection_background_color: colors.element_selection_background,
5927 code_block_overflow_x_scroll: true,
5928 heading_level_styles: Some(HeadingLevelStyles {
5929 h1: Some(TextStyleRefinement {
5930 font_size: Some(rems(1.15).into()),
5931 ..Default::default()
5932 }),
5933 h2: Some(TextStyleRefinement {
5934 font_size: Some(rems(1.1).into()),
5935 ..Default::default()
5936 }),
5937 h3: Some(TextStyleRefinement {
5938 font_size: Some(rems(1.05).into()),
5939 ..Default::default()
5940 }),
5941 h4: Some(TextStyleRefinement {
5942 font_size: Some(rems(1.).into()),
5943 ..Default::default()
5944 }),
5945 h5: Some(TextStyleRefinement {
5946 font_size: Some(rems(0.95).into()),
5947 ..Default::default()
5948 }),
5949 h6: Some(TextStyleRefinement {
5950 font_size: Some(rems(0.875).into()),
5951 ..Default::default()
5952 }),
5953 }),
5954 code_block: StyleRefinement {
5955 padding: EdgesRefinement {
5956 top: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(px(8.)))),
5957 left: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(px(8.)))),
5958 right: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(px(8.)))),
5959 bottom: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(px(8.)))),
5960 },
5961 margin: EdgesRefinement {
5962 top: Some(Length::Definite(px(8.).into())),
5963 left: Some(Length::Definite(px(0.).into())),
5964 right: Some(Length::Definite(px(0.).into())),
5965 bottom: Some(Length::Definite(px(12.).into())),
5966 },
5967 border_style: Some(BorderStyle::Solid),
5968 border_widths: EdgesRefinement {
5969 top: Some(AbsoluteLength::Pixels(px(1.))),
5970 left: Some(AbsoluteLength::Pixels(px(1.))),
5971 right: Some(AbsoluteLength::Pixels(px(1.))),
5972 bottom: Some(AbsoluteLength::Pixels(px(1.))),
5973 },
5974 border_color: Some(colors.border_variant),
5975 background: Some(colors.editor_background.into()),
5976 text: Some(TextStyleRefinement {
5977 font_family: Some(theme_settings.buffer_font.family.clone()),
5978 font_fallbacks: theme_settings.buffer_font.fallbacks.clone(),
5979 font_features: Some(theme_settings.buffer_font.features.clone()),
5980 font_size: Some(buffer_font_size.into()),
5981 ..Default::default()
5982 }),
5983 ..Default::default()
5984 },
5985 inline_code: TextStyleRefinement {
5986 font_family: Some(theme_settings.buffer_font.family.clone()),
5987 font_fallbacks: theme_settings.buffer_font.fallbacks.clone(),
5988 font_features: Some(theme_settings.buffer_font.features.clone()),
5989 font_size: Some(buffer_font_size.into()),
5990 background_color: Some(colors.editor_foreground.opacity(0.08)),
5991 ..Default::default()
5992 },
5993 link: TextStyleRefinement {
5994 background_color: Some(colors.editor_foreground.opacity(0.025)),
5995 color: Some(colors.text_accent),
5996 underline: Some(UnderlineStyle {
5997 color: Some(colors.text_accent.opacity(0.5)),
5998 thickness: px(1.),
5999 ..Default::default()
6000 }),
6001 ..Default::default()
6002 },
6003 ..Default::default()
6004 }
6005}
6006
6007fn plan_label_markdown_style(
6008 status: &acp::PlanEntryStatus,
6009 window: &Window,
6010 cx: &App,
6011) -> MarkdownStyle {
6012 let default_md_style = default_markdown_style(false, false, window, cx);
6013
6014 MarkdownStyle {
6015 base_text_style: TextStyle {
6016 color: cx.theme().colors().text_muted,
6017 strikethrough: if matches!(status, acp::PlanEntryStatus::Completed) {
6018 Some(gpui::StrikethroughStyle {
6019 thickness: px(1.),
6020 color: Some(cx.theme().colors().text_muted.opacity(0.8)),
6021 })
6022 } else {
6023 None
6024 },
6025 ..default_md_style.base_text_style
6026 },
6027 ..default_md_style
6028 }
6029}
6030
6031fn terminal_command_markdown_style(window: &Window, cx: &App) -> MarkdownStyle {
6032 let default_md_style = default_markdown_style(true, false, window, cx);
6033
6034 MarkdownStyle {
6035 base_text_style: TextStyle {
6036 ..default_md_style.base_text_style
6037 },
6038 selection_background_color: cx.theme().colors().element_selection_background,
6039 ..Default::default()
6040 }
6041}
6042
6043#[cfg(test)]
6044pub(crate) mod tests {
6045 use acp_thread::StubAgentConnection;
6046 use agent_client_protocol::SessionId;
6047 use assistant_text_thread::TextThreadStore;
6048 use fs::FakeFs;
6049 use gpui::{EventEmitter, SemanticVersion, TestAppContext, VisualTestContext};
6050 use project::Project;
6051 use serde_json::json;
6052 use settings::SettingsStore;
6053 use std::any::Any;
6054 use std::path::Path;
6055 use workspace::Item;
6056
6057 use super::*;
6058
6059 #[gpui::test]
6060 async fn test_drop(cx: &mut TestAppContext) {
6061 init_test(cx);
6062
6063 let (thread_view, _cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
6064 let weak_view = thread_view.downgrade();
6065 drop(thread_view);
6066 assert!(!weak_view.is_upgradable());
6067 }
6068
6069 #[gpui::test]
6070 async fn test_notification_for_stop_event(cx: &mut TestAppContext) {
6071 init_test(cx);
6072
6073 let (thread_view, cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
6074
6075 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
6076 message_editor.update_in(cx, |editor, window, cx| {
6077 editor.set_text("Hello", window, cx);
6078 });
6079
6080 cx.deactivate_window();
6081
6082 thread_view.update_in(cx, |thread_view, window, cx| {
6083 thread_view.send(window, cx);
6084 });
6085
6086 cx.run_until_parked();
6087
6088 assert!(
6089 cx.windows()
6090 .iter()
6091 .any(|window| window.downcast::<AgentNotification>().is_some())
6092 );
6093 }
6094
6095 #[gpui::test]
6096 async fn test_notification_for_error(cx: &mut TestAppContext) {
6097 init_test(cx);
6098
6099 let (thread_view, cx) =
6100 setup_thread_view(StubAgentServer::new(SaboteurAgentConnection), cx).await;
6101
6102 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
6103 message_editor.update_in(cx, |editor, window, cx| {
6104 editor.set_text("Hello", window, cx);
6105 });
6106
6107 cx.deactivate_window();
6108
6109 thread_view.update_in(cx, |thread_view, window, cx| {
6110 thread_view.send(window, cx);
6111 });
6112
6113 cx.run_until_parked();
6114
6115 assert!(
6116 cx.windows()
6117 .iter()
6118 .any(|window| window.downcast::<AgentNotification>().is_some())
6119 );
6120 }
6121
6122 #[gpui::test]
6123 async fn test_refusal_handling(cx: &mut TestAppContext) {
6124 init_test(cx);
6125
6126 let (thread_view, cx) =
6127 setup_thread_view(StubAgentServer::new(RefusalAgentConnection), cx).await;
6128
6129 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
6130 message_editor.update_in(cx, |editor, window, cx| {
6131 editor.set_text("Do something harmful", window, cx);
6132 });
6133
6134 thread_view.update_in(cx, |thread_view, window, cx| {
6135 thread_view.send(window, cx);
6136 });
6137
6138 cx.run_until_parked();
6139
6140 // Check that the refusal error is set
6141 thread_view.read_with(cx, |thread_view, _cx| {
6142 assert!(
6143 matches!(thread_view.thread_error, Some(ThreadError::Refusal)),
6144 "Expected refusal error to be set"
6145 );
6146 });
6147 }
6148
6149 #[gpui::test]
6150 async fn test_notification_for_tool_authorization(cx: &mut TestAppContext) {
6151 init_test(cx);
6152
6153 let tool_call_id = acp::ToolCallId("1".into());
6154 let tool_call = acp::ToolCall {
6155 id: tool_call_id.clone(),
6156 title: "Label".into(),
6157 kind: acp::ToolKind::Edit,
6158 status: acp::ToolCallStatus::Pending,
6159 content: vec!["hi".into()],
6160 locations: vec![],
6161 raw_input: None,
6162 raw_output: None,
6163 meta: None,
6164 };
6165 let connection =
6166 StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
6167 tool_call_id,
6168 vec![acp::PermissionOption {
6169 id: acp::PermissionOptionId("1".into()),
6170 name: "Allow".into(),
6171 kind: acp::PermissionOptionKind::AllowOnce,
6172 meta: None,
6173 }],
6174 )]));
6175
6176 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
6177
6178 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
6179
6180 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
6181 message_editor.update_in(cx, |editor, window, cx| {
6182 editor.set_text("Hello", window, cx);
6183 });
6184
6185 cx.deactivate_window();
6186
6187 thread_view.update_in(cx, |thread_view, window, cx| {
6188 thread_view.send(window, cx);
6189 });
6190
6191 cx.run_until_parked();
6192
6193 assert!(
6194 cx.windows()
6195 .iter()
6196 .any(|window| window.downcast::<AgentNotification>().is_some())
6197 );
6198 }
6199
6200 #[gpui::test]
6201 async fn test_notification_when_panel_hidden(cx: &mut TestAppContext) {
6202 init_test(cx);
6203
6204 let (thread_view, cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
6205
6206 add_to_workspace(thread_view.clone(), cx);
6207
6208 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
6209
6210 message_editor.update_in(cx, |editor, window, cx| {
6211 editor.set_text("Hello", window, cx);
6212 });
6213
6214 // Window is active (don't deactivate), but panel will be hidden
6215 // Note: In the test environment, the panel is not actually added to the dock,
6216 // so is_agent_panel_hidden will return true
6217
6218 thread_view.update_in(cx, |thread_view, window, cx| {
6219 thread_view.send(window, cx);
6220 });
6221
6222 cx.run_until_parked();
6223
6224 // Should show notification because window is active but panel is hidden
6225 assert!(
6226 cx.windows()
6227 .iter()
6228 .any(|window| window.downcast::<AgentNotification>().is_some()),
6229 "Expected notification when panel is hidden"
6230 );
6231 }
6232
6233 #[gpui::test]
6234 async fn test_notification_still_works_when_window_inactive(cx: &mut TestAppContext) {
6235 init_test(cx);
6236
6237 let (thread_view, cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
6238
6239 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
6240 message_editor.update_in(cx, |editor, window, cx| {
6241 editor.set_text("Hello", window, cx);
6242 });
6243
6244 // Deactivate window - should show notification regardless of setting
6245 cx.deactivate_window();
6246
6247 thread_view.update_in(cx, |thread_view, window, cx| {
6248 thread_view.send(window, cx);
6249 });
6250
6251 cx.run_until_parked();
6252
6253 // Should still show notification when window is inactive (existing behavior)
6254 assert!(
6255 cx.windows()
6256 .iter()
6257 .any(|window| window.downcast::<AgentNotification>().is_some()),
6258 "Expected notification when window is inactive"
6259 );
6260 }
6261
6262 #[gpui::test]
6263 async fn test_notification_respects_never_setting(cx: &mut TestAppContext) {
6264 init_test(cx);
6265
6266 // Set notify_when_agent_waiting to Never
6267 cx.update(|cx| {
6268 AgentSettings::override_global(
6269 AgentSettings {
6270 notify_when_agent_waiting: NotifyWhenAgentWaiting::Never,
6271 ..AgentSettings::get_global(cx).clone()
6272 },
6273 cx,
6274 );
6275 });
6276
6277 let (thread_view, cx) = setup_thread_view(StubAgentServer::default_response(), cx).await;
6278
6279 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
6280 message_editor.update_in(cx, |editor, window, cx| {
6281 editor.set_text("Hello", window, cx);
6282 });
6283
6284 // Window is active
6285
6286 thread_view.update_in(cx, |thread_view, window, cx| {
6287 thread_view.send(window, cx);
6288 });
6289
6290 cx.run_until_parked();
6291
6292 // Should NOT show notification because notify_when_agent_waiting is Never
6293 assert!(
6294 !cx.windows()
6295 .iter()
6296 .any(|window| window.downcast::<AgentNotification>().is_some()),
6297 "Expected no notification when notify_when_agent_waiting is Never"
6298 );
6299 }
6300
6301 async fn setup_thread_view(
6302 agent: impl AgentServer + 'static,
6303 cx: &mut TestAppContext,
6304 ) -> (Entity<AcpThreadView>, &mut VisualTestContext) {
6305 let fs = FakeFs::new(cx.executor());
6306 let project = Project::test(fs, [], cx).await;
6307 let (workspace, cx) =
6308 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6309
6310 let text_thread_store =
6311 cx.update(|_window, cx| cx.new(|cx| TextThreadStore::fake(project.clone(), cx)));
6312 let history_store =
6313 cx.update(|_window, cx| cx.new(|cx| HistoryStore::new(text_thread_store, cx)));
6314
6315 let thread_view = cx.update(|window, cx| {
6316 cx.new(|cx| {
6317 AcpThreadView::new(
6318 Rc::new(agent),
6319 None,
6320 None,
6321 workspace.downgrade(),
6322 project,
6323 history_store,
6324 None,
6325 window,
6326 cx,
6327 )
6328 })
6329 });
6330 cx.run_until_parked();
6331 (thread_view, cx)
6332 }
6333
6334 fn add_to_workspace(thread_view: Entity<AcpThreadView>, cx: &mut VisualTestContext) {
6335 let workspace = thread_view.read_with(cx, |thread_view, _cx| thread_view.workspace.clone());
6336
6337 workspace
6338 .update_in(cx, |workspace, window, cx| {
6339 workspace.add_item_to_active_pane(
6340 Box::new(cx.new(|_| ThreadViewItem(thread_view.clone()))),
6341 None,
6342 true,
6343 window,
6344 cx,
6345 );
6346 })
6347 .unwrap();
6348 }
6349
6350 struct ThreadViewItem(Entity<AcpThreadView>);
6351
6352 impl Item for ThreadViewItem {
6353 type Event = ();
6354
6355 fn include_in_nav_history() -> bool {
6356 false
6357 }
6358
6359 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
6360 "Test".into()
6361 }
6362 }
6363
6364 impl EventEmitter<()> for ThreadViewItem {}
6365
6366 impl Focusable for ThreadViewItem {
6367 fn focus_handle(&self, cx: &App) -> FocusHandle {
6368 self.0.read(cx).focus_handle(cx)
6369 }
6370 }
6371
6372 impl Render for ThreadViewItem {
6373 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
6374 self.0.clone().into_any_element()
6375 }
6376 }
6377
6378 struct StubAgentServer<C> {
6379 connection: C,
6380 }
6381
6382 impl<C> StubAgentServer<C> {
6383 fn new(connection: C) -> Self {
6384 Self { connection }
6385 }
6386 }
6387
6388 impl StubAgentServer<StubAgentConnection> {
6389 fn default_response() -> Self {
6390 let conn = StubAgentConnection::new();
6391 conn.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
6392 acp::ContentChunk {
6393 content: "Default response".into(),
6394 meta: None,
6395 },
6396 )]);
6397 Self::new(conn)
6398 }
6399 }
6400
6401 impl<C> AgentServer for StubAgentServer<C>
6402 where
6403 C: 'static + AgentConnection + Send + Clone,
6404 {
6405 fn telemetry_id(&self) -> &'static str {
6406 "test"
6407 }
6408
6409 fn logo(&self) -> ui::IconName {
6410 ui::IconName::Ai
6411 }
6412
6413 fn name(&self) -> SharedString {
6414 "Test".into()
6415 }
6416
6417 fn connect(
6418 &self,
6419 _root_dir: Option<&Path>,
6420 _delegate: AgentServerDelegate,
6421 _cx: &mut App,
6422 ) -> Task<gpui::Result<(Rc<dyn AgentConnection>, Option<task::SpawnInTerminal>)>> {
6423 Task::ready(Ok((Rc::new(self.connection.clone()), None)))
6424 }
6425
6426 fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
6427 self
6428 }
6429 }
6430
6431 #[derive(Clone)]
6432 struct SaboteurAgentConnection;
6433
6434 impl AgentConnection for SaboteurAgentConnection {
6435 fn telemetry_id(&self) -> &'static str {
6436 "saboteur"
6437 }
6438
6439 fn new_thread(
6440 self: Rc<Self>,
6441 project: Entity<Project>,
6442 _cwd: &Path,
6443 cx: &mut gpui::App,
6444 ) -> Task<gpui::Result<Entity<AcpThread>>> {
6445 Task::ready(Ok(cx.new(|cx| {
6446 let action_log = cx.new(|_| ActionLog::new(project.clone()));
6447 AcpThread::new(
6448 "SaboteurAgentConnection",
6449 self,
6450 project,
6451 action_log,
6452 SessionId("test".into()),
6453 watch::Receiver::constant(acp::PromptCapabilities {
6454 image: true,
6455 audio: true,
6456 embedded_context: true,
6457 meta: None,
6458 }),
6459 cx,
6460 )
6461 })))
6462 }
6463
6464 fn auth_methods(&self) -> &[acp::AuthMethod] {
6465 &[]
6466 }
6467
6468 fn authenticate(
6469 &self,
6470 _method_id: acp::AuthMethodId,
6471 _cx: &mut App,
6472 ) -> Task<gpui::Result<()>> {
6473 unimplemented!()
6474 }
6475
6476 fn prompt(
6477 &self,
6478 _id: Option<acp_thread::UserMessageId>,
6479 _params: acp::PromptRequest,
6480 _cx: &mut App,
6481 ) -> Task<gpui::Result<acp::PromptResponse>> {
6482 Task::ready(Err(anyhow::anyhow!("Error prompting")))
6483 }
6484
6485 fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {
6486 unimplemented!()
6487 }
6488
6489 fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
6490 self
6491 }
6492 }
6493
6494 /// Simulates a model which always returns a refusal response
6495 #[derive(Clone)]
6496 struct RefusalAgentConnection;
6497
6498 impl AgentConnection for RefusalAgentConnection {
6499 fn telemetry_id(&self) -> &'static str {
6500 "refusal"
6501 }
6502
6503 fn new_thread(
6504 self: Rc<Self>,
6505 project: Entity<Project>,
6506 _cwd: &Path,
6507 cx: &mut gpui::App,
6508 ) -> Task<gpui::Result<Entity<AcpThread>>> {
6509 Task::ready(Ok(cx.new(|cx| {
6510 let action_log = cx.new(|_| ActionLog::new(project.clone()));
6511 AcpThread::new(
6512 "RefusalAgentConnection",
6513 self,
6514 project,
6515 action_log,
6516 SessionId("test".into()),
6517 watch::Receiver::constant(acp::PromptCapabilities {
6518 image: true,
6519 audio: true,
6520 embedded_context: true,
6521 meta: None,
6522 }),
6523 cx,
6524 )
6525 })))
6526 }
6527
6528 fn auth_methods(&self) -> &[acp::AuthMethod] {
6529 &[]
6530 }
6531
6532 fn authenticate(
6533 &self,
6534 _method_id: acp::AuthMethodId,
6535 _cx: &mut App,
6536 ) -> Task<gpui::Result<()>> {
6537 unimplemented!()
6538 }
6539
6540 fn prompt(
6541 &self,
6542 _id: Option<acp_thread::UserMessageId>,
6543 _params: acp::PromptRequest,
6544 _cx: &mut App,
6545 ) -> Task<gpui::Result<acp::PromptResponse>> {
6546 Task::ready(Ok(acp::PromptResponse {
6547 stop_reason: acp::StopReason::Refusal,
6548 meta: None,
6549 }))
6550 }
6551
6552 fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {
6553 unimplemented!()
6554 }
6555
6556 fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
6557 self
6558 }
6559 }
6560
6561 pub(crate) fn init_test(cx: &mut TestAppContext) {
6562 cx.update(|cx| {
6563 let settings_store = SettingsStore::test(cx);
6564 cx.set_global(settings_store);
6565 theme::init(theme::LoadThemes::JustBase, cx);
6566 release_channel::init(SemanticVersion::default(), cx);
6567 prompt_store::init(cx)
6568 });
6569 }
6570
6571 #[gpui::test]
6572 async fn test_rewind_views(cx: &mut TestAppContext) {
6573 init_test(cx);
6574
6575 let fs = FakeFs::new(cx.executor());
6576 fs.insert_tree(
6577 "/project",
6578 json!({
6579 "test1.txt": "old content 1",
6580 "test2.txt": "old content 2"
6581 }),
6582 )
6583 .await;
6584 let project = Project::test(fs, [Path::new("/project")], cx).await;
6585 let (workspace, cx) =
6586 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6587
6588 let text_thread_store =
6589 cx.update(|_window, cx| cx.new(|cx| TextThreadStore::fake(project.clone(), cx)));
6590 let history_store =
6591 cx.update(|_window, cx| cx.new(|cx| HistoryStore::new(text_thread_store, cx)));
6592
6593 let connection = Rc::new(StubAgentConnection::new());
6594 let thread_view = cx.update(|window, cx| {
6595 cx.new(|cx| {
6596 AcpThreadView::new(
6597 Rc::new(StubAgentServer::new(connection.as_ref().clone())),
6598 None,
6599 None,
6600 workspace.downgrade(),
6601 project.clone(),
6602 history_store.clone(),
6603 None,
6604 window,
6605 cx,
6606 )
6607 })
6608 });
6609
6610 cx.run_until_parked();
6611
6612 let thread = thread_view
6613 .read_with(cx, |view, _| view.thread().cloned())
6614 .unwrap();
6615
6616 // First user message
6617 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(acp::ToolCall {
6618 id: acp::ToolCallId("tool1".into()),
6619 title: "Edit file 1".into(),
6620 kind: acp::ToolKind::Edit,
6621 status: acp::ToolCallStatus::Completed,
6622 content: vec![acp::ToolCallContent::Diff {
6623 diff: acp::Diff {
6624 path: "/project/test1.txt".into(),
6625 old_text: Some("old content 1".into()),
6626 new_text: "new content 1".into(),
6627 meta: None,
6628 },
6629 }],
6630 locations: vec![],
6631 raw_input: None,
6632 raw_output: None,
6633 meta: None,
6634 })]);
6635
6636 thread
6637 .update(cx, |thread, cx| thread.send_raw("Give me a diff", cx))
6638 .await
6639 .unwrap();
6640 cx.run_until_parked();
6641
6642 thread.read_with(cx, |thread, _| {
6643 assert_eq!(thread.entries().len(), 2);
6644 });
6645
6646 thread_view.read_with(cx, |view, cx| {
6647 view.entry_view_state.read_with(cx, |entry_view_state, _| {
6648 assert!(
6649 entry_view_state
6650 .entry(0)
6651 .unwrap()
6652 .message_editor()
6653 .is_some()
6654 );
6655 assert!(entry_view_state.entry(1).unwrap().has_content());
6656 });
6657 });
6658
6659 // Second user message
6660 connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(acp::ToolCall {
6661 id: acp::ToolCallId("tool2".into()),
6662 title: "Edit file 2".into(),
6663 kind: acp::ToolKind::Edit,
6664 status: acp::ToolCallStatus::Completed,
6665 content: vec![acp::ToolCallContent::Diff {
6666 diff: acp::Diff {
6667 path: "/project/test2.txt".into(),
6668 old_text: Some("old content 2".into()),
6669 new_text: "new content 2".into(),
6670 meta: None,
6671 },
6672 }],
6673 locations: vec![],
6674 raw_input: None,
6675 raw_output: None,
6676 meta: None,
6677 })]);
6678
6679 thread
6680 .update(cx, |thread, cx| thread.send_raw("Another one", cx))
6681 .await
6682 .unwrap();
6683 cx.run_until_parked();
6684
6685 let second_user_message_id = thread.read_with(cx, |thread, _| {
6686 assert_eq!(thread.entries().len(), 4);
6687 let AgentThreadEntry::UserMessage(user_message) = &thread.entries()[2] else {
6688 panic!();
6689 };
6690 user_message.id.clone().unwrap()
6691 });
6692
6693 thread_view.read_with(cx, |view, cx| {
6694 view.entry_view_state.read_with(cx, |entry_view_state, _| {
6695 assert!(
6696 entry_view_state
6697 .entry(0)
6698 .unwrap()
6699 .message_editor()
6700 .is_some()
6701 );
6702 assert!(entry_view_state.entry(1).unwrap().has_content());
6703 assert!(
6704 entry_view_state
6705 .entry(2)
6706 .unwrap()
6707 .message_editor()
6708 .is_some()
6709 );
6710 assert!(entry_view_state.entry(3).unwrap().has_content());
6711 });
6712 });
6713
6714 // Rewind to first message
6715 thread
6716 .update(cx, |thread, cx| thread.rewind(second_user_message_id, cx))
6717 .await
6718 .unwrap();
6719
6720 cx.run_until_parked();
6721
6722 thread.read_with(cx, |thread, _| {
6723 assert_eq!(thread.entries().len(), 2);
6724 });
6725
6726 thread_view.read_with(cx, |view, cx| {
6727 view.entry_view_state.read_with(cx, |entry_view_state, _| {
6728 assert!(
6729 entry_view_state
6730 .entry(0)
6731 .unwrap()
6732 .message_editor()
6733 .is_some()
6734 );
6735 assert!(entry_view_state.entry(1).unwrap().has_content());
6736
6737 // Old views should be dropped
6738 assert!(entry_view_state.entry(2).is_none());
6739 assert!(entry_view_state.entry(3).is_none());
6740 });
6741 });
6742 }
6743
6744 #[gpui::test]
6745 async fn test_message_editing_cancel(cx: &mut TestAppContext) {
6746 init_test(cx);
6747
6748 let connection = StubAgentConnection::new();
6749
6750 connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
6751 acp::ContentChunk {
6752 content: acp::ContentBlock::Text(acp::TextContent {
6753 text: "Response".into(),
6754 annotations: None,
6755 meta: None,
6756 }),
6757 meta: None,
6758 },
6759 )]);
6760
6761 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
6762 add_to_workspace(thread_view.clone(), cx);
6763
6764 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
6765 message_editor.update_in(cx, |editor, window, cx| {
6766 editor.set_text("Original message to edit", window, cx);
6767 });
6768 thread_view.update_in(cx, |thread_view, window, cx| {
6769 thread_view.send(window, cx);
6770 });
6771
6772 cx.run_until_parked();
6773
6774 let user_message_editor = thread_view.read_with(cx, |view, cx| {
6775 assert_eq!(view.editing_message, None);
6776
6777 view.entry_view_state
6778 .read(cx)
6779 .entry(0)
6780 .unwrap()
6781 .message_editor()
6782 .unwrap()
6783 .clone()
6784 });
6785
6786 // Focus
6787 cx.focus(&user_message_editor);
6788 thread_view.read_with(cx, |view, _cx| {
6789 assert_eq!(view.editing_message, Some(0));
6790 });
6791
6792 // Edit
6793 user_message_editor.update_in(cx, |editor, window, cx| {
6794 editor.set_text("Edited message content", window, cx);
6795 });
6796
6797 // Cancel
6798 user_message_editor.update_in(cx, |_editor, window, cx| {
6799 window.dispatch_action(Box::new(editor::actions::Cancel), cx);
6800 });
6801
6802 thread_view.read_with(cx, |view, _cx| {
6803 assert_eq!(view.editing_message, None);
6804 });
6805
6806 user_message_editor.read_with(cx, |editor, cx| {
6807 assert_eq!(editor.text(cx), "Original message to edit");
6808 });
6809 }
6810
6811 #[gpui::test]
6812 async fn test_message_doesnt_send_if_empty(cx: &mut TestAppContext) {
6813 init_test(cx);
6814
6815 let connection = StubAgentConnection::new();
6816
6817 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
6818 add_to_workspace(thread_view.clone(), cx);
6819
6820 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
6821 let mut events = cx.events(&message_editor);
6822 message_editor.update_in(cx, |editor, window, cx| {
6823 editor.set_text("", window, cx);
6824 });
6825
6826 message_editor.update_in(cx, |_editor, window, cx| {
6827 window.dispatch_action(Box::new(Chat), cx);
6828 });
6829 cx.run_until_parked();
6830 // We shouldn't have received any messages
6831 assert!(matches!(
6832 events.try_next(),
6833 Err(futures::channel::mpsc::TryRecvError { .. })
6834 ));
6835 }
6836
6837 #[gpui::test]
6838 async fn test_message_editing_regenerate(cx: &mut TestAppContext) {
6839 init_test(cx);
6840
6841 let connection = StubAgentConnection::new();
6842
6843 connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
6844 acp::ContentChunk {
6845 content: acp::ContentBlock::Text(acp::TextContent {
6846 text: "Response".into(),
6847 annotations: None,
6848 meta: None,
6849 }),
6850 meta: None,
6851 },
6852 )]);
6853
6854 let (thread_view, cx) =
6855 setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
6856 add_to_workspace(thread_view.clone(), cx);
6857
6858 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
6859 message_editor.update_in(cx, |editor, window, cx| {
6860 editor.set_text("Original message to edit", window, cx);
6861 });
6862 thread_view.update_in(cx, |thread_view, window, cx| {
6863 thread_view.send(window, cx);
6864 });
6865
6866 cx.run_until_parked();
6867
6868 let user_message_editor = thread_view.read_with(cx, |view, cx| {
6869 assert_eq!(view.editing_message, None);
6870 assert_eq!(view.thread().unwrap().read(cx).entries().len(), 2);
6871
6872 view.entry_view_state
6873 .read(cx)
6874 .entry(0)
6875 .unwrap()
6876 .message_editor()
6877 .unwrap()
6878 .clone()
6879 });
6880
6881 // Focus
6882 cx.focus(&user_message_editor);
6883
6884 // Edit
6885 user_message_editor.update_in(cx, |editor, window, cx| {
6886 editor.set_text("Edited message content", window, cx);
6887 });
6888
6889 // Send
6890 connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
6891 acp::ContentChunk {
6892 content: acp::ContentBlock::Text(acp::TextContent {
6893 text: "New Response".into(),
6894 annotations: None,
6895 meta: None,
6896 }),
6897 meta: None,
6898 },
6899 )]);
6900
6901 user_message_editor.update_in(cx, |_editor, window, cx| {
6902 window.dispatch_action(Box::new(Chat), cx);
6903 });
6904
6905 cx.run_until_parked();
6906
6907 thread_view.read_with(cx, |view, cx| {
6908 assert_eq!(view.editing_message, None);
6909
6910 let entries = view.thread().unwrap().read(cx).entries();
6911 assert_eq!(entries.len(), 2);
6912 assert_eq!(
6913 entries[0].to_markdown(cx),
6914 "## User\n\nEdited message content\n\n"
6915 );
6916 assert_eq!(
6917 entries[1].to_markdown(cx),
6918 "## Assistant\n\nNew Response\n\n"
6919 );
6920
6921 let new_editor = view.entry_view_state.read_with(cx, |state, _cx| {
6922 assert!(!state.entry(1).unwrap().has_content());
6923 state.entry(0).unwrap().message_editor().unwrap().clone()
6924 });
6925
6926 assert_eq!(new_editor.read(cx).text(cx), "Edited message content");
6927 })
6928 }
6929
6930 #[gpui::test]
6931 async fn test_message_editing_while_generating(cx: &mut TestAppContext) {
6932 init_test(cx);
6933
6934 let connection = StubAgentConnection::new();
6935
6936 let (thread_view, cx) =
6937 setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
6938 add_to_workspace(thread_view.clone(), cx);
6939
6940 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
6941 message_editor.update_in(cx, |editor, window, cx| {
6942 editor.set_text("Original message to edit", window, cx);
6943 });
6944 thread_view.update_in(cx, |thread_view, window, cx| {
6945 thread_view.send(window, cx);
6946 });
6947
6948 cx.run_until_parked();
6949
6950 let (user_message_editor, session_id) = thread_view.read_with(cx, |view, cx| {
6951 let thread = view.thread().unwrap().read(cx);
6952 assert_eq!(thread.entries().len(), 1);
6953
6954 let editor = view
6955 .entry_view_state
6956 .read(cx)
6957 .entry(0)
6958 .unwrap()
6959 .message_editor()
6960 .unwrap()
6961 .clone();
6962
6963 (editor, thread.session_id().clone())
6964 });
6965
6966 // Focus
6967 cx.focus(&user_message_editor);
6968
6969 thread_view.read_with(cx, |view, _cx| {
6970 assert_eq!(view.editing_message, Some(0));
6971 });
6972
6973 // Edit
6974 user_message_editor.update_in(cx, |editor, window, cx| {
6975 editor.set_text("Edited message content", window, cx);
6976 });
6977
6978 thread_view.read_with(cx, |view, _cx| {
6979 assert_eq!(view.editing_message, Some(0));
6980 });
6981
6982 // Finish streaming response
6983 cx.update(|_, cx| {
6984 connection.send_update(
6985 session_id.clone(),
6986 acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk {
6987 content: acp::ContentBlock::Text(acp::TextContent {
6988 text: "Response".into(),
6989 annotations: None,
6990 meta: None,
6991 }),
6992 meta: None,
6993 }),
6994 cx,
6995 );
6996 connection.end_turn(session_id, acp::StopReason::EndTurn);
6997 });
6998
6999 thread_view.read_with(cx, |view, _cx| {
7000 assert_eq!(view.editing_message, Some(0));
7001 });
7002
7003 cx.run_until_parked();
7004
7005 // Should still be editing
7006 cx.update(|window, cx| {
7007 assert!(user_message_editor.focus_handle(cx).is_focused(window));
7008 assert_eq!(thread_view.read(cx).editing_message, Some(0));
7009 assert_eq!(
7010 user_message_editor.read(cx).text(cx),
7011 "Edited message content"
7012 );
7013 });
7014 }
7015
7016 #[gpui::test]
7017 async fn test_interrupt(cx: &mut TestAppContext) {
7018 init_test(cx);
7019
7020 let connection = StubAgentConnection::new();
7021
7022 let (thread_view, cx) =
7023 setup_thread_view(StubAgentServer::new(connection.clone()), cx).await;
7024 add_to_workspace(thread_view.clone(), cx);
7025
7026 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
7027 message_editor.update_in(cx, |editor, window, cx| {
7028 editor.set_text("Message 1", window, cx);
7029 });
7030 thread_view.update_in(cx, |thread_view, window, cx| {
7031 thread_view.send(window, cx);
7032 });
7033
7034 let (thread, session_id) = thread_view.read_with(cx, |view, cx| {
7035 let thread = view.thread().unwrap();
7036
7037 (thread.clone(), thread.read(cx).session_id().clone())
7038 });
7039
7040 cx.run_until_parked();
7041
7042 cx.update(|_, cx| {
7043 connection.send_update(
7044 session_id.clone(),
7045 acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk {
7046 content: "Message 1 resp".into(),
7047 meta: None,
7048 }),
7049 cx,
7050 );
7051 });
7052
7053 cx.run_until_parked();
7054
7055 thread.read_with(cx, |thread, cx| {
7056 assert_eq!(
7057 thread.to_markdown(cx),
7058 indoc::indoc! {"
7059 ## User
7060
7061 Message 1
7062
7063 ## Assistant
7064
7065 Message 1 resp
7066
7067 "}
7068 )
7069 });
7070
7071 message_editor.update_in(cx, |editor, window, cx| {
7072 editor.set_text("Message 2", window, cx);
7073 });
7074 thread_view.update_in(cx, |thread_view, window, cx| {
7075 thread_view.send(window, cx);
7076 });
7077
7078 cx.update(|_, cx| {
7079 // Simulate a response sent after beginning to cancel
7080 connection.send_update(
7081 session_id.clone(),
7082 acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk {
7083 content: "onse".into(),
7084 meta: None,
7085 }),
7086 cx,
7087 );
7088 });
7089
7090 cx.run_until_parked();
7091
7092 // Last Message 1 response should appear before Message 2
7093 thread.read_with(cx, |thread, cx| {
7094 assert_eq!(
7095 thread.to_markdown(cx),
7096 indoc::indoc! {"
7097 ## User
7098
7099 Message 1
7100
7101 ## Assistant
7102
7103 Message 1 response
7104
7105 ## User
7106
7107 Message 2
7108
7109 "}
7110 )
7111 });
7112
7113 cx.update(|_, cx| {
7114 connection.send_update(
7115 session_id.clone(),
7116 acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk {
7117 content: "Message 2 response".into(),
7118 meta: None,
7119 }),
7120 cx,
7121 );
7122 connection.end_turn(session_id.clone(), acp::StopReason::EndTurn);
7123 });
7124
7125 cx.run_until_parked();
7126
7127 thread.read_with(cx, |thread, cx| {
7128 assert_eq!(
7129 thread.to_markdown(cx),
7130 indoc::indoc! {"
7131 ## User
7132
7133 Message 1
7134
7135 ## Assistant
7136
7137 Message 1 response
7138
7139 ## User
7140
7141 Message 2
7142
7143 ## Assistant
7144
7145 Message 2 response
7146
7147 "}
7148 )
7149 });
7150 }
7151
7152 #[gpui::test]
7153 async fn test_message_editing_insert_selections(cx: &mut TestAppContext) {
7154 init_test(cx);
7155
7156 let connection = StubAgentConnection::new();
7157 connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
7158 acp::ContentChunk {
7159 content: acp::ContentBlock::Text(acp::TextContent {
7160 text: "Response".into(),
7161 annotations: None,
7162 meta: None,
7163 }),
7164 meta: None,
7165 },
7166 )]);
7167
7168 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
7169 add_to_workspace(thread_view.clone(), cx);
7170
7171 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
7172 message_editor.update_in(cx, |editor, window, cx| {
7173 editor.set_text("Original message to edit", window, cx)
7174 });
7175 thread_view.update_in(cx, |thread_view, window, cx| thread_view.send(window, cx));
7176 cx.run_until_parked();
7177
7178 let user_message_editor = thread_view.read_with(cx, |thread_view, cx| {
7179 thread_view
7180 .entry_view_state
7181 .read(cx)
7182 .entry(0)
7183 .expect("Should have at least one entry")
7184 .message_editor()
7185 .expect("Should have message editor")
7186 .clone()
7187 });
7188
7189 cx.focus(&user_message_editor);
7190 thread_view.read_with(cx, |thread_view, _cx| {
7191 assert_eq!(thread_view.editing_message, Some(0));
7192 });
7193
7194 // Ensure to edit the focused message before proceeding otherwise, since
7195 // its content is not different from what was sent, focus will be lost.
7196 user_message_editor.update_in(cx, |editor, window, cx| {
7197 editor.set_text("Original message to edit with ", window, cx)
7198 });
7199
7200 // Create a simple buffer with some text so we can create a selection
7201 // that will then be added to the message being edited.
7202 let (workspace, project) = thread_view.read_with(cx, |thread_view, _cx| {
7203 (thread_view.workspace.clone(), thread_view.project.clone())
7204 });
7205 let buffer = project.update(cx, |project, cx| {
7206 project.create_local_buffer("let a = 10 + 10;", None, false, cx)
7207 });
7208
7209 workspace
7210 .update_in(cx, |workspace, window, cx| {
7211 let editor = cx.new(|cx| {
7212 let mut editor =
7213 Editor::for_buffer(buffer.clone(), Some(project.clone()), window, cx);
7214
7215 editor.change_selections(Default::default(), window, cx, |selections| {
7216 selections.select_ranges([8..15]);
7217 });
7218
7219 editor
7220 });
7221 workspace.add_item_to_active_pane(Box::new(editor), None, false, window, cx);
7222 })
7223 .unwrap();
7224
7225 thread_view.update_in(cx, |thread_view, window, cx| {
7226 assert_eq!(thread_view.editing_message, Some(0));
7227 thread_view.insert_selections(window, cx);
7228 });
7229
7230 user_message_editor.read_with(cx, |editor, cx| {
7231 let text = editor.editor().read(cx).text(cx);
7232 let expected_text = String::from("Original message to edit with selection ");
7233
7234 assert_eq!(text, expected_text);
7235 });
7236 }
7237
7238 #[gpui::test]
7239 async fn test_insert_selections(cx: &mut TestAppContext) {
7240 init_test(cx);
7241
7242 let connection = StubAgentConnection::new();
7243 connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
7244 acp::ContentChunk {
7245 content: acp::ContentBlock::Text(acp::TextContent {
7246 text: "Response".into(),
7247 annotations: None,
7248 meta: None,
7249 }),
7250 meta: None,
7251 },
7252 )]);
7253
7254 let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
7255 add_to_workspace(thread_view.clone(), cx);
7256
7257 let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
7258 message_editor.update_in(cx, |editor, window, cx| {
7259 editor.set_text("Can you review this snippet ", window, cx)
7260 });
7261
7262 // Create a simple buffer with some text so we can create a selection
7263 // that will then be added to the message being edited.
7264 let (workspace, project) = thread_view.read_with(cx, |thread_view, _cx| {
7265 (thread_view.workspace.clone(), thread_view.project.clone())
7266 });
7267 let buffer = project.update(cx, |project, cx| {
7268 project.create_local_buffer("let a = 10 + 10;", None, false, cx)
7269 });
7270
7271 workspace
7272 .update_in(cx, |workspace, window, cx| {
7273 let editor = cx.new(|cx| {
7274 let mut editor =
7275 Editor::for_buffer(buffer.clone(), Some(project.clone()), window, cx);
7276
7277 editor.change_selections(Default::default(), window, cx, |selections| {
7278 selections.select_ranges([8..15]);
7279 });
7280
7281 editor
7282 });
7283 workspace.add_item_to_active_pane(Box::new(editor), None, false, window, cx);
7284 })
7285 .unwrap();
7286
7287 thread_view.update_in(cx, |thread_view, window, cx| {
7288 assert_eq!(thread_view.editing_message, None);
7289 thread_view.insert_selections(window, cx);
7290 });
7291
7292 thread_view.read_with(cx, |thread_view, cx| {
7293 let text = thread_view.message_editor.read(cx).text(cx);
7294 let expected_txt = String::from("Can you review this snippet selection ");
7295
7296 assert_eq!(text, expected_txt);
7297 })
7298 }
7299}