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