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