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