thread_view.rs

   1use acp_thread::{
   2    AcpThread, AcpThreadEvent, AgentThreadEntry, AssistantMessage, AssistantMessageChunk,
   3    LoadError, MentionPath, ThreadStatus, ToolCall, ToolCallContent, ToolCallStatus,
   4};
   5use acp_thread::{AgentConnection, Plan};
   6use action_log::ActionLog;
   7use agent_client_protocol as acp;
   8use agent_servers::AgentServer;
   9use agent_settings::{AgentSettings, NotifyWhenAgentWaiting};
  10use audio::{Audio, Sound};
  11use buffer_diff::BufferDiff;
  12use collections::{HashMap, HashSet};
  13use editor::{
  14    AnchorRangeExt, ContextMenuOptions, ContextMenuPlacement, Editor, EditorElement, EditorMode,
  15    EditorStyle, MinimapVisibility, MultiBuffer, PathKey,
  16};
  17use file_icons::FileIcons;
  18use gpui::{
  19    Action, Animation, AnimationExt, App, BorderStyle, EdgesRefinement, Empty, Entity, EntityId,
  20    FocusHandle, Focusable, Hsla, Length, ListOffset, ListState, MouseButton, PlatformDisplay,
  21    SharedString, Stateful, StyleRefinement, Subscription, Task, TextStyle, TextStyleRefinement,
  22    Transformation, UnderlineStyle, WeakEntity, Window, WindowHandle, div, linear_color_stop,
  23    linear_gradient, list, percentage, point, prelude::*, pulsating_between,
  24};
  25use language::language_settings::SoftWrap;
  26use language::{Buffer, Language};
  27use markdown::{HeadingLevelStyles, Markdown, MarkdownElement, MarkdownStyle};
  28use parking_lot::Mutex;
  29use project::{CompletionIntent, Project};
  30use settings::{Settings as _, SettingsStore};
  31use std::{
  32    cell::RefCell, collections::BTreeMap, path::Path, process::ExitStatus, rc::Rc, sync::Arc,
  33    time::Duration,
  34};
  35use terminal_view::TerminalView;
  36use text::{Anchor, BufferSnapshot};
  37use theme::ThemeSettings;
  38use ui::{
  39    Disclosure, Divider, DividerColor, KeyBinding, Scrollbar, ScrollbarState, Tooltip, prelude::*,
  40};
  41use util::{ResultExt, size::format_file_size, time::duration_alt_display};
  42use workspace::{CollaboratorId, Workspace};
  43use zed_actions::agent::{Chat, NextHistoryMessage, PreviousHistoryMessage};
  44
  45use crate::acp::completion_provider::{ContextPickerCompletionProvider, MentionSet};
  46use crate::acp::message_history::MessageHistory;
  47use crate::agent_diff::AgentDiff;
  48use crate::message_editor::{MAX_EDITOR_LINES, MIN_EDITOR_LINES};
  49use crate::ui::{AgentNotification, AgentNotificationEvent};
  50use crate::{
  51    AgentDiffPane, AgentPanel, ExpandMessageEditor, Follow, KeepAll, OpenAgentDiff, RejectAll,
  52};
  53
  54const RESPONSE_PADDING_X: Pixels = px(19.);
  55
  56pub struct AcpThreadView {
  57    agent: Rc<dyn AgentServer>,
  58    workspace: WeakEntity<Workspace>,
  59    project: Entity<Project>,
  60    thread_state: ThreadState,
  61    diff_editors: HashMap<EntityId, Entity<Editor>>,
  62    terminal_views: HashMap<EntityId, Entity<TerminalView>>,
  63    message_editor: Entity<Editor>,
  64    message_set_from_history: Option<BufferSnapshot>,
  65    _message_editor_subscription: Subscription,
  66    mention_set: Arc<Mutex<MentionSet>>,
  67    notifications: Vec<WindowHandle<AgentNotification>>,
  68    notification_subscriptions: HashMap<WindowHandle<AgentNotification>, Vec<Subscription>>,
  69    last_error: Option<Entity<Markdown>>,
  70    list_state: ListState,
  71    scrollbar_state: ScrollbarState,
  72    auth_task: Option<Task<()>>,
  73    expanded_tool_calls: HashSet<acp::ToolCallId>,
  74    expanded_thinking_blocks: HashSet<(usize, usize)>,
  75    edits_expanded: bool,
  76    plan_expanded: bool,
  77    editor_expanded: bool,
  78    terminal_expanded: bool,
  79    message_history: Rc<RefCell<MessageHistory<Vec<acp::ContentBlock>>>>,
  80    _cancel_task: Option<Task<()>>,
  81    _subscriptions: [Subscription; 1],
  82}
  83
  84enum ThreadState {
  85    Loading {
  86        _task: Task<()>,
  87    },
  88    Ready {
  89        thread: Entity<AcpThread>,
  90        _subscription: [Subscription; 2],
  91    },
  92    LoadError(LoadError),
  93    Unauthenticated {
  94        connection: Rc<dyn AgentConnection>,
  95    },
  96    ServerExited {
  97        status: ExitStatus,
  98    },
  99}
 100
 101impl AcpThreadView {
 102    pub fn new(
 103        agent: Rc<dyn AgentServer>,
 104        workspace: WeakEntity<Workspace>,
 105        project: Entity<Project>,
 106        message_history: Rc<RefCell<MessageHistory<Vec<acp::ContentBlock>>>>,
 107        min_lines: usize,
 108        max_lines: Option<usize>,
 109        window: &mut Window,
 110        cx: &mut Context<Self>,
 111    ) -> Self {
 112        let language = Language::new(
 113            language::LanguageConfig {
 114                completion_query_characters: HashSet::from_iter(['.', '-', '_', '@']),
 115                ..Default::default()
 116            },
 117            None,
 118        );
 119
 120        let mention_set = Arc::new(Mutex::new(MentionSet::default()));
 121
 122        let message_editor = cx.new(|cx| {
 123            let buffer = cx.new(|cx| Buffer::local("", cx).with_language(Arc::new(language), cx));
 124            let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 125
 126            let mut editor = Editor::new(
 127                editor::EditorMode::AutoHeight {
 128                    min_lines,
 129                    max_lines: max_lines,
 130                },
 131                buffer,
 132                None,
 133                window,
 134                cx,
 135            );
 136            editor.set_placeholder_text("Message the agent - @ to include files", cx);
 137            editor.set_show_indent_guides(false, cx);
 138            editor.set_soft_wrap();
 139            editor.set_use_modal_editing(true);
 140            editor.set_completion_provider(Some(Rc::new(ContextPickerCompletionProvider::new(
 141                mention_set.clone(),
 142                workspace.clone(),
 143                cx.weak_entity(),
 144            ))));
 145            editor.set_context_menu_options(ContextMenuOptions {
 146                min_entries_visible: 12,
 147                max_entries_visible: 12,
 148                placement: Some(ContextMenuPlacement::Above),
 149            });
 150            editor
 151        });
 152
 153        let message_editor_subscription =
 154            cx.subscribe(&message_editor, |this, editor, event, cx| {
 155                if let editor::EditorEvent::BufferEdited = &event {
 156                    let buffer = editor
 157                        .read(cx)
 158                        .buffer()
 159                        .read(cx)
 160                        .as_singleton()
 161                        .unwrap()
 162                        .read(cx)
 163                        .snapshot();
 164                    if let Some(message) = this.message_set_from_history.clone()
 165                        && message.version() != buffer.version()
 166                    {
 167                        this.message_set_from_history = None;
 168                    }
 169
 170                    if this.message_set_from_history.is_none() {
 171                        this.message_history.borrow_mut().reset_position();
 172                    }
 173                }
 174            });
 175
 176        let mention_set = mention_set.clone();
 177
 178        let list_state = ListState::new(0, gpui::ListAlignment::Bottom, px(2048.0));
 179
 180        let subscription = cx.observe_global_in::<SettingsStore>(window, Self::settings_changed);
 181
 182        Self {
 183            agent: agent.clone(),
 184            workspace: workspace.clone(),
 185            project: project.clone(),
 186            thread_state: Self::initial_state(agent, workspace, project, window, cx),
 187            message_editor,
 188            message_set_from_history: None,
 189            _message_editor_subscription: message_editor_subscription,
 190            mention_set,
 191            notifications: Vec::new(),
 192            notification_subscriptions: HashMap::default(),
 193            diff_editors: Default::default(),
 194            terminal_views: Default::default(),
 195            list_state: list_state.clone(),
 196            scrollbar_state: ScrollbarState::new(list_state).parent_entity(&cx.entity()),
 197            last_error: None,
 198            auth_task: None,
 199            expanded_tool_calls: HashSet::default(),
 200            expanded_thinking_blocks: HashSet::default(),
 201            edits_expanded: false,
 202            plan_expanded: false,
 203            editor_expanded: false,
 204            terminal_expanded: true,
 205            message_history,
 206            _subscriptions: [subscription],
 207            _cancel_task: None,
 208        }
 209    }
 210
 211    fn initial_state(
 212        agent: Rc<dyn AgentServer>,
 213        workspace: WeakEntity<Workspace>,
 214        project: Entity<Project>,
 215        window: &mut Window,
 216        cx: &mut Context<Self>,
 217    ) -> ThreadState {
 218        let root_dir = project
 219            .read(cx)
 220            .visible_worktrees(cx)
 221            .next()
 222            .map(|worktree| worktree.read(cx).abs_path())
 223            .unwrap_or_else(|| paths::home_dir().as_path().into());
 224
 225        let connect_task = agent.connect(&root_dir, &project, cx);
 226        let load_task = cx.spawn_in(window, async move |this, cx| {
 227            let connection = match connect_task.await {
 228                Ok(connection) => connection,
 229                Err(err) => {
 230                    this.update(cx, |this, cx| {
 231                        this.handle_load_error(err, cx);
 232                        cx.notify();
 233                    })
 234                    .log_err();
 235                    return;
 236                }
 237            };
 238
 239            // this.update_in(cx, |_this, _window, cx| {
 240            //     let status = connection.exit_status(cx);
 241            //     cx.spawn(async move |this, cx| {
 242            //         let status = status.await.ok();
 243            //         this.update(cx, |this, cx| {
 244            //             this.thread_state = ThreadState::ServerExited { status };
 245            //             cx.notify();
 246            //         })
 247            //         .ok();
 248            //     })
 249            //     .detach();
 250            // })
 251            // .ok();
 252
 253            let result = match connection
 254                .clone()
 255                .new_thread(project.clone(), &root_dir, cx)
 256                .await
 257            {
 258                Err(e) => {
 259                    let mut cx = cx.clone();
 260                    if e.is::<acp_thread::AuthRequired>() {
 261                        this.update(&mut cx, |this, cx| {
 262                            this.thread_state = ThreadState::Unauthenticated { connection };
 263                            cx.notify();
 264                        })
 265                        .ok();
 266                        return;
 267                    } else {
 268                        Err(e)
 269                    }
 270                }
 271                Ok(session_id) => Ok(session_id),
 272            };
 273
 274            this.update_in(cx, |this, window, cx| {
 275                match result {
 276                    Ok(thread) => {
 277                        let thread_subscription =
 278                            cx.subscribe_in(&thread, window, Self::handle_thread_event);
 279
 280                        let action_log = thread.read(cx).action_log().clone();
 281                        let action_log_subscription =
 282                            cx.observe(&action_log, |_, _, cx| cx.notify());
 283
 284                        this.list_state
 285                            .splice(0..0, thread.read(cx).entries().len());
 286
 287                        AgentDiff::set_active_thread(&workspace, thread.clone(), window, cx);
 288
 289                        this.thread_state = ThreadState::Ready {
 290                            thread,
 291                            _subscription: [thread_subscription, action_log_subscription],
 292                        };
 293
 294                        cx.notify();
 295                    }
 296                    Err(err) => {
 297                        this.handle_load_error(err, cx);
 298                    }
 299                };
 300            })
 301            .log_err();
 302        });
 303
 304        ThreadState::Loading { _task: load_task }
 305    }
 306
 307    fn handle_load_error(&mut self, err: anyhow::Error, cx: &mut Context<Self>) {
 308        if let Some(load_err) = err.downcast_ref::<LoadError>() {
 309            self.thread_state = ThreadState::LoadError(load_err.clone());
 310        } else {
 311            self.thread_state = ThreadState::LoadError(LoadError::Other(err.to_string().into()))
 312        }
 313        cx.notify();
 314    }
 315
 316    pub fn thread(&self) -> Option<&Entity<AcpThread>> {
 317        match &self.thread_state {
 318            ThreadState::Ready { thread, .. } => Some(thread),
 319            ThreadState::Unauthenticated { .. }
 320            | ThreadState::Loading { .. }
 321            | ThreadState::LoadError(..)
 322            | ThreadState::ServerExited { .. } => None,
 323        }
 324    }
 325
 326    pub fn title(&self, cx: &App) -> SharedString {
 327        match &self.thread_state {
 328            ThreadState::Ready { thread, .. } => thread.read(cx).title(),
 329            ThreadState::Loading { .. } => "Loading…".into(),
 330            ThreadState::LoadError(_) => "Failed to load".into(),
 331            ThreadState::Unauthenticated { .. } => "Not authenticated".into(),
 332            ThreadState::ServerExited { .. } => "Server exited unexpectedly".into(),
 333        }
 334    }
 335
 336    pub fn cancel(&mut self, cx: &mut Context<Self>) {
 337        self.last_error.take();
 338
 339        if let Some(thread) = self.thread() {
 340            self._cancel_task = Some(thread.update(cx, |thread, cx| thread.cancel(cx)));
 341        }
 342    }
 343
 344    pub fn expand_message_editor(
 345        &mut self,
 346        _: &ExpandMessageEditor,
 347        _window: &mut Window,
 348        cx: &mut Context<Self>,
 349    ) {
 350        self.set_editor_is_expanded(!self.editor_expanded, cx);
 351        cx.notify();
 352    }
 353
 354    fn set_editor_is_expanded(&mut self, is_expanded: bool, cx: &mut Context<Self>) {
 355        self.editor_expanded = is_expanded;
 356        self.message_editor.update(cx, |editor, _| {
 357            if self.editor_expanded {
 358                editor.set_mode(EditorMode::Full {
 359                    scale_ui_elements_with_buffer_font_size: false,
 360                    show_active_line_background: false,
 361                    sized_by_content: false,
 362                })
 363            } else {
 364                editor.set_mode(EditorMode::AutoHeight {
 365                    min_lines: MIN_EDITOR_LINES,
 366                    max_lines: Some(MAX_EDITOR_LINES),
 367                })
 368            }
 369        });
 370        cx.notify();
 371    }
 372
 373    fn chat(&mut self, _: &Chat, window: &mut Window, cx: &mut Context<Self>) {
 374        self.last_error.take();
 375
 376        let mut ix = 0;
 377        let mut chunks: Vec<acp::ContentBlock> = Vec::new();
 378        let project = self.project.clone();
 379        self.message_editor.update(cx, |editor, cx| {
 380            let text = editor.text(cx);
 381            editor.display_map.update(cx, |map, cx| {
 382                let snapshot = map.snapshot(cx);
 383                for (crease_id, crease) in snapshot.crease_snapshot.creases() {
 384                    // Skip creases that have been edited out of the message buffer.
 385                    if !crease.range().start.is_valid(&snapshot.buffer_snapshot) {
 386                        continue;
 387                    }
 388
 389                    if let Some(project_path) =
 390                        self.mention_set.lock().path_for_crease_id(crease_id)
 391                    {
 392                        let crease_range = crease.range().to_offset(&snapshot.buffer_snapshot);
 393                        if crease_range.start > ix {
 394                            chunks.push(text[ix..crease_range.start].into());
 395                        }
 396                        if let Some(abs_path) = project.read(cx).absolute_path(&project_path, cx) {
 397                            let path_str = abs_path.display().to_string();
 398                            chunks.push(acp::ContentBlock::ResourceLink(acp::ResourceLink {
 399                                uri: path_str.clone(),
 400                                name: path_str,
 401                                annotations: None,
 402                                description: None,
 403                                mime_type: None,
 404                                size: None,
 405                                title: None,
 406                            }));
 407                        }
 408                        ix = crease_range.end;
 409                    }
 410                }
 411
 412                if ix < text.len() {
 413                    let last_chunk = text[ix..].trim_end();
 414                    if !last_chunk.is_empty() {
 415                        chunks.push(last_chunk.into());
 416                    }
 417                }
 418            })
 419        });
 420
 421        if chunks.is_empty() {
 422            return;
 423        }
 424
 425        let Some(thread) = self.thread() else {
 426            return;
 427        };
 428        let task = thread.update(cx, |thread, cx| thread.send(chunks.clone(), cx));
 429
 430        cx.spawn(async move |this, cx| {
 431            let result = task.await;
 432
 433            this.update(cx, |this, cx| {
 434                if let Err(err) = result {
 435                    this.last_error =
 436                        Some(cx.new(|cx| Markdown::new(err.to_string().into(), None, None, cx)))
 437                }
 438            })
 439        })
 440        .detach();
 441
 442        let mention_set = self.mention_set.clone();
 443
 444        self.set_editor_is_expanded(false, cx);
 445
 446        self.message_editor.update(cx, |editor, cx| {
 447            editor.clear(window, cx);
 448            editor.remove_creases(mention_set.lock().drain(), cx)
 449        });
 450
 451        self.scroll_to_bottom(cx);
 452
 453        self.message_history.borrow_mut().push(chunks);
 454    }
 455
 456    fn previous_history_message(
 457        &mut self,
 458        _: &PreviousHistoryMessage,
 459        window: &mut Window,
 460        cx: &mut Context<Self>,
 461    ) {
 462        if self.message_set_from_history.is_none() && !self.message_editor.read(cx).is_empty(cx) {
 463            self.message_editor.update(cx, |editor, cx| {
 464                editor.move_up(&Default::default(), window, cx);
 465            });
 466            return;
 467        }
 468
 469        self.message_set_from_history = Self::set_draft_message(
 470            self.message_editor.clone(),
 471            self.mention_set.clone(),
 472            self.project.clone(),
 473            self.message_history
 474                .borrow_mut()
 475                .prev()
 476                .map(|blocks| blocks.as_slice()),
 477            window,
 478            cx,
 479        );
 480    }
 481
 482    fn next_history_message(
 483        &mut self,
 484        _: &NextHistoryMessage,
 485        window: &mut Window,
 486        cx: &mut Context<Self>,
 487    ) {
 488        if self.message_set_from_history.is_none() {
 489            self.message_editor.update(cx, |editor, cx| {
 490                editor.move_down(&Default::default(), window, cx);
 491            });
 492            return;
 493        }
 494
 495        let mut message_history = self.message_history.borrow_mut();
 496        let next_history = message_history.next();
 497
 498        let set_draft_message = Self::set_draft_message(
 499            self.message_editor.clone(),
 500            self.mention_set.clone(),
 501            self.project.clone(),
 502            Some(
 503                next_history
 504                    .map(|blocks| blocks.as_slice())
 505                    .unwrap_or_else(|| &[]),
 506            ),
 507            window,
 508            cx,
 509        );
 510        // If we reset the text to an empty string because we ran out of history,
 511        // we don't want to mark it as coming from the history
 512        self.message_set_from_history = if next_history.is_some() {
 513            set_draft_message
 514        } else {
 515            None
 516        };
 517    }
 518
 519    fn open_agent_diff(&mut self, _: &OpenAgentDiff, window: &mut Window, cx: &mut Context<Self>) {
 520        if let Some(thread) = self.thread() {
 521            AgentDiffPane::deploy(thread.clone(), self.workspace.clone(), window, cx).log_err();
 522        }
 523    }
 524
 525    fn open_edited_buffer(
 526        &mut self,
 527        buffer: &Entity<Buffer>,
 528        window: &mut Window,
 529        cx: &mut Context<Self>,
 530    ) {
 531        let Some(thread) = self.thread() else {
 532            return;
 533        };
 534
 535        let Some(diff) =
 536            AgentDiffPane::deploy(thread.clone(), self.workspace.clone(), window, cx).log_err()
 537        else {
 538            return;
 539        };
 540
 541        diff.update(cx, |diff, cx| {
 542            diff.move_to_path(PathKey::for_buffer(&buffer, cx), window, cx)
 543        })
 544    }
 545
 546    fn set_draft_message(
 547        message_editor: Entity<Editor>,
 548        mention_set: Arc<Mutex<MentionSet>>,
 549        project: Entity<Project>,
 550        message: Option<&[acp::ContentBlock]>,
 551        window: &mut Window,
 552        cx: &mut Context<Self>,
 553    ) -> Option<BufferSnapshot> {
 554        cx.notify();
 555
 556        let message = message?;
 557
 558        let mut text = String::new();
 559        let mut mentions = Vec::new();
 560
 561        for chunk in message {
 562            match chunk {
 563                acp::ContentBlock::Text(text_content) => {
 564                    text.push_str(&text_content.text);
 565                }
 566                acp::ContentBlock::ResourceLink(resource_link) => {
 567                    let path = Path::new(&resource_link.uri);
 568                    let start = text.len();
 569                    let content = MentionPath::new(&path).to_string();
 570                    text.push_str(&content);
 571                    let end = text.len();
 572                    if let Some(project_path) =
 573                        project.read(cx).project_path_for_absolute_path(&path, cx)
 574                    {
 575                        let filename: SharedString = path
 576                            .file_name()
 577                            .unwrap_or_default()
 578                            .to_string_lossy()
 579                            .to_string()
 580                            .into();
 581                        mentions.push((start..end, project_path, filename));
 582                    }
 583                }
 584                acp::ContentBlock::Image(_)
 585                | acp::ContentBlock::Audio(_)
 586                | acp::ContentBlock::Resource(_) => {}
 587            }
 588        }
 589
 590        let snapshot = message_editor.update(cx, |editor, cx| {
 591            editor.set_text(text, window, cx);
 592            editor.buffer().read(cx).snapshot(cx)
 593        });
 594
 595        for (range, project_path, filename) in mentions {
 596            let crease_icon_path = if project_path.path.is_dir() {
 597                FileIcons::get_folder_icon(false, cx)
 598                    .unwrap_or_else(|| IconName::Folder.path().into())
 599            } else {
 600                FileIcons::get_icon(Path::new(project_path.path.as_ref()), cx)
 601                    .unwrap_or_else(|| IconName::File.path().into())
 602            };
 603
 604            let anchor = snapshot.anchor_before(range.start);
 605            let crease_id = crate::context_picker::insert_crease_for_mention(
 606                anchor.excerpt_id,
 607                anchor.text_anchor,
 608                range.end - range.start,
 609                filename,
 610                crease_icon_path,
 611                message_editor.clone(),
 612                window,
 613                cx,
 614            );
 615            if let Some(crease_id) = crease_id {
 616                mention_set.lock().insert(crease_id, project_path);
 617            }
 618        }
 619
 620        let snapshot = snapshot.as_singleton().unwrap().2.clone();
 621        Some(snapshot.text)
 622    }
 623
 624    fn handle_thread_event(
 625        &mut self,
 626        thread: &Entity<AcpThread>,
 627        event: &AcpThreadEvent,
 628        window: &mut Window,
 629        cx: &mut Context<Self>,
 630    ) {
 631        let count = self.list_state.item_count();
 632        match event {
 633            AcpThreadEvent::NewEntry => {
 634                let index = thread.read(cx).entries().len() - 1;
 635                self.sync_thread_entry_view(index, window, cx);
 636                self.list_state.splice(count..count, 1);
 637            }
 638            AcpThreadEvent::EntryUpdated(index) => {
 639                let index = *index;
 640                self.sync_thread_entry_view(index, window, cx);
 641                self.list_state.splice(index..index + 1, 1);
 642            }
 643            AcpThreadEvent::ToolAuthorizationRequired => {
 644                self.notify_with_sound("Waiting for tool confirmation", IconName::Info, window, cx);
 645            }
 646            AcpThreadEvent::Stopped => {
 647                let used_tools = thread.read(cx).used_tools_since_last_user_message();
 648                self.notify_with_sound(
 649                    if used_tools {
 650                        "Finished running tools"
 651                    } else {
 652                        "New message"
 653                    },
 654                    IconName::ZedAssistant,
 655                    window,
 656                    cx,
 657                );
 658            }
 659            AcpThreadEvent::Error => {
 660                self.notify_with_sound(
 661                    "Agent stopped due to an error",
 662                    IconName::Warning,
 663                    window,
 664                    cx,
 665                );
 666            }
 667            AcpThreadEvent::ServerExited(status) => {
 668                self.thread_state = ThreadState::ServerExited { status: *status };
 669            }
 670        }
 671        cx.notify();
 672    }
 673
 674    fn sync_thread_entry_view(
 675        &mut self,
 676        entry_ix: usize,
 677        window: &mut Window,
 678        cx: &mut Context<Self>,
 679    ) {
 680        self.sync_diff_multibuffers(entry_ix, window, cx);
 681        self.sync_terminals(entry_ix, window, cx);
 682    }
 683
 684    fn sync_diff_multibuffers(
 685        &mut self,
 686        entry_ix: usize,
 687        window: &mut Window,
 688        cx: &mut Context<Self>,
 689    ) {
 690        let Some(multibuffers) = self.entry_diff_multibuffers(entry_ix, cx) else {
 691            return;
 692        };
 693
 694        let multibuffers = multibuffers.collect::<Vec<_>>();
 695
 696        for multibuffer in multibuffers {
 697            if self.diff_editors.contains_key(&multibuffer.entity_id()) {
 698                return;
 699            }
 700
 701            let editor = cx.new(|cx| {
 702                let mut editor = Editor::new(
 703                    EditorMode::Full {
 704                        scale_ui_elements_with_buffer_font_size: false,
 705                        show_active_line_background: false,
 706                        sized_by_content: true,
 707                    },
 708                    multibuffer.clone(),
 709                    None,
 710                    window,
 711                    cx,
 712                );
 713                editor.set_show_gutter(false, cx);
 714                editor.disable_inline_diagnostics();
 715                editor.disable_expand_excerpt_buttons(cx);
 716                editor.set_show_vertical_scrollbar(false, cx);
 717                editor.set_minimap_visibility(MinimapVisibility::Disabled, window, cx);
 718                editor.set_soft_wrap_mode(SoftWrap::None, cx);
 719                editor.scroll_manager.set_forbid_vertical_scroll(true);
 720                editor.set_show_indent_guides(false, cx);
 721                editor.set_read_only(true);
 722                editor.set_show_breakpoints(false, cx);
 723                editor.set_show_code_actions(false, cx);
 724                editor.set_show_git_diff_gutter(false, cx);
 725                editor.set_expand_all_diff_hunks(cx);
 726                editor.set_text_style_refinement(diff_editor_text_style_refinement(cx));
 727                editor
 728            });
 729            let entity_id = multibuffer.entity_id();
 730            cx.observe_release(&multibuffer, move |this, _, _| {
 731                this.diff_editors.remove(&entity_id);
 732            })
 733            .detach();
 734
 735            self.diff_editors.insert(entity_id, editor);
 736        }
 737    }
 738
 739    fn entry_diff_multibuffers(
 740        &self,
 741        entry_ix: usize,
 742        cx: &App,
 743    ) -> Option<impl Iterator<Item = Entity<MultiBuffer>>> {
 744        let entry = self.thread()?.read(cx).entries().get(entry_ix)?;
 745        Some(
 746            entry
 747                .diffs()
 748                .map(|diff| diff.read(cx).multibuffer().clone()),
 749        )
 750    }
 751
 752    fn sync_terminals(&mut self, entry_ix: usize, window: &mut Window, cx: &mut Context<Self>) {
 753        let Some(terminals) = self.entry_terminals(entry_ix, cx) else {
 754            return;
 755        };
 756
 757        let terminals = terminals.collect::<Vec<_>>();
 758
 759        for terminal in terminals {
 760            if self.terminal_views.contains_key(&terminal.entity_id()) {
 761                return;
 762            }
 763
 764            let terminal_view = cx.new(|cx| {
 765                let mut view = TerminalView::new(
 766                    terminal.read(cx).inner().clone(),
 767                    self.workspace.clone(),
 768                    None,
 769                    self.project.downgrade(),
 770                    window,
 771                    cx,
 772                );
 773                view.set_embedded_mode(Some(1000), cx);
 774                view
 775            });
 776
 777            let entity_id = terminal.entity_id();
 778            cx.observe_release(&terminal, move |this, _, _| {
 779                this.terminal_views.remove(&entity_id);
 780            })
 781            .detach();
 782
 783            self.terminal_views.insert(entity_id, terminal_view);
 784        }
 785    }
 786
 787    fn entry_terminals(
 788        &self,
 789        entry_ix: usize,
 790        cx: &App,
 791    ) -> Option<impl Iterator<Item = Entity<acp_thread::Terminal>>> {
 792        let entry = self.thread()?.read(cx).entries().get(entry_ix)?;
 793        Some(entry.terminals().map(|terminal| terminal.clone()))
 794    }
 795
 796    fn authenticate(
 797        &mut self,
 798        method: acp::AuthMethodId,
 799        window: &mut Window,
 800        cx: &mut Context<Self>,
 801    ) {
 802        let ThreadState::Unauthenticated { ref connection } = self.thread_state else {
 803            return;
 804        };
 805
 806        self.last_error.take();
 807        let authenticate = connection.authenticate(method, cx);
 808        self.auth_task = Some(cx.spawn_in(window, {
 809            let project = self.project.clone();
 810            let agent = self.agent.clone();
 811            async move |this, cx| {
 812                let result = authenticate.await;
 813
 814                this.update_in(cx, |this, window, cx| {
 815                    if let Err(err) = result {
 816                        this.last_error = Some(cx.new(|cx| {
 817                            Markdown::new(format!("Error: {err}").into(), None, None, cx)
 818                        }))
 819                    } else {
 820                        this.thread_state = Self::initial_state(
 821                            agent,
 822                            this.workspace.clone(),
 823                            project.clone(),
 824                            window,
 825                            cx,
 826                        )
 827                    }
 828                    this.auth_task.take()
 829                })
 830                .ok();
 831            }
 832        }));
 833    }
 834
 835    fn authorize_tool_call(
 836        &mut self,
 837        tool_call_id: acp::ToolCallId,
 838        option_id: acp::PermissionOptionId,
 839        option_kind: acp::PermissionOptionKind,
 840        cx: &mut Context<Self>,
 841    ) {
 842        let Some(thread) = self.thread() else {
 843            return;
 844        };
 845        thread.update(cx, |thread, cx| {
 846            thread.authorize_tool_call(tool_call_id, option_id, option_kind, cx);
 847        });
 848        cx.notify();
 849    }
 850
 851    fn render_entry(
 852        &self,
 853        index: usize,
 854        total_entries: usize,
 855        entry: &AgentThreadEntry,
 856        window: &mut Window,
 857        cx: &Context<Self>,
 858    ) -> AnyElement {
 859        let primary = match &entry {
 860            AgentThreadEntry::UserMessage(message) => div()
 861                .py_4()
 862                .px_2()
 863                .child(
 864                    v_flex()
 865                        .p_3()
 866                        .gap_1p5()
 867                        .rounded_lg()
 868                        .shadow_md()
 869                        .bg(cx.theme().colors().editor_background)
 870                        .border_1()
 871                        .border_color(cx.theme().colors().border)
 872                        .text_xs()
 873                        .children(message.content.markdown().map(|md| {
 874                            self.render_markdown(
 875                                md.clone(),
 876                                user_message_markdown_style(window, cx),
 877                            )
 878                        })),
 879                )
 880                .into_any(),
 881            AgentThreadEntry::AssistantMessage(AssistantMessage { chunks }) => {
 882                let style = default_markdown_style(false, window, cx);
 883                let message_body = v_flex()
 884                    .w_full()
 885                    .gap_2p5()
 886                    .children(chunks.iter().enumerate().filter_map(
 887                        |(chunk_ix, chunk)| match chunk {
 888                            AssistantMessageChunk::Message { block } => {
 889                                block.markdown().map(|md| {
 890                                    self.render_markdown(md.clone(), style.clone())
 891                                        .into_any_element()
 892                                })
 893                            }
 894                            AssistantMessageChunk::Thought { block } => {
 895                                block.markdown().map(|md| {
 896                                    self.render_thinking_block(
 897                                        index,
 898                                        chunk_ix,
 899                                        md.clone(),
 900                                        window,
 901                                        cx,
 902                                    )
 903                                    .into_any_element()
 904                                })
 905                            }
 906                        },
 907                    ))
 908                    .into_any();
 909
 910                v_flex()
 911                    .px_5()
 912                    .py_1()
 913                    .when(index + 1 == total_entries, |this| this.pb_4())
 914                    .w_full()
 915                    .text_ui(cx)
 916                    .child(message_body)
 917                    .into_any()
 918            }
 919            AgentThreadEntry::ToolCall(tool_call) => {
 920                let has_terminals = tool_call.terminals().next().is_some();
 921
 922                div().w_full().py_1p5().px_5().map(|this| {
 923                    if has_terminals {
 924                        this.children(tool_call.terminals().map(|terminal| {
 925                            self.render_terminal_tool_call(terminal, tool_call, window, cx)
 926                        }))
 927                    } else {
 928                        this.child(self.render_tool_call(index, tool_call, window, cx))
 929                    }
 930                })
 931            }
 932            .into_any(),
 933        };
 934
 935        let Some(thread) = self.thread() else {
 936            return primary;
 937        };
 938
 939        let is_generating = matches!(thread.read(cx).status(), ThreadStatus::Generating);
 940        if index == total_entries - 1 && !is_generating {
 941            v_flex()
 942                .w_full()
 943                .child(primary)
 944                .child(self.render_thread_controls(cx))
 945                .into_any_element()
 946        } else {
 947            primary
 948        }
 949    }
 950
 951    fn tool_card_header_bg(&self, cx: &Context<Self>) -> Hsla {
 952        cx.theme()
 953            .colors()
 954            .element_background
 955            .blend(cx.theme().colors().editor_foreground.opacity(0.025))
 956    }
 957
 958    fn tool_card_border_color(&self, cx: &Context<Self>) -> Hsla {
 959        cx.theme().colors().border.opacity(0.6)
 960    }
 961
 962    fn tool_name_font_size(&self) -> Rems {
 963        rems_from_px(13.)
 964    }
 965
 966    fn render_thinking_block(
 967        &self,
 968        entry_ix: usize,
 969        chunk_ix: usize,
 970        chunk: Entity<Markdown>,
 971        window: &Window,
 972        cx: &Context<Self>,
 973    ) -> AnyElement {
 974        let header_id = SharedString::from(format!("thinking-block-header-{}", entry_ix));
 975        let card_header_id = SharedString::from("inner-card-header");
 976        let key = (entry_ix, chunk_ix);
 977        let is_open = self.expanded_thinking_blocks.contains(&key);
 978
 979        v_flex()
 980            .child(
 981                h_flex()
 982                    .id(header_id)
 983                    .group(&card_header_id)
 984                    .relative()
 985                    .w_full()
 986                    .gap_1p5()
 987                    .opacity(0.8)
 988                    .hover(|style| style.opacity(1.))
 989                    .child(
 990                        h_flex()
 991                            .size_4()
 992                            .justify_center()
 993                            .child(
 994                                div()
 995                                    .group_hover(&card_header_id, |s| s.invisible().w_0())
 996                                    .child(
 997                                        Icon::new(IconName::ToolThink)
 998                                            .size(IconSize::Small)
 999                                            .color(Color::Muted),
1000                                    ),
1001                            )
1002                            .child(
1003                                h_flex()
1004                                    .absolute()
1005                                    .inset_0()
1006                                    .invisible()
1007                                    .justify_center()
1008                                    .group_hover(&card_header_id, |s| s.visible())
1009                                    .child(
1010                                        Disclosure::new(("expand", entry_ix), is_open)
1011                                            .opened_icon(IconName::ChevronUp)
1012                                            .closed_icon(IconName::ChevronRight)
1013                                            .on_click(cx.listener({
1014                                                move |this, _event, _window, cx| {
1015                                                    if is_open {
1016                                                        this.expanded_thinking_blocks.remove(&key);
1017                                                    } else {
1018                                                        this.expanded_thinking_blocks.insert(key);
1019                                                    }
1020                                                    cx.notify();
1021                                                }
1022                                            })),
1023                                    ),
1024                            ),
1025                    )
1026                    .child(
1027                        div()
1028                            .text_size(self.tool_name_font_size())
1029                            .child("Thinking"),
1030                    )
1031                    .on_click(cx.listener({
1032                        move |this, _event, _window, cx| {
1033                            if is_open {
1034                                this.expanded_thinking_blocks.remove(&key);
1035                            } else {
1036                                this.expanded_thinking_blocks.insert(key);
1037                            }
1038                            cx.notify();
1039                        }
1040                    })),
1041            )
1042            .when(is_open, |this| {
1043                this.child(
1044                    div()
1045                        .relative()
1046                        .mt_1p5()
1047                        .ml(px(7.))
1048                        .pl_4()
1049                        .border_l_1()
1050                        .border_color(self.tool_card_border_color(cx))
1051                        .text_ui_sm(cx)
1052                        .child(
1053                            self.render_markdown(chunk, default_markdown_style(false, window, cx)),
1054                        ),
1055                )
1056            })
1057            .into_any_element()
1058    }
1059
1060    fn render_tool_call_icon(
1061        &self,
1062        group_name: SharedString,
1063        entry_ix: usize,
1064        is_collapsible: bool,
1065        is_open: bool,
1066        tool_call: &ToolCall,
1067        cx: &Context<Self>,
1068    ) -> Div {
1069        let tool_icon = Icon::new(match tool_call.kind {
1070            acp::ToolKind::Read => IconName::ToolRead,
1071            acp::ToolKind::Edit => IconName::ToolPencil,
1072            acp::ToolKind::Delete => IconName::ToolDeleteFile,
1073            acp::ToolKind::Move => IconName::ArrowRightLeft,
1074            acp::ToolKind::Search => IconName::ToolSearch,
1075            acp::ToolKind::Execute => IconName::ToolTerminal,
1076            acp::ToolKind::Think => IconName::ToolThink,
1077            acp::ToolKind::Fetch => IconName::ToolWeb,
1078            acp::ToolKind::Other => IconName::ToolHammer,
1079        })
1080        .size(IconSize::Small)
1081        .color(Color::Muted);
1082
1083        if is_collapsible {
1084            h_flex()
1085                .size_4()
1086                .justify_center()
1087                .child(
1088                    div()
1089                        .group_hover(&group_name, |s| s.invisible().w_0())
1090                        .child(tool_icon),
1091                )
1092                .child(
1093                    h_flex()
1094                        .absolute()
1095                        .inset_0()
1096                        .invisible()
1097                        .justify_center()
1098                        .group_hover(&group_name, |s| s.visible())
1099                        .child(
1100                            Disclosure::new(("expand", entry_ix), is_open)
1101                                .opened_icon(IconName::ChevronUp)
1102                                .closed_icon(IconName::ChevronRight)
1103                                .on_click(cx.listener({
1104                                    let id = tool_call.id.clone();
1105                                    move |this: &mut Self, _, _, cx: &mut Context<Self>| {
1106                                        if is_open {
1107                                            this.expanded_tool_calls.remove(&id);
1108                                        } else {
1109                                            this.expanded_tool_calls.insert(id.clone());
1110                                        }
1111                                        cx.notify();
1112                                    }
1113                                })),
1114                        ),
1115                )
1116        } else {
1117            div().child(tool_icon)
1118        }
1119    }
1120
1121    fn render_tool_call(
1122        &self,
1123        entry_ix: usize,
1124        tool_call: &ToolCall,
1125        window: &Window,
1126        cx: &Context<Self>,
1127    ) -> Div {
1128        let header_id = SharedString::from(format!("outer-tool-call-header-{}", entry_ix));
1129        let card_header_id = SharedString::from("inner-tool-call-header");
1130
1131        let status_icon = match &tool_call.status {
1132            ToolCallStatus::Allowed {
1133                status: acp::ToolCallStatus::Pending,
1134            }
1135            | ToolCallStatus::WaitingForConfirmation { .. } => None,
1136            ToolCallStatus::Allowed {
1137                status: acp::ToolCallStatus::InProgress,
1138                ..
1139            } => Some(
1140                Icon::new(IconName::ArrowCircle)
1141                    .color(Color::Accent)
1142                    .size(IconSize::Small)
1143                    .with_animation(
1144                        "running",
1145                        Animation::new(Duration::from_secs(2)).repeat(),
1146                        |icon, delta| icon.transform(Transformation::rotate(percentage(delta))),
1147                    )
1148                    .into_any(),
1149            ),
1150            ToolCallStatus::Allowed {
1151                status: acp::ToolCallStatus::Completed,
1152                ..
1153            } => None,
1154            ToolCallStatus::Rejected
1155            | ToolCallStatus::Canceled
1156            | ToolCallStatus::Allowed {
1157                status: acp::ToolCallStatus::Failed,
1158                ..
1159            } => Some(
1160                Icon::new(IconName::Close)
1161                    .color(Color::Error)
1162                    .size(IconSize::Small)
1163                    .into_any_element(),
1164            ),
1165        };
1166
1167        let needs_confirmation = matches!(
1168            tool_call.status,
1169            ToolCallStatus::WaitingForConfirmation { .. }
1170        );
1171        let is_edit = matches!(tool_call.kind, acp::ToolKind::Edit);
1172        let has_diff = tool_call
1173            .content
1174            .iter()
1175            .any(|content| matches!(content, ToolCallContent::Diff { .. }));
1176        let has_nonempty_diff = tool_call.content.iter().any(|content| match content {
1177            ToolCallContent::Diff(diff) => diff.read(cx).has_revealed_range(cx),
1178            _ => false,
1179        });
1180        let is_collapsible =
1181            !tool_call.content.is_empty() && !needs_confirmation && !is_edit && !has_diff;
1182        let is_open = tool_call.content.is_empty()
1183            || needs_confirmation
1184            || has_nonempty_diff
1185            || self.expanded_tool_calls.contains(&tool_call.id);
1186
1187        let gradient_overlay = |color: Hsla| {
1188            div()
1189                .absolute()
1190                .top_0()
1191                .right_0()
1192                .w_12()
1193                .h_full()
1194                .bg(linear_gradient(
1195                    90.,
1196                    linear_color_stop(color, 1.),
1197                    linear_color_stop(color.opacity(0.2), 0.),
1198                ))
1199        };
1200
1201        v_flex()
1202            .when(needs_confirmation || is_edit || has_diff, |this| {
1203                this.rounded_lg()
1204                    .border_1()
1205                    .border_color(self.tool_card_border_color(cx))
1206                    .bg(cx.theme().colors().editor_background)
1207                    .overflow_hidden()
1208            })
1209            .child(
1210                h_flex()
1211                    .id(header_id)
1212                    .w_full()
1213                    .gap_1()
1214                    .justify_between()
1215                    .map(|this| {
1216                        if needs_confirmation || is_edit || has_diff {
1217                            this.pl_2()
1218                                .pr_1()
1219                                .py_1()
1220                                .rounded_t_md()
1221                                .border_b_1()
1222                                .border_color(self.tool_card_border_color(cx))
1223                                .bg(self.tool_card_header_bg(cx))
1224                        } else {
1225                            this.opacity(0.8).hover(|style| style.opacity(1.))
1226                        }
1227                    })
1228                    .child(
1229                        h_flex()
1230                            .group(&card_header_id)
1231                            .relative()
1232                            .w_full()
1233                            .map(|this| {
1234                                if tool_call.locations.len() == 1 {
1235                                    this.gap_0()
1236                                } else {
1237                                    this.gap_1p5()
1238                                }
1239                            })
1240                            .text_size(self.tool_name_font_size())
1241                            .child(self.render_tool_call_icon(
1242                                card_header_id,
1243                                entry_ix,
1244                                is_collapsible,
1245                                is_open,
1246                                tool_call,
1247                                cx,
1248                            ))
1249                            .child(if tool_call.locations.len() == 1 {
1250                                let name = tool_call.locations[0]
1251                                    .path
1252                                    .file_name()
1253                                    .unwrap_or_default()
1254                                    .display()
1255                                    .to_string();
1256
1257                                h_flex()
1258                                    .id(("open-tool-call-location", entry_ix))
1259                                    .w_full()
1260                                    .max_w_full()
1261                                    .px_1p5()
1262                                    .rounded_sm()
1263                                    .overflow_x_scroll()
1264                                    .opacity(0.8)
1265                                    .hover(|label| {
1266                                        label.opacity(1.).bg(cx
1267                                            .theme()
1268                                            .colors()
1269                                            .element_hover
1270                                            .opacity(0.5))
1271                                    })
1272                                    .child(name)
1273                                    .tooltip(Tooltip::text("Jump to File"))
1274                                    .on_click(cx.listener(move |this, _, window, cx| {
1275                                        this.open_tool_call_location(entry_ix, 0, window, cx);
1276                                    }))
1277                                    .into_any_element()
1278                            } else {
1279                                h_flex()
1280                                    .id("non-card-label-container")
1281                                    .w_full()
1282                                    .relative()
1283                                    .overflow_hidden()
1284                                    .child(
1285                                        h_flex()
1286                                            .id("non-card-label")
1287                                            .pr_8()
1288                                            .w_full()
1289                                            .overflow_x_scroll()
1290                                            .child(self.render_markdown(
1291                                                tool_call.label.clone(),
1292                                                default_markdown_style(
1293                                                    needs_confirmation || is_edit || has_diff,
1294                                                    window,
1295                                                    cx,
1296                                                ),
1297                                            )),
1298                                    )
1299                                    .map(|this| {
1300                                        if needs_confirmation {
1301                                            this.child(gradient_overlay(
1302                                                self.tool_card_header_bg(cx),
1303                                            ))
1304                                        } else {
1305                                            this.child(gradient_overlay(
1306                                                cx.theme().colors().panel_background,
1307                                            ))
1308                                        }
1309                                    })
1310                                    .on_click(cx.listener({
1311                                        let id = tool_call.id.clone();
1312                                        move |this: &mut Self, _, _, cx: &mut Context<Self>| {
1313                                            if is_open {
1314                                                this.expanded_tool_calls.remove(&id);
1315                                            } else {
1316                                                this.expanded_tool_calls.insert(id.clone());
1317                                            }
1318                                            cx.notify();
1319                                        }
1320                                    }))
1321                                    .into_any()
1322                            }),
1323                    )
1324                    .children(status_icon),
1325            )
1326            .when(is_open, |this| {
1327                this.child(
1328                    v_flex()
1329                        .text_xs()
1330                        .when(is_collapsible, |this| {
1331                            this.mt_1()
1332                                .border_1()
1333                                .border_color(self.tool_card_border_color(cx))
1334                                .bg(cx.theme().colors().editor_background)
1335                                .rounded_lg()
1336                        })
1337                        .map(|this| {
1338                            if is_open {
1339                                match &tool_call.status {
1340                                    ToolCallStatus::WaitingForConfirmation { options, .. } => this
1341                                        .children(tool_call.content.iter().map(|content| {
1342                                            div()
1343                                                .py_1p5()
1344                                                .child(self.render_tool_call_content(
1345                                                    content, tool_call, window, cx,
1346                                                ))
1347                                                .into_any_element()
1348                                        }))
1349                                        .child(self.render_permission_buttons(
1350                                            options,
1351                                            entry_ix,
1352                                            tool_call.id.clone(),
1353                                            tool_call.content.is_empty(),
1354                                            cx,
1355                                        )),
1356                                    ToolCallStatus::Allowed { .. } | ToolCallStatus::Canceled => {
1357                                        this.children(tool_call.content.iter().map(|content| {
1358                                            div()
1359                                                .py_1p5()
1360                                                .child(self.render_tool_call_content(
1361                                                    content, tool_call, window, cx,
1362                                                ))
1363                                                .into_any_element()
1364                                        }))
1365                                    }
1366                                    ToolCallStatus::Rejected => this,
1367                                }
1368                            } else {
1369                                this
1370                            }
1371                        }),
1372                )
1373            })
1374    }
1375
1376    fn render_tool_call_content(
1377        &self,
1378        content: &ToolCallContent,
1379        tool_call: &ToolCall,
1380        window: &Window,
1381        cx: &Context<Self>,
1382    ) -> AnyElement {
1383        match content {
1384            ToolCallContent::ContentBlock(content) => {
1385                if let Some(md) = content.markdown() {
1386                    div()
1387                        .p_2()
1388                        .child(
1389                            self.render_markdown(
1390                                md.clone(),
1391                                default_markdown_style(false, window, cx),
1392                            ),
1393                        )
1394                        .into_any_element()
1395                } else {
1396                    Empty.into_any_element()
1397                }
1398            }
1399            ToolCallContent::Diff(diff) => self.render_diff_editor(&diff.read(cx).multibuffer()),
1400            ToolCallContent::Terminal(terminal) => {
1401                self.render_terminal_tool_call(terminal, tool_call, window, cx)
1402            }
1403        }
1404    }
1405
1406    fn render_permission_buttons(
1407        &self,
1408        options: &[acp::PermissionOption],
1409        entry_ix: usize,
1410        tool_call_id: acp::ToolCallId,
1411        empty_content: bool,
1412        cx: &Context<Self>,
1413    ) -> Div {
1414        h_flex()
1415            .py_1()
1416            .pl_2()
1417            .pr_1()
1418            .gap_1()
1419            .justify_between()
1420            .flex_wrap()
1421            .when(!empty_content, |this| {
1422                this.border_t_1()
1423                    .border_color(self.tool_card_border_color(cx))
1424            })
1425            .child(
1426                div()
1427                    .min_w(rems_from_px(145.))
1428                    .child(LoadingLabel::new("Waiting for Confirmation").size(LabelSize::Small)),
1429            )
1430            .child(h_flex().gap_0p5().children(options.iter().map(|option| {
1431                let option_id = SharedString::from(option.id.0.clone());
1432                Button::new((option_id, entry_ix), option.name.clone())
1433                    .map(|this| match option.kind {
1434                        acp::PermissionOptionKind::AllowOnce => {
1435                            this.icon(IconName::Check).icon_color(Color::Success)
1436                        }
1437                        acp::PermissionOptionKind::AllowAlways => {
1438                            this.icon(IconName::CheckDouble).icon_color(Color::Success)
1439                        }
1440                        acp::PermissionOptionKind::RejectOnce => {
1441                            this.icon(IconName::Close).icon_color(Color::Error)
1442                        }
1443                        acp::PermissionOptionKind::RejectAlways => {
1444                            this.icon(IconName::Close).icon_color(Color::Error)
1445                        }
1446                    })
1447                    .icon_position(IconPosition::Start)
1448                    .icon_size(IconSize::XSmall)
1449                    .label_size(LabelSize::Small)
1450                    .on_click(cx.listener({
1451                        let tool_call_id = tool_call_id.clone();
1452                        let option_id = option.id.clone();
1453                        let option_kind = option.kind;
1454                        move |this, _, _, cx| {
1455                            this.authorize_tool_call(
1456                                tool_call_id.clone(),
1457                                option_id.clone(),
1458                                option_kind,
1459                                cx,
1460                            );
1461                        }
1462                    }))
1463            })))
1464    }
1465
1466    fn render_diff_editor(&self, multibuffer: &Entity<MultiBuffer>) -> AnyElement {
1467        v_flex()
1468            .h_full()
1469            .child(
1470                if let Some(editor) = self.diff_editors.get(&multibuffer.entity_id()) {
1471                    editor.clone().into_any_element()
1472                } else {
1473                    Empty.into_any()
1474                },
1475            )
1476            .into_any()
1477    }
1478
1479    fn render_terminal_tool_call(
1480        &self,
1481        terminal: &Entity<acp_thread::Terminal>,
1482        tool_call: &ToolCall,
1483        window: &Window,
1484        cx: &Context<Self>,
1485    ) -> AnyElement {
1486        let terminal_data = terminal.read(cx);
1487        let working_dir = terminal_data.working_dir();
1488        let command = terminal_data.command();
1489        let started_at = terminal_data.started_at();
1490
1491        let tool_failed = matches!(
1492            &tool_call.status,
1493            ToolCallStatus::Rejected
1494                | ToolCallStatus::Canceled
1495                | ToolCallStatus::Allowed {
1496                    status: acp::ToolCallStatus::Failed,
1497                    ..
1498                }
1499        );
1500
1501        let output = terminal_data.output();
1502        let command_finished = output.is_some();
1503        let truncated_output = output.is_some_and(|output| output.was_content_truncated);
1504        let output_line_count = output.map(|output| output.content_line_count).unwrap_or(0);
1505
1506        let command_failed = command_finished
1507            && output.is_some_and(|o| o.exit_status.is_none_or(|status| !status.success()));
1508
1509        let time_elapsed = if let Some(output) = output {
1510            output.ended_at.duration_since(started_at)
1511        } else {
1512            started_at.elapsed()
1513        };
1514
1515        let header_bg = cx
1516            .theme()
1517            .colors()
1518            .element_background
1519            .blend(cx.theme().colors().editor_foreground.opacity(0.025));
1520        let border_color = cx.theme().colors().border.opacity(0.6);
1521
1522        let working_dir = working_dir
1523            .as_ref()
1524            .map(|path| format!("{}", path.display()))
1525            .unwrap_or_else(|| "current directory".to_string());
1526
1527        let header = h_flex()
1528            .id(SharedString::from(format!(
1529                "terminal-tool-header-{}",
1530                terminal.entity_id()
1531            )))
1532            .flex_none()
1533            .gap_1()
1534            .justify_between()
1535            .rounded_t_md()
1536            .child(
1537                div()
1538                    .id(("command-target-path", terminal.entity_id()))
1539                    .w_full()
1540                    .max_w_full()
1541                    .overflow_x_scroll()
1542                    .child(
1543                        Label::new(working_dir)
1544                            .buffer_font(cx)
1545                            .size(LabelSize::XSmall)
1546                            .color(Color::Muted),
1547                    ),
1548            )
1549            .when(!command_finished, |header| {
1550                header
1551                    .gap_1p5()
1552                    .child(
1553                        Button::new(
1554                            SharedString::from(format!("stop-terminal-{}", terminal.entity_id())),
1555                            "Stop",
1556                        )
1557                        .icon(IconName::Stop)
1558                        .icon_position(IconPosition::Start)
1559                        .icon_size(IconSize::Small)
1560                        .icon_color(Color::Error)
1561                        .label_size(LabelSize::Small)
1562                        .tooltip(move |window, cx| {
1563                            Tooltip::with_meta(
1564                                "Stop This Command",
1565                                None,
1566                                "Also possible by placing your cursor inside the terminal and using regular terminal bindings.",
1567                                window,
1568                                cx,
1569                            )
1570                        })
1571                        .on_click({
1572                            let terminal = terminal.clone();
1573                            cx.listener(move |_this, _event, _window, cx| {
1574                                let inner_terminal = terminal.read(cx).inner().clone();
1575                                inner_terminal.update(cx, |inner_terminal, _cx| {
1576                                    inner_terminal.kill_active_task();
1577                                });
1578                            })
1579                        }),
1580                    )
1581                    .child(Divider::vertical())
1582                    .child(
1583                        Icon::new(IconName::ArrowCircle)
1584                            .size(IconSize::XSmall)
1585                            .color(Color::Info)
1586                            .with_animation(
1587                                "arrow-circle",
1588                                Animation::new(Duration::from_secs(2)).repeat(),
1589                                |icon, delta| {
1590                                    icon.transform(Transformation::rotate(percentage(delta)))
1591                                },
1592                            ),
1593                    )
1594            })
1595            .when(tool_failed || command_failed, |header| {
1596                header.child(
1597                    div()
1598                        .id(("terminal-tool-error-code-indicator", terminal.entity_id()))
1599                        .child(
1600                            Icon::new(IconName::Close)
1601                                .size(IconSize::Small)
1602                                .color(Color::Error),
1603                        )
1604                        .when_some(output.and_then(|o| o.exit_status), |this, status| {
1605                            this.tooltip(Tooltip::text(format!(
1606                                "Exited with code {}",
1607                                status.code().unwrap_or(-1),
1608                            )))
1609                        }),
1610                )
1611            })
1612            .when(truncated_output, |header| {
1613                let tooltip = if let Some(output) = output {
1614                    if output_line_count + 10 > terminal::MAX_SCROLL_HISTORY_LINES {
1615                        "Output exceeded terminal max lines and was \
1616                            truncated, the model received the first 16 KB."
1617                            .to_string()
1618                    } else {
1619                        format!(
1620                            "Output is {} long—to avoid unexpected token usage, \
1621                                only 16 KB was sent back to the model.",
1622                            format_file_size(output.original_content_len as u64, true),
1623                        )
1624                    }
1625                } else {
1626                    "Output was truncated".to_string()
1627                };
1628
1629                header.child(
1630                    h_flex()
1631                        .id(("terminal-tool-truncated-label", terminal.entity_id()))
1632                        .gap_1()
1633                        .child(
1634                            Icon::new(IconName::Info)
1635                                .size(IconSize::XSmall)
1636                                .color(Color::Ignored),
1637                        )
1638                        .child(
1639                            Label::new("Truncated")
1640                                .color(Color::Muted)
1641                                .size(LabelSize::XSmall),
1642                        )
1643                        .tooltip(Tooltip::text(tooltip)),
1644                )
1645            })
1646            .when(time_elapsed > Duration::from_secs(10), |header| {
1647                header.child(
1648                    Label::new(format!("({})", duration_alt_display(time_elapsed)))
1649                        .buffer_font(cx)
1650                        .color(Color::Muted)
1651                        .size(LabelSize::XSmall),
1652                )
1653            })
1654            .child(
1655                Disclosure::new(
1656                    SharedString::from(format!(
1657                        "terminal-tool-disclosure-{}",
1658                        terminal.entity_id()
1659                    )),
1660                    self.terminal_expanded,
1661                )
1662                .opened_icon(IconName::ChevronUp)
1663                .closed_icon(IconName::ChevronDown)
1664                .on_click(cx.listener(move |this, _event, _window, _cx| {
1665                    this.terminal_expanded = !this.terminal_expanded;
1666                })),
1667            );
1668
1669        let show_output =
1670            self.terminal_expanded && self.terminal_views.contains_key(&terminal.entity_id());
1671
1672        v_flex()
1673            .mb_2()
1674            .border_1()
1675            .when(tool_failed || command_failed, |card| card.border_dashed())
1676            .border_color(border_color)
1677            .rounded_lg()
1678            .overflow_hidden()
1679            .child(
1680                v_flex()
1681                    .p_2()
1682                    .gap_0p5()
1683                    .bg(header_bg)
1684                    .text_xs()
1685                    .child(header)
1686                    .child(
1687                        MarkdownElement::new(
1688                            command.clone(),
1689                            terminal_command_markdown_style(window, cx),
1690                        )
1691                        .code_block_renderer(
1692                            markdown::CodeBlockRenderer::Default {
1693                                copy_button: false,
1694                                copy_button_on_hover: true,
1695                                border: false,
1696                            },
1697                        ),
1698                    ),
1699            )
1700            .when(show_output, |this| {
1701                let terminal_view = self.terminal_views.get(&terminal.entity_id()).unwrap();
1702
1703                this.child(
1704                    div()
1705                        .pt_2()
1706                        .border_t_1()
1707                        .when(tool_failed || command_failed, |card| card.border_dashed())
1708                        .border_color(border_color)
1709                        .bg(cx.theme().colors().editor_background)
1710                        .rounded_b_md()
1711                        .text_ui_sm(cx)
1712                        .child(terminal_view.clone()),
1713                )
1714            })
1715            .into_any()
1716    }
1717
1718    fn render_agent_logo(&self) -> AnyElement {
1719        Icon::new(self.agent.logo())
1720            .color(Color::Muted)
1721            .size(IconSize::XLarge)
1722            .into_any_element()
1723    }
1724
1725    fn render_error_agent_logo(&self) -> AnyElement {
1726        let logo = Icon::new(self.agent.logo())
1727            .color(Color::Muted)
1728            .size(IconSize::XLarge)
1729            .into_any_element();
1730
1731        h_flex()
1732            .relative()
1733            .justify_center()
1734            .child(div().opacity(0.3).child(logo))
1735            .child(
1736                h_flex().absolute().right_1().bottom_0().child(
1737                    Icon::new(IconName::XCircle)
1738                        .color(Color::Error)
1739                        .size(IconSize::Small),
1740                ),
1741            )
1742            .into_any_element()
1743    }
1744
1745    fn render_empty_state(&self, cx: &App) -> AnyElement {
1746        let loading = matches!(&self.thread_state, ThreadState::Loading { .. });
1747
1748        v_flex()
1749            .size_full()
1750            .items_center()
1751            .justify_center()
1752            .child(if loading {
1753                h_flex()
1754                    .justify_center()
1755                    .child(self.render_agent_logo())
1756                    .with_animation(
1757                        "pulsating_icon",
1758                        Animation::new(Duration::from_secs(2))
1759                            .repeat()
1760                            .with_easing(pulsating_between(0.4, 1.0)),
1761                        |icon, delta| icon.opacity(delta),
1762                    )
1763                    .into_any()
1764            } else {
1765                self.render_agent_logo().into_any_element()
1766            })
1767            .child(h_flex().mt_4().mb_1().justify_center().child(if loading {
1768                div()
1769                    .child(LoadingLabel::new("").size(LabelSize::Large))
1770                    .into_any_element()
1771            } else {
1772                Headline::new(self.agent.empty_state_headline())
1773                    .size(HeadlineSize::Medium)
1774                    .into_any_element()
1775            }))
1776            .child(
1777                div()
1778                    .max_w_1_2()
1779                    .text_sm()
1780                    .text_center()
1781                    .map(|this| {
1782                        if loading {
1783                            this.invisible()
1784                        } else {
1785                            this.text_color(cx.theme().colors().text_muted)
1786                        }
1787                    })
1788                    .child(self.agent.empty_state_message()),
1789            )
1790            .into_any()
1791    }
1792
1793    fn render_pending_auth_state(&self) -> AnyElement {
1794        v_flex()
1795            .items_center()
1796            .justify_center()
1797            .child(self.render_error_agent_logo())
1798            .child(
1799                h_flex()
1800                    .mt_4()
1801                    .mb_1()
1802                    .justify_center()
1803                    .child(Headline::new("Not Authenticated").size(HeadlineSize::Medium)),
1804            )
1805            .into_any()
1806    }
1807
1808    fn render_server_exited(&self, status: ExitStatus, _cx: &Context<Self>) -> AnyElement {
1809        v_flex()
1810            .items_center()
1811            .justify_center()
1812            .child(self.render_error_agent_logo())
1813            .child(
1814                v_flex()
1815                    .mt_4()
1816                    .mb_2()
1817                    .gap_0p5()
1818                    .text_center()
1819                    .items_center()
1820                    .child(Headline::new("Server exited unexpectedly").size(HeadlineSize::Medium))
1821                    .child(
1822                        Label::new(format!("Exit status: {}", status.code().unwrap_or(-127)))
1823                            .size(LabelSize::Small)
1824                            .color(Color::Muted),
1825                    ),
1826            )
1827            .into_any_element()
1828    }
1829
1830    fn render_load_error(&self, e: &LoadError, cx: &Context<Self>) -> AnyElement {
1831        let mut container = v_flex()
1832            .items_center()
1833            .justify_center()
1834            .child(self.render_error_agent_logo())
1835            .child(
1836                v_flex()
1837                    .mt_4()
1838                    .mb_2()
1839                    .gap_0p5()
1840                    .text_center()
1841                    .items_center()
1842                    .child(Headline::new("Failed to launch").size(HeadlineSize::Medium))
1843                    .child(
1844                        Label::new(e.to_string())
1845                            .size(LabelSize::Small)
1846                            .color(Color::Muted),
1847                    ),
1848            );
1849
1850        if let LoadError::Unsupported {
1851            upgrade_message,
1852            upgrade_command,
1853            ..
1854        } = &e
1855        {
1856            let upgrade_message = upgrade_message.clone();
1857            let upgrade_command = upgrade_command.clone();
1858            container = container.child(Button::new("upgrade", upgrade_message).on_click(
1859                cx.listener(move |this, _, window, cx| {
1860                    this.workspace
1861                        .update(cx, |workspace, cx| {
1862                            let project = workspace.project().read(cx);
1863                            let cwd = project.first_project_directory(cx);
1864                            let shell = project.terminal_settings(&cwd, cx).shell.clone();
1865                            let spawn_in_terminal = task::SpawnInTerminal {
1866                                id: task::TaskId("install".to_string()),
1867                                full_label: upgrade_command.clone(),
1868                                label: upgrade_command.clone(),
1869                                command: Some(upgrade_command.clone()),
1870                                args: Vec::new(),
1871                                command_label: upgrade_command.clone(),
1872                                cwd,
1873                                env: Default::default(),
1874                                use_new_terminal: true,
1875                                allow_concurrent_runs: true,
1876                                reveal: Default::default(),
1877                                reveal_target: Default::default(),
1878                                hide: Default::default(),
1879                                shell,
1880                                show_summary: true,
1881                                show_command: true,
1882                                show_rerun: false,
1883                            };
1884                            workspace
1885                                .spawn_in_terminal(spawn_in_terminal, window, cx)
1886                                .detach();
1887                        })
1888                        .ok();
1889                }),
1890            ));
1891        }
1892
1893        container.into_any()
1894    }
1895
1896    fn render_activity_bar(
1897        &self,
1898        thread_entity: &Entity<AcpThread>,
1899        window: &mut Window,
1900        cx: &Context<Self>,
1901    ) -> Option<AnyElement> {
1902        let thread = thread_entity.read(cx);
1903        let action_log = thread.action_log();
1904        let changed_buffers = action_log.read(cx).changed_buffers(cx);
1905        let plan = thread.plan();
1906
1907        if changed_buffers.is_empty() && plan.is_empty() {
1908            return None;
1909        }
1910
1911        let editor_bg_color = cx.theme().colors().editor_background;
1912        let active_color = cx.theme().colors().element_selected;
1913        let bg_edit_files_disclosure = editor_bg_color.blend(active_color.opacity(0.3));
1914
1915        let pending_edits = thread.has_pending_edit_tool_calls();
1916
1917        v_flex()
1918            .mt_1()
1919            .mx_2()
1920            .bg(bg_edit_files_disclosure)
1921            .border_1()
1922            .border_b_0()
1923            .border_color(cx.theme().colors().border)
1924            .rounded_t_md()
1925            .shadow(vec![gpui::BoxShadow {
1926                color: gpui::black().opacity(0.15),
1927                offset: point(px(1.), px(-1.)),
1928                blur_radius: px(3.),
1929                spread_radius: px(0.),
1930            }])
1931            .when(!plan.is_empty(), |this| {
1932                this.child(self.render_plan_summary(plan, window, cx))
1933                    .when(self.plan_expanded, |parent| {
1934                        parent.child(self.render_plan_entries(plan, window, cx))
1935                    })
1936            })
1937            .when(!changed_buffers.is_empty(), |this| {
1938                this.child(Divider::horizontal().color(DividerColor::Border))
1939                    .child(self.render_edits_summary(
1940                        action_log,
1941                        &changed_buffers,
1942                        self.edits_expanded,
1943                        pending_edits,
1944                        window,
1945                        cx,
1946                    ))
1947                    .when(self.edits_expanded, |parent| {
1948                        parent.child(self.render_edited_files(
1949                            action_log,
1950                            &changed_buffers,
1951                            pending_edits,
1952                            cx,
1953                        ))
1954                    })
1955            })
1956            .into_any()
1957            .into()
1958    }
1959
1960    fn render_plan_summary(&self, plan: &Plan, window: &mut Window, cx: &Context<Self>) -> Div {
1961        let stats = plan.stats();
1962
1963        let title = if let Some(entry) = stats.in_progress_entry
1964            && !self.plan_expanded
1965        {
1966            h_flex()
1967                .w_full()
1968                .cursor_default()
1969                .gap_1()
1970                .text_xs()
1971                .text_color(cx.theme().colors().text_muted)
1972                .justify_between()
1973                .child(
1974                    h_flex()
1975                        .gap_1()
1976                        .child(
1977                            Label::new("Current:")
1978                                .size(LabelSize::Small)
1979                                .color(Color::Muted),
1980                        )
1981                        .child(MarkdownElement::new(
1982                            entry.content.clone(),
1983                            plan_label_markdown_style(&entry.status, window, cx),
1984                        )),
1985                )
1986                .when(stats.pending > 0, |this| {
1987                    this.child(
1988                        Label::new(format!("{} left", stats.pending))
1989                            .size(LabelSize::Small)
1990                            .color(Color::Muted)
1991                            .mr_1(),
1992                    )
1993                })
1994        } else {
1995            let status_label = if stats.pending == 0 {
1996                "All Done".to_string()
1997            } else if stats.completed == 0 {
1998                format!("{} Tasks", plan.entries.len())
1999            } else {
2000                format!("{}/{}", stats.completed, plan.entries.len())
2001            };
2002
2003            h_flex()
2004                .w_full()
2005                .gap_1()
2006                .justify_between()
2007                .child(
2008                    Label::new("Plan")
2009                        .size(LabelSize::Small)
2010                        .color(Color::Muted),
2011                )
2012                .child(
2013                    Label::new(status_label)
2014                        .size(LabelSize::Small)
2015                        .color(Color::Muted)
2016                        .mr_1(),
2017                )
2018        };
2019
2020        h_flex()
2021            .p_1()
2022            .justify_between()
2023            .when(self.plan_expanded, |this| {
2024                this.border_b_1().border_color(cx.theme().colors().border)
2025            })
2026            .child(
2027                h_flex()
2028                    .id("plan_summary")
2029                    .w_full()
2030                    .gap_1()
2031                    .child(Disclosure::new("plan_disclosure", self.plan_expanded))
2032                    .child(title)
2033                    .on_click(cx.listener(|this, _, _, cx| {
2034                        this.plan_expanded = !this.plan_expanded;
2035                        cx.notify();
2036                    })),
2037            )
2038    }
2039
2040    fn render_plan_entries(&self, plan: &Plan, window: &mut Window, cx: &Context<Self>) -> Div {
2041        v_flex().children(plan.entries.iter().enumerate().flat_map(|(index, entry)| {
2042            let element = h_flex()
2043                .py_1()
2044                .px_2()
2045                .gap_2()
2046                .justify_between()
2047                .bg(cx.theme().colors().editor_background)
2048                .when(index < plan.entries.len() - 1, |parent| {
2049                    parent.border_color(cx.theme().colors().border).border_b_1()
2050                })
2051                .child(
2052                    h_flex()
2053                        .id(("plan_entry", index))
2054                        .gap_1p5()
2055                        .max_w_full()
2056                        .overflow_x_scroll()
2057                        .text_xs()
2058                        .text_color(cx.theme().colors().text_muted)
2059                        .child(match entry.status {
2060                            acp::PlanEntryStatus::Pending => Icon::new(IconName::TodoPending)
2061                                .size(IconSize::Small)
2062                                .color(Color::Muted)
2063                                .into_any_element(),
2064                            acp::PlanEntryStatus::InProgress => Icon::new(IconName::TodoProgress)
2065                                .size(IconSize::Small)
2066                                .color(Color::Accent)
2067                                .with_animation(
2068                                    "running",
2069                                    Animation::new(Duration::from_secs(2)).repeat(),
2070                                    |icon, delta| {
2071                                        icon.transform(Transformation::rotate(percentage(delta)))
2072                                    },
2073                                )
2074                                .into_any_element(),
2075                            acp::PlanEntryStatus::Completed => Icon::new(IconName::TodoComplete)
2076                                .size(IconSize::Small)
2077                                .color(Color::Success)
2078                                .into_any_element(),
2079                        })
2080                        .child(MarkdownElement::new(
2081                            entry.content.clone(),
2082                            plan_label_markdown_style(&entry.status, window, cx),
2083                        )),
2084                );
2085
2086            Some(element)
2087        }))
2088    }
2089
2090    fn render_edits_summary(
2091        &self,
2092        action_log: &Entity<ActionLog>,
2093        changed_buffers: &BTreeMap<Entity<Buffer>, Entity<BufferDiff>>,
2094        expanded: bool,
2095        pending_edits: bool,
2096        window: &mut Window,
2097        cx: &Context<Self>,
2098    ) -> Div {
2099        const EDIT_NOT_READY_TOOLTIP_LABEL: &str = "Wait until file edits are complete.";
2100
2101        let focus_handle = self.focus_handle(cx);
2102
2103        h_flex()
2104            .p_1()
2105            .justify_between()
2106            .when(expanded, |this| {
2107                this.border_b_1().border_color(cx.theme().colors().border)
2108            })
2109            .child(
2110                h_flex()
2111                    .id("edits-container")
2112                    .w_full()
2113                    .gap_1()
2114                    .child(Disclosure::new("edits-disclosure", expanded))
2115                    .map(|this| {
2116                        if pending_edits {
2117                            this.child(
2118                                Label::new(format!(
2119                                    "Editing {} {}",
2120                                    changed_buffers.len(),
2121                                    if changed_buffers.len() == 1 {
2122                                        "file"
2123                                    } else {
2124                                        "files"
2125                                    }
2126                                ))
2127                                .color(Color::Muted)
2128                                .size(LabelSize::Small)
2129                                .with_animation(
2130                                    "edit-label",
2131                                    Animation::new(Duration::from_secs(2))
2132                                        .repeat()
2133                                        .with_easing(pulsating_between(0.3, 0.7)),
2134                                    |label, delta| label.alpha(delta),
2135                                ),
2136                            )
2137                        } else {
2138                            this.child(
2139                                Label::new("Edits")
2140                                    .size(LabelSize::Small)
2141                                    .color(Color::Muted),
2142                            )
2143                            .child(Label::new("").size(LabelSize::XSmall).color(Color::Muted))
2144                            .child(
2145                                Label::new(format!(
2146                                    "{} {}",
2147                                    changed_buffers.len(),
2148                                    if changed_buffers.len() == 1 {
2149                                        "file"
2150                                    } else {
2151                                        "files"
2152                                    }
2153                                ))
2154                                .size(LabelSize::Small)
2155                                .color(Color::Muted),
2156                            )
2157                        }
2158                    })
2159                    .on_click(cx.listener(|this, _, _, cx| {
2160                        this.edits_expanded = !this.edits_expanded;
2161                        cx.notify();
2162                    })),
2163            )
2164            .child(
2165                h_flex()
2166                    .gap_1()
2167                    .child(
2168                        IconButton::new("review-changes", IconName::ListTodo)
2169                            .icon_size(IconSize::Small)
2170                            .tooltip({
2171                                let focus_handle = focus_handle.clone();
2172                                move |window, cx| {
2173                                    Tooltip::for_action_in(
2174                                        "Review Changes",
2175                                        &OpenAgentDiff,
2176                                        &focus_handle,
2177                                        window,
2178                                        cx,
2179                                    )
2180                                }
2181                            })
2182                            .on_click(cx.listener(|_, _, window, cx| {
2183                                window.dispatch_action(OpenAgentDiff.boxed_clone(), cx);
2184                            })),
2185                    )
2186                    .child(Divider::vertical().color(DividerColor::Border))
2187                    .child(
2188                        Button::new("reject-all-changes", "Reject All")
2189                            .label_size(LabelSize::Small)
2190                            .disabled(pending_edits)
2191                            .when(pending_edits, |this| {
2192                                this.tooltip(Tooltip::text(EDIT_NOT_READY_TOOLTIP_LABEL))
2193                            })
2194                            .key_binding(
2195                                KeyBinding::for_action_in(
2196                                    &RejectAll,
2197                                    &focus_handle.clone(),
2198                                    window,
2199                                    cx,
2200                                )
2201                                .map(|kb| kb.size(rems_from_px(10.))),
2202                            )
2203                            .on_click({
2204                                let action_log = action_log.clone();
2205                                cx.listener(move |_, _, _, cx| {
2206                                    action_log.update(cx, |action_log, cx| {
2207                                        action_log.reject_all_edits(cx).detach();
2208                                    })
2209                                })
2210                            }),
2211                    )
2212                    .child(
2213                        Button::new("keep-all-changes", "Keep All")
2214                            .label_size(LabelSize::Small)
2215                            .disabled(pending_edits)
2216                            .when(pending_edits, |this| {
2217                                this.tooltip(Tooltip::text(EDIT_NOT_READY_TOOLTIP_LABEL))
2218                            })
2219                            .key_binding(
2220                                KeyBinding::for_action_in(&KeepAll, &focus_handle, window, cx)
2221                                    .map(|kb| kb.size(rems_from_px(10.))),
2222                            )
2223                            .on_click({
2224                                let action_log = action_log.clone();
2225                                cx.listener(move |_, _, _, cx| {
2226                                    action_log.update(cx, |action_log, cx| {
2227                                        action_log.keep_all_edits(cx);
2228                                    })
2229                                })
2230                            }),
2231                    ),
2232            )
2233    }
2234
2235    fn render_edited_files(
2236        &self,
2237        action_log: &Entity<ActionLog>,
2238        changed_buffers: &BTreeMap<Entity<Buffer>, Entity<BufferDiff>>,
2239        pending_edits: bool,
2240        cx: &Context<Self>,
2241    ) -> Div {
2242        let editor_bg_color = cx.theme().colors().editor_background;
2243
2244        v_flex().children(changed_buffers.into_iter().enumerate().flat_map(
2245            |(index, (buffer, _diff))| {
2246                let file = buffer.read(cx).file()?;
2247                let path = file.path();
2248
2249                let file_path = path.parent().and_then(|parent| {
2250                    let parent_str = parent.to_string_lossy();
2251
2252                    if parent_str.is_empty() {
2253                        None
2254                    } else {
2255                        Some(
2256                            Label::new(format!("/{}{}", parent_str, std::path::MAIN_SEPARATOR_STR))
2257                                .color(Color::Muted)
2258                                .size(LabelSize::XSmall)
2259                                .buffer_font(cx),
2260                        )
2261                    }
2262                });
2263
2264                let file_name = path.file_name().map(|name| {
2265                    Label::new(name.to_string_lossy().to_string())
2266                        .size(LabelSize::XSmall)
2267                        .buffer_font(cx)
2268                });
2269
2270                let file_icon = FileIcons::get_icon(&path, cx)
2271                    .map(Icon::from_path)
2272                    .map(|icon| icon.color(Color::Muted).size(IconSize::Small))
2273                    .unwrap_or_else(|| {
2274                        Icon::new(IconName::File)
2275                            .color(Color::Muted)
2276                            .size(IconSize::Small)
2277                    });
2278
2279                let overlay_gradient = linear_gradient(
2280                    90.,
2281                    linear_color_stop(editor_bg_color, 1.),
2282                    linear_color_stop(editor_bg_color.opacity(0.2), 0.),
2283                );
2284
2285                let element = h_flex()
2286                    .group("edited-code")
2287                    .id(("file-container", index))
2288                    .relative()
2289                    .py_1()
2290                    .pl_2()
2291                    .pr_1()
2292                    .gap_2()
2293                    .justify_between()
2294                    .bg(editor_bg_color)
2295                    .when(index < changed_buffers.len() - 1, |parent| {
2296                        parent.border_color(cx.theme().colors().border).border_b_1()
2297                    })
2298                    .child(
2299                        h_flex()
2300                            .id(("file-name", index))
2301                            .pr_8()
2302                            .gap_1p5()
2303                            .max_w_full()
2304                            .overflow_x_scroll()
2305                            .child(file_icon)
2306                            .child(h_flex().gap_0p5().children(file_name).children(file_path))
2307                            .on_click({
2308                                let buffer = buffer.clone();
2309                                cx.listener(move |this, _, window, cx| {
2310                                    this.open_edited_buffer(&buffer, window, cx);
2311                                })
2312                            }),
2313                    )
2314                    .child(
2315                        h_flex()
2316                            .gap_1()
2317                            .visible_on_hover("edited-code")
2318                            .child(
2319                                Button::new("review", "Review")
2320                                    .label_size(LabelSize::Small)
2321                                    .on_click({
2322                                        let buffer = buffer.clone();
2323                                        cx.listener(move |this, _, window, cx| {
2324                                            this.open_edited_buffer(&buffer, window, cx);
2325                                        })
2326                                    }),
2327                            )
2328                            .child(Divider::vertical().color(DividerColor::BorderVariant))
2329                            .child(
2330                                Button::new("reject-file", "Reject")
2331                                    .label_size(LabelSize::Small)
2332                                    .disabled(pending_edits)
2333                                    .on_click({
2334                                        let buffer = buffer.clone();
2335                                        let action_log = action_log.clone();
2336                                        move |_, _, cx| {
2337                                            action_log.update(cx, |action_log, cx| {
2338                                                action_log
2339                                                    .reject_edits_in_ranges(
2340                                                        buffer.clone(),
2341                                                        vec![Anchor::MIN..Anchor::MAX],
2342                                                        cx,
2343                                                    )
2344                                                    .detach_and_log_err(cx);
2345                                            })
2346                                        }
2347                                    }),
2348                            )
2349                            .child(
2350                                Button::new("keep-file", "Keep")
2351                                    .label_size(LabelSize::Small)
2352                                    .disabled(pending_edits)
2353                                    .on_click({
2354                                        let buffer = buffer.clone();
2355                                        let action_log = action_log.clone();
2356                                        move |_, _, cx| {
2357                                            action_log.update(cx, |action_log, cx| {
2358                                                action_log.keep_edits_in_range(
2359                                                    buffer.clone(),
2360                                                    Anchor::MIN..Anchor::MAX,
2361                                                    cx,
2362                                                );
2363                                            })
2364                                        }
2365                                    }),
2366                            ),
2367                    )
2368                    .child(
2369                        div()
2370                            .id("gradient-overlay")
2371                            .absolute()
2372                            .h_full()
2373                            .w_12()
2374                            .top_0()
2375                            .bottom_0()
2376                            .right(px(152.))
2377                            .bg(overlay_gradient),
2378                    );
2379
2380                Some(element)
2381            },
2382        ))
2383    }
2384
2385    fn render_message_editor(&mut self, window: &mut Window, cx: &mut Context<Self>) -> AnyElement {
2386        let focus_handle = self.message_editor.focus_handle(cx);
2387        let editor_bg_color = cx.theme().colors().editor_background;
2388        let (expand_icon, expand_tooltip) = if self.editor_expanded {
2389            (IconName::Minimize, "Minimize Message Editor")
2390        } else {
2391            (IconName::Maximize, "Expand Message Editor")
2392        };
2393
2394        v_flex()
2395            .on_action(cx.listener(Self::expand_message_editor))
2396            .p_2()
2397            .gap_2()
2398            .border_t_1()
2399            .border_color(cx.theme().colors().border)
2400            .bg(editor_bg_color)
2401            .when(self.editor_expanded, |this| {
2402                this.h(vh(0.8, window)).size_full().justify_between()
2403            })
2404            .child(
2405                v_flex()
2406                    .relative()
2407                    .size_full()
2408                    .pt_1()
2409                    .pr_2p5()
2410                    .child(div().flex_1().child({
2411                        let settings = ThemeSettings::get_global(cx);
2412                        let font_size = TextSize::Small
2413                            .rems(cx)
2414                            .to_pixels(settings.agent_font_size(cx));
2415                        let line_height = settings.buffer_line_height.value() * font_size;
2416
2417                        let text_style = TextStyle {
2418                            color: cx.theme().colors().text,
2419                            font_family: settings.buffer_font.family.clone(),
2420                            font_fallbacks: settings.buffer_font.fallbacks.clone(),
2421                            font_features: settings.buffer_font.features.clone(),
2422                            font_size: font_size.into(),
2423                            line_height: line_height.into(),
2424                            ..Default::default()
2425                        };
2426
2427                        EditorElement::new(
2428                            &self.message_editor,
2429                            EditorStyle {
2430                                background: editor_bg_color,
2431                                local_player: cx.theme().players().local(),
2432                                text: text_style,
2433                                syntax: cx.theme().syntax().clone(),
2434                                ..Default::default()
2435                            },
2436                        )
2437                    }))
2438                    .child(
2439                        h_flex()
2440                            .absolute()
2441                            .top_0()
2442                            .right_0()
2443                            .opacity(0.5)
2444                            .hover(|this| this.opacity(1.0))
2445                            .child(
2446                                IconButton::new("toggle-height", expand_icon)
2447                                    .icon_size(IconSize::Small)
2448                                    .icon_color(Color::Muted)
2449                                    .tooltip({
2450                                        let focus_handle = focus_handle.clone();
2451                                        move |window, cx| {
2452                                            Tooltip::for_action_in(
2453                                                expand_tooltip,
2454                                                &ExpandMessageEditor,
2455                                                &focus_handle,
2456                                                window,
2457                                                cx,
2458                                            )
2459                                        }
2460                                    })
2461                                    .on_click(cx.listener(|_, _, window, cx| {
2462                                        window.dispatch_action(Box::new(ExpandMessageEditor), cx);
2463                                    })),
2464                            ),
2465                    ),
2466            )
2467            .child(
2468                h_flex()
2469                    .flex_none()
2470                    .justify_between()
2471                    .child(self.render_follow_toggle(cx))
2472                    .child(self.render_send_button(cx)),
2473            )
2474            .into_any()
2475    }
2476
2477    fn render_send_button(&self, cx: &mut Context<Self>) -> AnyElement {
2478        if self.thread().map_or(true, |thread| {
2479            thread.read(cx).status() == ThreadStatus::Idle
2480        }) {
2481            let is_editor_empty = self.message_editor.read(cx).is_empty(cx);
2482            IconButton::new("send-message", IconName::Send)
2483                .icon_color(Color::Accent)
2484                .style(ButtonStyle::Filled)
2485                .disabled(self.thread().is_none() || is_editor_empty)
2486                .when(!is_editor_empty, |button| {
2487                    button.tooltip(move |window, cx| Tooltip::for_action("Send", &Chat, window, cx))
2488                })
2489                .when(is_editor_empty, |button| {
2490                    button.tooltip(Tooltip::text("Type a message to submit"))
2491                })
2492                .on_click(cx.listener(|this, _, window, cx| {
2493                    this.chat(&Chat, window, cx);
2494                }))
2495                .into_any_element()
2496        } else {
2497            IconButton::new("stop-generation", IconName::Stop)
2498                .icon_color(Color::Error)
2499                .style(ButtonStyle::Tinted(ui::TintColor::Error))
2500                .tooltip(move |window, cx| {
2501                    Tooltip::for_action("Stop Generation", &editor::actions::Cancel, window, cx)
2502                })
2503                .on_click(cx.listener(|this, _event, _, cx| this.cancel(cx)))
2504                .into_any_element()
2505        }
2506    }
2507
2508    fn render_follow_toggle(&self, cx: &mut Context<Self>) -> impl IntoElement {
2509        let following = self
2510            .workspace
2511            .read_with(cx, |workspace, _| {
2512                workspace.is_being_followed(CollaboratorId::Agent)
2513            })
2514            .unwrap_or(false);
2515
2516        IconButton::new("follow-agent", IconName::Crosshair)
2517            .icon_size(IconSize::Small)
2518            .icon_color(Color::Muted)
2519            .toggle_state(following)
2520            .selected_icon_color(Some(Color::Custom(cx.theme().players().agent().cursor)))
2521            .tooltip(move |window, cx| {
2522                if following {
2523                    Tooltip::for_action("Stop Following Agent", &Follow, window, cx)
2524                } else {
2525                    Tooltip::with_meta(
2526                        "Follow Agent",
2527                        Some(&Follow),
2528                        "Track the agent's location as it reads and edits files.",
2529                        window,
2530                        cx,
2531                    )
2532                }
2533            })
2534            .on_click(cx.listener(move |this, _, window, cx| {
2535                this.workspace
2536                    .update(cx, |workspace, cx| {
2537                        if following {
2538                            workspace.unfollow(CollaboratorId::Agent, window, cx);
2539                        } else {
2540                            workspace.follow(CollaboratorId::Agent, window, cx);
2541                        }
2542                    })
2543                    .ok();
2544            }))
2545    }
2546
2547    fn render_markdown(&self, markdown: Entity<Markdown>, style: MarkdownStyle) -> MarkdownElement {
2548        let workspace = self.workspace.clone();
2549        MarkdownElement::new(markdown, style).on_url_click(move |text, window, cx| {
2550            Self::open_link(text, &workspace, window, cx);
2551        })
2552    }
2553
2554    fn open_link(
2555        url: SharedString,
2556        workspace: &WeakEntity<Workspace>,
2557        window: &mut Window,
2558        cx: &mut App,
2559    ) {
2560        let Some(workspace) = workspace.upgrade() else {
2561            cx.open_url(&url);
2562            return;
2563        };
2564
2565        if let Some(mention_path) = MentionPath::try_parse(&url) {
2566            workspace.update(cx, |workspace, cx| {
2567                let project = workspace.project();
2568                let Some((path, entry)) = project.update(cx, |project, cx| {
2569                    let path = project.find_project_path(mention_path.path(), cx)?;
2570                    let entry = project.entry_for_path(&path, cx)?;
2571                    Some((path, entry))
2572                }) else {
2573                    return;
2574                };
2575
2576                if entry.is_dir() {
2577                    project.update(cx, |_, cx| {
2578                        cx.emit(project::Event::RevealInProjectPanel(entry.id));
2579                    });
2580                } else {
2581                    workspace
2582                        .open_path(path, None, true, window, cx)
2583                        .detach_and_log_err(cx);
2584                }
2585            })
2586        } else {
2587            cx.open_url(&url);
2588        }
2589    }
2590
2591    fn open_tool_call_location(
2592        &self,
2593        entry_ix: usize,
2594        location_ix: usize,
2595        window: &mut Window,
2596        cx: &mut Context<Self>,
2597    ) -> Option<()> {
2598        let location = self
2599            .thread()?
2600            .read(cx)
2601            .entries()
2602            .get(entry_ix)?
2603            .locations()?
2604            .get(location_ix)?;
2605
2606        let project_path = self
2607            .project
2608            .read(cx)
2609            .find_project_path(&location.path, cx)?;
2610
2611        let open_task = self
2612            .workspace
2613            .update(cx, |worskpace, cx| {
2614                worskpace.open_path(project_path, None, true, window, cx)
2615            })
2616            .log_err()?;
2617
2618        window
2619            .spawn(cx, async move |cx| {
2620                let item = open_task.await?;
2621
2622                let Some(active_editor) = item.downcast::<Editor>() else {
2623                    return anyhow::Ok(());
2624                };
2625
2626                active_editor.update_in(cx, |editor, window, cx| {
2627                    let snapshot = editor.buffer().read(cx).snapshot(cx);
2628                    let first_hunk = editor
2629                        .diff_hunks_in_ranges(
2630                            &[editor::Anchor::min()..editor::Anchor::max()],
2631                            &snapshot,
2632                        )
2633                        .next();
2634                    if let Some(first_hunk) = first_hunk {
2635                        let first_hunk_start = first_hunk.multi_buffer_range().start;
2636                        editor.change_selections(Default::default(), window, cx, |selections| {
2637                            selections.select_anchor_ranges([first_hunk_start..first_hunk_start]);
2638                        })
2639                    }
2640                })?;
2641
2642                anyhow::Ok(())
2643            })
2644            .detach_and_log_err(cx);
2645
2646        None
2647    }
2648
2649    pub fn open_thread_as_markdown(
2650        &self,
2651        workspace: Entity<Workspace>,
2652        window: &mut Window,
2653        cx: &mut App,
2654    ) -> Task<anyhow::Result<()>> {
2655        let markdown_language_task = workspace
2656            .read(cx)
2657            .app_state()
2658            .languages
2659            .language_for_name("Markdown");
2660
2661        let (thread_summary, markdown) = if let Some(thread) = self.thread() {
2662            let thread = thread.read(cx);
2663            (thread.title().to_string(), thread.to_markdown(cx))
2664        } else {
2665            return Task::ready(Ok(()));
2666        };
2667
2668        window.spawn(cx, async move |cx| {
2669            let markdown_language = markdown_language_task.await?;
2670
2671            workspace.update_in(cx, |workspace, window, cx| {
2672                let project = workspace.project().clone();
2673
2674                if !project.read(cx).is_local() {
2675                    anyhow::bail!("failed to open active thread as markdown in remote project");
2676                }
2677
2678                let buffer = project.update(cx, |project, cx| {
2679                    project.create_local_buffer(&markdown, Some(markdown_language), cx)
2680                });
2681                let buffer = cx.new(|cx| {
2682                    MultiBuffer::singleton(buffer, cx).with_title(thread_summary.clone())
2683                });
2684
2685                workspace.add_item_to_active_pane(
2686                    Box::new(cx.new(|cx| {
2687                        let mut editor =
2688                            Editor::for_multibuffer(buffer, Some(project.clone()), window, cx);
2689                        editor.set_breadcrumb_header(thread_summary);
2690                        editor
2691                    })),
2692                    None,
2693                    true,
2694                    window,
2695                    cx,
2696                );
2697
2698                anyhow::Ok(())
2699            })??;
2700            anyhow::Ok(())
2701        })
2702    }
2703
2704    fn scroll_to_top(&mut self, cx: &mut Context<Self>) {
2705        self.list_state.scroll_to(ListOffset::default());
2706        cx.notify();
2707    }
2708
2709    pub fn scroll_to_bottom(&mut self, cx: &mut Context<Self>) {
2710        if let Some(thread) = self.thread() {
2711            let entry_count = thread.read(cx).entries().len();
2712            self.list_state.reset(entry_count);
2713            cx.notify();
2714        }
2715    }
2716
2717    fn notify_with_sound(
2718        &mut self,
2719        caption: impl Into<SharedString>,
2720        icon: IconName,
2721        window: &mut Window,
2722        cx: &mut Context<Self>,
2723    ) {
2724        self.play_notification_sound(window, cx);
2725        self.show_notification(caption, icon, window, cx);
2726    }
2727
2728    fn play_notification_sound(&self, window: &Window, cx: &mut App) {
2729        let settings = AgentSettings::get_global(cx);
2730        if settings.play_sound_when_agent_done && !window.is_window_active() {
2731            Audio::play_sound(Sound::AgentDone, cx);
2732        }
2733    }
2734
2735    fn show_notification(
2736        &mut self,
2737        caption: impl Into<SharedString>,
2738        icon: IconName,
2739        window: &mut Window,
2740        cx: &mut Context<Self>,
2741    ) {
2742        if window.is_window_active() || !self.notifications.is_empty() {
2743            return;
2744        }
2745
2746        let title = self.title(cx);
2747
2748        match AgentSettings::get_global(cx).notify_when_agent_waiting {
2749            NotifyWhenAgentWaiting::PrimaryScreen => {
2750                if let Some(primary) = cx.primary_display() {
2751                    self.pop_up(icon, caption.into(), title, window, primary, cx);
2752                }
2753            }
2754            NotifyWhenAgentWaiting::AllScreens => {
2755                let caption = caption.into();
2756                for screen in cx.displays() {
2757                    self.pop_up(icon, caption.clone(), title.clone(), window, screen, cx);
2758                }
2759            }
2760            NotifyWhenAgentWaiting::Never => {
2761                // Don't show anything
2762            }
2763        }
2764    }
2765
2766    fn pop_up(
2767        &mut self,
2768        icon: IconName,
2769        caption: SharedString,
2770        title: SharedString,
2771        window: &mut Window,
2772        screen: Rc<dyn PlatformDisplay>,
2773        cx: &mut Context<Self>,
2774    ) {
2775        let options = AgentNotification::window_options(screen, cx);
2776
2777        let project_name = self.workspace.upgrade().and_then(|workspace| {
2778            workspace
2779                .read(cx)
2780                .project()
2781                .read(cx)
2782                .visible_worktrees(cx)
2783                .next()
2784                .map(|worktree| worktree.read(cx).root_name().to_string())
2785        });
2786
2787        if let Some(screen_window) = cx
2788            .open_window(options, |_, cx| {
2789                cx.new(|_| {
2790                    AgentNotification::new(title.clone(), caption.clone(), icon, project_name)
2791                })
2792            })
2793            .log_err()
2794        {
2795            if let Some(pop_up) = screen_window.entity(cx).log_err() {
2796                self.notification_subscriptions
2797                    .entry(screen_window)
2798                    .or_insert_with(Vec::new)
2799                    .push(cx.subscribe_in(&pop_up, window, {
2800                        |this, _, event, window, cx| match event {
2801                            AgentNotificationEvent::Accepted => {
2802                                let handle = window.window_handle();
2803                                cx.activate(true);
2804
2805                                let workspace_handle = this.workspace.clone();
2806
2807                                // If there are multiple Zed windows, activate the correct one.
2808                                cx.defer(move |cx| {
2809                                    handle
2810                                        .update(cx, |_view, window, _cx| {
2811                                            window.activate_window();
2812
2813                                            if let Some(workspace) = workspace_handle.upgrade() {
2814                                                workspace.update(_cx, |workspace, cx| {
2815                                                    workspace.focus_panel::<AgentPanel>(window, cx);
2816                                                });
2817                                            }
2818                                        })
2819                                        .log_err();
2820                                });
2821
2822                                this.dismiss_notifications(cx);
2823                            }
2824                            AgentNotificationEvent::Dismissed => {
2825                                this.dismiss_notifications(cx);
2826                            }
2827                        }
2828                    }));
2829
2830                self.notifications.push(screen_window);
2831
2832                // If the user manually refocuses the original window, dismiss the popup.
2833                self.notification_subscriptions
2834                    .entry(screen_window)
2835                    .or_insert_with(Vec::new)
2836                    .push({
2837                        let pop_up_weak = pop_up.downgrade();
2838
2839                        cx.observe_window_activation(window, move |_, window, cx| {
2840                            if window.is_window_active() {
2841                                if let Some(pop_up) = pop_up_weak.upgrade() {
2842                                    pop_up.update(cx, |_, cx| {
2843                                        cx.emit(AgentNotificationEvent::Dismissed);
2844                                    });
2845                                }
2846                            }
2847                        })
2848                    });
2849            }
2850        }
2851    }
2852
2853    fn dismiss_notifications(&mut self, cx: &mut Context<Self>) {
2854        for window in self.notifications.drain(..) {
2855            window
2856                .update(cx, |_, window, _| {
2857                    window.remove_window();
2858                })
2859                .ok();
2860
2861            self.notification_subscriptions.remove(&window);
2862        }
2863    }
2864
2865    fn render_thread_controls(&self, cx: &Context<Self>) -> impl IntoElement {
2866        let open_as_markdown = IconButton::new("open-as-markdown", IconName::FileMarkdown)
2867            .icon_size(IconSize::XSmall)
2868            .icon_color(Color::Ignored)
2869            .tooltip(Tooltip::text("Open Thread as Markdown"))
2870            .on_click(cx.listener(move |this, _, window, cx| {
2871                if let Some(workspace) = this.workspace.upgrade() {
2872                    this.open_thread_as_markdown(workspace, window, cx)
2873                        .detach_and_log_err(cx);
2874                }
2875            }));
2876
2877        let scroll_to_top = IconButton::new("scroll_to_top", IconName::ArrowUp)
2878            .icon_size(IconSize::XSmall)
2879            .icon_color(Color::Ignored)
2880            .tooltip(Tooltip::text("Scroll To Top"))
2881            .on_click(cx.listener(move |this, _, _, cx| {
2882                this.scroll_to_top(cx);
2883            }));
2884
2885        h_flex()
2886            .w_full()
2887            .mr_1()
2888            .pb_2()
2889            .gap_1()
2890            .px(RESPONSE_PADDING_X)
2891            .opacity(0.4)
2892            .hover(|style| style.opacity(1.))
2893            .flex_wrap()
2894            .justify_end()
2895            .child(open_as_markdown)
2896            .child(scroll_to_top)
2897    }
2898
2899    fn render_vertical_scrollbar(&self, cx: &mut Context<Self>) -> Stateful<Div> {
2900        div()
2901            .id("acp-thread-scrollbar")
2902            .occlude()
2903            .on_mouse_move(cx.listener(|_, _, _, cx| {
2904                cx.notify();
2905                cx.stop_propagation()
2906            }))
2907            .on_hover(|_, _, cx| {
2908                cx.stop_propagation();
2909            })
2910            .on_any_mouse_down(|_, _, cx| {
2911                cx.stop_propagation();
2912            })
2913            .on_mouse_up(
2914                MouseButton::Left,
2915                cx.listener(|_, _, _, cx| {
2916                    cx.stop_propagation();
2917                }),
2918            )
2919            .on_scroll_wheel(cx.listener(|_, _, _, cx| {
2920                cx.notify();
2921            }))
2922            .h_full()
2923            .absolute()
2924            .right_1()
2925            .top_1()
2926            .bottom_0()
2927            .w(px(12.))
2928            .cursor_default()
2929            .children(Scrollbar::vertical(self.scrollbar_state.clone()).map(|s| s.auto_hide(cx)))
2930    }
2931
2932    fn settings_changed(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
2933        for diff_editor in self.diff_editors.values() {
2934            diff_editor.update(cx, |diff_editor, cx| {
2935                diff_editor.set_text_style_refinement(diff_editor_text_style_refinement(cx));
2936                cx.notify();
2937            })
2938        }
2939    }
2940
2941    pub(crate) fn insert_dragged_files(
2942        &self,
2943        paths: Vec<project::ProjectPath>,
2944        _added_worktrees: Vec<Entity<project::Worktree>>,
2945        window: &mut Window,
2946        cx: &mut Context<'_, Self>,
2947    ) {
2948        let buffer = self.message_editor.read(cx).buffer().clone();
2949        let Some((&excerpt_id, _, _)) = buffer.read(cx).snapshot(cx).as_singleton() else {
2950            return;
2951        };
2952        let Some(buffer) = buffer.read(cx).as_singleton() else {
2953            return;
2954        };
2955        for path in paths {
2956            let Some(entry) = self.project.read(cx).entry_for_path(&path, cx) else {
2957                continue;
2958            };
2959            let Some(abs_path) = self.project.read(cx).absolute_path(&path, cx) else {
2960                continue;
2961            };
2962
2963            let anchor = buffer.update(cx, |buffer, _cx| buffer.anchor_before(buffer.len()));
2964            let path_prefix = abs_path
2965                .file_name()
2966                .unwrap_or(path.path.as_os_str())
2967                .display()
2968                .to_string();
2969            let completion = ContextPickerCompletionProvider::completion_for_path(
2970                path,
2971                &path_prefix,
2972                false,
2973                entry.is_dir(),
2974                excerpt_id,
2975                anchor..anchor,
2976                self.message_editor.clone(),
2977                self.mention_set.clone(),
2978                cx,
2979            );
2980
2981            self.message_editor.update(cx, |message_editor, cx| {
2982                message_editor.edit(
2983                    [(
2984                        multi_buffer::Anchor::max()..multi_buffer::Anchor::max(),
2985                        completion.new_text,
2986                    )],
2987                    cx,
2988                );
2989            });
2990            if let Some(confirm) = completion.confirm.clone() {
2991                confirm(CompletionIntent::Complete, window, cx);
2992            }
2993        }
2994    }
2995}
2996
2997impl Focusable for AcpThreadView {
2998    fn focus_handle(&self, cx: &App) -> FocusHandle {
2999        self.message_editor.focus_handle(cx)
3000    }
3001}
3002
3003impl Render for AcpThreadView {
3004    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
3005        v_flex()
3006            .size_full()
3007            .key_context("AcpThread")
3008            .on_action(cx.listener(Self::chat))
3009            .on_action(cx.listener(Self::previous_history_message))
3010            .on_action(cx.listener(Self::next_history_message))
3011            .on_action(cx.listener(Self::open_agent_diff))
3012            .bg(cx.theme().colors().panel_background)
3013            .child(match &self.thread_state {
3014                ThreadState::Unauthenticated { connection } => v_flex()
3015                    .p_2()
3016                    .flex_1()
3017                    .items_center()
3018                    .justify_center()
3019                    .child(self.render_pending_auth_state())
3020                    .child(h_flex().mt_1p5().justify_center().children(
3021                        connection.auth_methods().into_iter().map(|method| {
3022                            Button::new(
3023                                SharedString::from(method.id.0.clone()),
3024                                method.name.clone(),
3025                            )
3026                            .on_click({
3027                                let method_id = method.id.clone();
3028                                cx.listener(move |this, _, window, cx| {
3029                                    this.authenticate(method_id.clone(), window, cx)
3030                                })
3031                            })
3032                        }),
3033                    )),
3034                ThreadState::Loading { .. } => v_flex().flex_1().child(self.render_empty_state(cx)),
3035                ThreadState::LoadError(e) => v_flex()
3036                    .p_2()
3037                    .flex_1()
3038                    .items_center()
3039                    .justify_center()
3040                    .child(self.render_load_error(e, cx)),
3041                ThreadState::ServerExited { status } => v_flex()
3042                    .p_2()
3043                    .flex_1()
3044                    .items_center()
3045                    .justify_center()
3046                    .child(self.render_server_exited(*status, cx)),
3047                ThreadState::Ready { thread, .. } => {
3048                    let thread_clone = thread.clone();
3049
3050                    v_flex().flex_1().map(|this| {
3051                        if self.list_state.item_count() > 0 {
3052                            this.child(
3053                                list(
3054                                    self.list_state.clone(),
3055                                    cx.processor(|this, index: usize, window, cx| {
3056                                        let Some((entry, len)) = this.thread().and_then(|thread| {
3057                                            let entries = &thread.read(cx).entries();
3058                                            Some((entries.get(index)?, entries.len()))
3059                                        }) else {
3060                                            return Empty.into_any();
3061                                        };
3062                                        this.render_entry(index, len, entry, window, cx)
3063                                    }),
3064                                )
3065                                .with_sizing_behavior(gpui::ListSizingBehavior::Auto)
3066                                .flex_grow()
3067                                .into_any(),
3068                            )
3069                            .child(self.render_vertical_scrollbar(cx))
3070                            .children(match thread_clone.read(cx).status() {
3071                                ThreadStatus::Idle | ThreadStatus::WaitingForToolConfirmation => {
3072                                    None
3073                                }
3074                                ThreadStatus::Generating => div()
3075                                    .px_5()
3076                                    .py_2()
3077                                    .child(LoadingLabel::new("").size(LabelSize::Small))
3078                                    .into(),
3079                            })
3080                            .children(self.render_activity_bar(&thread_clone, window, cx))
3081                        } else {
3082                            this.child(self.render_empty_state(cx))
3083                        }
3084                    })
3085                }
3086            })
3087            .when_some(self.last_error.clone(), |el, error| {
3088                el.child(
3089                    div()
3090                        .p_2()
3091                        .text_xs()
3092                        .border_t_1()
3093                        .border_color(cx.theme().colors().border)
3094                        .bg(cx.theme().status().error_background)
3095                        .child(
3096                            self.render_markdown(error, default_markdown_style(false, window, cx)),
3097                        ),
3098                )
3099            })
3100            .child(self.render_message_editor(window, cx))
3101    }
3102}
3103
3104fn user_message_markdown_style(window: &Window, cx: &App) -> MarkdownStyle {
3105    let mut style = default_markdown_style(false, window, cx);
3106    let mut text_style = window.text_style();
3107    let theme_settings = ThemeSettings::get_global(cx);
3108
3109    let buffer_font = theme_settings.buffer_font.family.clone();
3110    let buffer_font_size = TextSize::Small.rems(cx);
3111
3112    text_style.refine(&TextStyleRefinement {
3113        font_family: Some(buffer_font),
3114        font_size: Some(buffer_font_size.into()),
3115        ..Default::default()
3116    });
3117
3118    style.base_text_style = text_style;
3119    style.link_callback = Some(Rc::new(move |url, cx| {
3120        if MentionPath::try_parse(url).is_some() {
3121            let colors = cx.theme().colors();
3122            Some(TextStyleRefinement {
3123                background_color: Some(colors.element_background),
3124                ..Default::default()
3125            })
3126        } else {
3127            None
3128        }
3129    }));
3130    style
3131}
3132
3133fn default_markdown_style(buffer_font: bool, window: &Window, cx: &App) -> MarkdownStyle {
3134    let theme_settings = ThemeSettings::get_global(cx);
3135    let colors = cx.theme().colors();
3136
3137    let buffer_font_size = TextSize::Small.rems(cx);
3138
3139    let mut text_style = window.text_style();
3140    let line_height = buffer_font_size * 1.75;
3141
3142    let font_family = if buffer_font {
3143        theme_settings.buffer_font.family.clone()
3144    } else {
3145        theme_settings.ui_font.family.clone()
3146    };
3147
3148    let font_size = if buffer_font {
3149        TextSize::Small.rems(cx)
3150    } else {
3151        TextSize::Default.rems(cx)
3152    };
3153
3154    text_style.refine(&TextStyleRefinement {
3155        font_family: Some(font_family),
3156        font_fallbacks: theme_settings.ui_font.fallbacks.clone(),
3157        font_features: Some(theme_settings.ui_font.features.clone()),
3158        font_size: Some(font_size.into()),
3159        line_height: Some(line_height.into()),
3160        color: Some(cx.theme().colors().text),
3161        ..Default::default()
3162    });
3163
3164    MarkdownStyle {
3165        base_text_style: text_style.clone(),
3166        syntax: cx.theme().syntax().clone(),
3167        selection_background_color: cx.theme().colors().element_selection_background,
3168        code_block_overflow_x_scroll: true,
3169        table_overflow_x_scroll: true,
3170        heading_level_styles: Some(HeadingLevelStyles {
3171            h1: Some(TextStyleRefinement {
3172                font_size: Some(rems(1.15).into()),
3173                ..Default::default()
3174            }),
3175            h2: Some(TextStyleRefinement {
3176                font_size: Some(rems(1.1).into()),
3177                ..Default::default()
3178            }),
3179            h3: Some(TextStyleRefinement {
3180                font_size: Some(rems(1.05).into()),
3181                ..Default::default()
3182            }),
3183            h4: Some(TextStyleRefinement {
3184                font_size: Some(rems(1.).into()),
3185                ..Default::default()
3186            }),
3187            h5: Some(TextStyleRefinement {
3188                font_size: Some(rems(0.95).into()),
3189                ..Default::default()
3190            }),
3191            h6: Some(TextStyleRefinement {
3192                font_size: Some(rems(0.875).into()),
3193                ..Default::default()
3194            }),
3195        }),
3196        code_block: StyleRefinement {
3197            padding: EdgesRefinement {
3198                top: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
3199                left: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
3200                right: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
3201                bottom: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
3202            },
3203            margin: EdgesRefinement {
3204                top: Some(Length::Definite(Pixels(8.).into())),
3205                left: Some(Length::Definite(Pixels(0.).into())),
3206                right: Some(Length::Definite(Pixels(0.).into())),
3207                bottom: Some(Length::Definite(Pixels(12.).into())),
3208            },
3209            border_style: Some(BorderStyle::Solid),
3210            border_widths: EdgesRefinement {
3211                top: Some(AbsoluteLength::Pixels(Pixels(1.))),
3212                left: Some(AbsoluteLength::Pixels(Pixels(1.))),
3213                right: Some(AbsoluteLength::Pixels(Pixels(1.))),
3214                bottom: Some(AbsoluteLength::Pixels(Pixels(1.))),
3215            },
3216            border_color: Some(colors.border_variant),
3217            background: Some(colors.editor_background.into()),
3218            text: Some(TextStyleRefinement {
3219                font_family: Some(theme_settings.buffer_font.family.clone()),
3220                font_fallbacks: theme_settings.buffer_font.fallbacks.clone(),
3221                font_features: Some(theme_settings.buffer_font.features.clone()),
3222                font_size: Some(buffer_font_size.into()),
3223                ..Default::default()
3224            }),
3225            ..Default::default()
3226        },
3227        inline_code: TextStyleRefinement {
3228            font_family: Some(theme_settings.buffer_font.family.clone()),
3229            font_fallbacks: theme_settings.buffer_font.fallbacks.clone(),
3230            font_features: Some(theme_settings.buffer_font.features.clone()),
3231            font_size: Some(buffer_font_size.into()),
3232            background_color: Some(colors.editor_foreground.opacity(0.08)),
3233            ..Default::default()
3234        },
3235        link: TextStyleRefinement {
3236            background_color: Some(colors.editor_foreground.opacity(0.025)),
3237            underline: Some(UnderlineStyle {
3238                color: Some(colors.text_accent.opacity(0.5)),
3239                thickness: px(1.),
3240                ..Default::default()
3241            }),
3242            ..Default::default()
3243        },
3244        ..Default::default()
3245    }
3246}
3247
3248fn plan_label_markdown_style(
3249    status: &acp::PlanEntryStatus,
3250    window: &Window,
3251    cx: &App,
3252) -> MarkdownStyle {
3253    let default_md_style = default_markdown_style(false, window, cx);
3254
3255    MarkdownStyle {
3256        base_text_style: TextStyle {
3257            color: cx.theme().colors().text_muted,
3258            strikethrough: if matches!(status, acp::PlanEntryStatus::Completed) {
3259                Some(gpui::StrikethroughStyle {
3260                    thickness: px(1.),
3261                    color: Some(cx.theme().colors().text_muted.opacity(0.8)),
3262                })
3263            } else {
3264                None
3265            },
3266            ..default_md_style.base_text_style
3267        },
3268        ..default_md_style
3269    }
3270}
3271
3272fn diff_editor_text_style_refinement(cx: &mut App) -> TextStyleRefinement {
3273    TextStyleRefinement {
3274        font_size: Some(
3275            TextSize::Small
3276                .rems(cx)
3277                .to_pixels(ThemeSettings::get_global(cx).agent_font_size(cx))
3278                .into(),
3279        ),
3280        ..Default::default()
3281    }
3282}
3283
3284fn terminal_command_markdown_style(window: &Window, cx: &App) -> MarkdownStyle {
3285    let default_md_style = default_markdown_style(true, window, cx);
3286
3287    MarkdownStyle {
3288        base_text_style: TextStyle {
3289            ..default_md_style.base_text_style
3290        },
3291        selection_background_color: cx.theme().colors().element_selection_background,
3292        ..Default::default()
3293    }
3294}
3295
3296#[cfg(test)]
3297mod tests {
3298    use agent_client_protocol::SessionId;
3299    use editor::EditorSettings;
3300    use fs::FakeFs;
3301    use futures::future::try_join_all;
3302    use gpui::{SemanticVersion, TestAppContext, VisualTestContext};
3303    use lsp::{CompletionContext, CompletionTriggerKind};
3304    use project::CompletionIntent;
3305    use rand::Rng;
3306    use serde_json::json;
3307    use settings::SettingsStore;
3308    use util::path;
3309
3310    use super::*;
3311
3312    #[gpui::test]
3313    async fn test_drop(cx: &mut TestAppContext) {
3314        init_test(cx);
3315
3316        let (thread_view, _cx) = setup_thread_view(StubAgentServer::default(), cx).await;
3317        let weak_view = thread_view.downgrade();
3318        drop(thread_view);
3319        assert!(!weak_view.is_upgradable());
3320    }
3321
3322    #[gpui::test]
3323    async fn test_notification_for_stop_event(cx: &mut TestAppContext) {
3324        init_test(cx);
3325
3326        let (thread_view, cx) = setup_thread_view(StubAgentServer::default(), cx).await;
3327
3328        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
3329        message_editor.update_in(cx, |editor, window, cx| {
3330            editor.set_text("Hello", window, cx);
3331        });
3332
3333        cx.deactivate_window();
3334
3335        thread_view.update_in(cx, |thread_view, window, cx| {
3336            thread_view.chat(&Chat, window, cx);
3337        });
3338
3339        cx.run_until_parked();
3340
3341        assert!(
3342            cx.windows()
3343                .iter()
3344                .any(|window| window.downcast::<AgentNotification>().is_some())
3345        );
3346    }
3347
3348    #[gpui::test]
3349    async fn test_notification_for_error(cx: &mut TestAppContext) {
3350        init_test(cx);
3351
3352        let (thread_view, cx) =
3353            setup_thread_view(StubAgentServer::new(SaboteurAgentConnection), cx).await;
3354
3355        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
3356        message_editor.update_in(cx, |editor, window, cx| {
3357            editor.set_text("Hello", window, cx);
3358        });
3359
3360        cx.deactivate_window();
3361
3362        thread_view.update_in(cx, |thread_view, window, cx| {
3363            thread_view.chat(&Chat, window, cx);
3364        });
3365
3366        cx.run_until_parked();
3367
3368        assert!(
3369            cx.windows()
3370                .iter()
3371                .any(|window| window.downcast::<AgentNotification>().is_some())
3372        );
3373    }
3374
3375    #[gpui::test]
3376    async fn test_notification_for_tool_authorization(cx: &mut TestAppContext) {
3377        init_test(cx);
3378
3379        let tool_call_id = acp::ToolCallId("1".into());
3380        let tool_call = acp::ToolCall {
3381            id: tool_call_id.clone(),
3382            title: "Label".into(),
3383            kind: acp::ToolKind::Edit,
3384            status: acp::ToolCallStatus::Pending,
3385            content: vec!["hi".into()],
3386            locations: vec![],
3387            raw_input: None,
3388            raw_output: None,
3389        };
3390        let connection = StubAgentConnection::new(vec![acp::SessionUpdate::ToolCall(tool_call)])
3391            .with_permission_requests(HashMap::from_iter([(
3392                tool_call_id,
3393                vec![acp::PermissionOption {
3394                    id: acp::PermissionOptionId("1".into()),
3395                    name: "Allow".into(),
3396                    kind: acp::PermissionOptionKind::AllowOnce,
3397                }],
3398            )]));
3399        let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
3400
3401        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
3402        message_editor.update_in(cx, |editor, window, cx| {
3403            editor.set_text("Hello", window, cx);
3404        });
3405
3406        cx.deactivate_window();
3407
3408        thread_view.update_in(cx, |thread_view, window, cx| {
3409            thread_view.chat(&Chat, window, cx);
3410        });
3411
3412        cx.run_until_parked();
3413
3414        assert!(
3415            cx.windows()
3416                .iter()
3417                .any(|window| window.downcast::<AgentNotification>().is_some())
3418        );
3419    }
3420
3421    #[gpui::test]
3422    async fn test_crease_removal(cx: &mut TestAppContext) {
3423        init_test(cx);
3424
3425        let fs = FakeFs::new(cx.executor());
3426        fs.insert_tree("/project", json!({"file": ""})).await;
3427        let project = Project::test(fs, [Path::new(path!("/project"))], cx).await;
3428        let agent = StubAgentServer::default();
3429        let (workspace, cx) =
3430            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
3431        let thread_view = cx.update(|window, cx| {
3432            cx.new(|cx| {
3433                AcpThreadView::new(
3434                    Rc::new(agent),
3435                    workspace.downgrade(),
3436                    project,
3437                    Rc::new(RefCell::new(MessageHistory::default())),
3438                    1,
3439                    None,
3440                    window,
3441                    cx,
3442                )
3443            })
3444        });
3445
3446        cx.run_until_parked();
3447
3448        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
3449        let excerpt_id = message_editor.update(cx, |editor, cx| {
3450            editor
3451                .buffer()
3452                .read(cx)
3453                .excerpt_ids()
3454                .into_iter()
3455                .next()
3456                .unwrap()
3457        });
3458        let completions = message_editor.update_in(cx, |editor, window, cx| {
3459            editor.set_text("Hello @", window, cx);
3460            let buffer = editor.buffer().read(cx).as_singleton().unwrap();
3461            let completion_provider = editor.completion_provider().unwrap();
3462            completion_provider.completions(
3463                excerpt_id,
3464                &buffer,
3465                Anchor::MAX,
3466                CompletionContext {
3467                    trigger_kind: CompletionTriggerKind::TRIGGER_CHARACTER,
3468                    trigger_character: Some("@".into()),
3469                },
3470                window,
3471                cx,
3472            )
3473        });
3474        let [_, completion]: [_; 2] = completions
3475            .await
3476            .unwrap()
3477            .into_iter()
3478            .flat_map(|response| response.completions)
3479            .collect::<Vec<_>>()
3480            .try_into()
3481            .unwrap();
3482
3483        message_editor.update_in(cx, |editor, window, cx| {
3484            let snapshot = editor.buffer().read(cx).snapshot(cx);
3485            let start = snapshot
3486                .anchor_in_excerpt(excerpt_id, completion.replace_range.start)
3487                .unwrap();
3488            let end = snapshot
3489                .anchor_in_excerpt(excerpt_id, completion.replace_range.end)
3490                .unwrap();
3491            editor.edit([(start..end, completion.new_text)], cx);
3492            (completion.confirm.unwrap())(CompletionIntent::Complete, window, cx);
3493        });
3494
3495        cx.run_until_parked();
3496
3497        // Backspace over the inserted crease (and the following space).
3498        message_editor.update_in(cx, |editor, window, cx| {
3499            editor.backspace(&Default::default(), window, cx);
3500            editor.backspace(&Default::default(), window, cx);
3501        });
3502
3503        thread_view.update_in(cx, |thread_view, window, cx| {
3504            thread_view.chat(&Chat, window, cx);
3505        });
3506
3507        cx.run_until_parked();
3508
3509        let content = thread_view.update_in(cx, |thread_view, _window, _cx| {
3510            thread_view
3511                .message_history
3512                .borrow()
3513                .items()
3514                .iter()
3515                .flatten()
3516                .cloned()
3517                .collect::<Vec<_>>()
3518        });
3519
3520        // We don't send a resource link for the deleted crease.
3521        pretty_assertions::assert_matches!(content.as_slice(), [acp::ContentBlock::Text { .. }]);
3522    }
3523
3524    async fn setup_thread_view(
3525        agent: impl AgentServer + 'static,
3526        cx: &mut TestAppContext,
3527    ) -> (Entity<AcpThreadView>, &mut VisualTestContext) {
3528        let fs = FakeFs::new(cx.executor());
3529        let project = Project::test(fs, [], cx).await;
3530        let (workspace, cx) =
3531            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
3532
3533        let thread_view = cx.update(|window, cx| {
3534            cx.new(|cx| {
3535                AcpThreadView::new(
3536                    Rc::new(agent),
3537                    workspace.downgrade(),
3538                    project,
3539                    Rc::new(RefCell::new(MessageHistory::default())),
3540                    1,
3541                    None,
3542                    window,
3543                    cx,
3544                )
3545            })
3546        });
3547        cx.run_until_parked();
3548        (thread_view, cx)
3549    }
3550
3551    struct StubAgentServer<C> {
3552        connection: C,
3553    }
3554
3555    impl<C> StubAgentServer<C> {
3556        fn new(connection: C) -> Self {
3557            Self { connection }
3558        }
3559    }
3560
3561    impl StubAgentServer<StubAgentConnection> {
3562        fn default() -> Self {
3563            Self::new(StubAgentConnection::default())
3564        }
3565    }
3566
3567    impl<C> AgentServer for StubAgentServer<C>
3568    where
3569        C: 'static + AgentConnection + Send + Clone,
3570    {
3571        fn logo(&self) -> ui::IconName {
3572            unimplemented!()
3573        }
3574
3575        fn name(&self) -> &'static str {
3576            unimplemented!()
3577        }
3578
3579        fn empty_state_headline(&self) -> &'static str {
3580            unimplemented!()
3581        }
3582
3583        fn empty_state_message(&self) -> &'static str {
3584            unimplemented!()
3585        }
3586
3587        fn connect(
3588            &self,
3589            _root_dir: &Path,
3590            _project: &Entity<Project>,
3591            _cx: &mut App,
3592        ) -> Task<gpui::Result<Rc<dyn AgentConnection>>> {
3593            Task::ready(Ok(Rc::new(self.connection.clone())))
3594        }
3595    }
3596
3597    #[derive(Clone, Default)]
3598    struct StubAgentConnection {
3599        sessions: Arc<Mutex<HashMap<acp::SessionId, WeakEntity<AcpThread>>>>,
3600        permission_requests: HashMap<acp::ToolCallId, Vec<acp::PermissionOption>>,
3601        updates: Vec<acp::SessionUpdate>,
3602    }
3603
3604    impl StubAgentConnection {
3605        fn new(updates: Vec<acp::SessionUpdate>) -> Self {
3606            Self {
3607                updates,
3608                permission_requests: HashMap::default(),
3609                sessions: Arc::default(),
3610            }
3611        }
3612
3613        fn with_permission_requests(
3614            mut self,
3615            permission_requests: HashMap<acp::ToolCallId, Vec<acp::PermissionOption>>,
3616        ) -> Self {
3617            self.permission_requests = permission_requests;
3618            self
3619        }
3620    }
3621
3622    impl AgentConnection for StubAgentConnection {
3623        fn auth_methods(&self) -> &[acp::AuthMethod] {
3624            &[]
3625        }
3626
3627        fn new_thread(
3628            self: Rc<Self>,
3629            project: Entity<Project>,
3630            _cwd: &Path,
3631            cx: &mut gpui::AsyncApp,
3632        ) -> Task<gpui::Result<Entity<AcpThread>>> {
3633            let session_id = SessionId(
3634                rand::thread_rng()
3635                    .sample_iter(&rand::distributions::Alphanumeric)
3636                    .take(7)
3637                    .map(char::from)
3638                    .collect::<String>()
3639                    .into(),
3640            );
3641            let thread = cx
3642                .new(|cx| AcpThread::new("Test", self.clone(), project, session_id.clone(), cx))
3643                .unwrap();
3644            self.sessions.lock().insert(session_id, thread.downgrade());
3645            Task::ready(Ok(thread))
3646        }
3647
3648        fn authenticate(
3649            &self,
3650            _method_id: acp::AuthMethodId,
3651            _cx: &mut App,
3652        ) -> Task<gpui::Result<()>> {
3653            unimplemented!()
3654        }
3655
3656        fn prompt(
3657            &self,
3658            params: acp::PromptRequest,
3659            cx: &mut App,
3660        ) -> Task<gpui::Result<acp::PromptResponse>> {
3661            let sessions = self.sessions.lock();
3662            let thread = sessions.get(&params.session_id).unwrap();
3663            let mut tasks = vec![];
3664            for update in &self.updates {
3665                let thread = thread.clone();
3666                let update = update.clone();
3667                let permission_request = if let acp::SessionUpdate::ToolCall(tool_call) = &update
3668                    && let Some(options) = self.permission_requests.get(&tool_call.id)
3669                {
3670                    Some((tool_call.clone(), options.clone()))
3671                } else {
3672                    None
3673                };
3674                let task = cx.spawn(async move |cx| {
3675                    if let Some((tool_call, options)) = permission_request {
3676                        let permission = thread.update(cx, |thread, cx| {
3677                            thread.request_tool_call_authorization(
3678                                tool_call.clone(),
3679                                options.clone(),
3680                                cx,
3681                            )
3682                        })?;
3683                        permission.await?;
3684                    }
3685                    thread.update(cx, |thread, cx| {
3686                        thread.handle_session_update(update.clone(), cx).unwrap();
3687                    })?;
3688                    anyhow::Ok(())
3689                });
3690                tasks.push(task);
3691            }
3692            cx.spawn(async move |_| {
3693                try_join_all(tasks).await?;
3694                Ok(acp::PromptResponse {
3695                    stop_reason: acp::StopReason::EndTurn,
3696                })
3697            })
3698        }
3699
3700        fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {
3701            unimplemented!()
3702        }
3703    }
3704
3705    #[derive(Clone)]
3706    struct SaboteurAgentConnection;
3707
3708    impl AgentConnection for SaboteurAgentConnection {
3709        fn new_thread(
3710            self: Rc<Self>,
3711            project: Entity<Project>,
3712            _cwd: &Path,
3713            cx: &mut gpui::AsyncApp,
3714        ) -> Task<gpui::Result<Entity<AcpThread>>> {
3715            Task::ready(Ok(cx
3716                .new(|cx| {
3717                    AcpThread::new(
3718                        "SaboteurAgentConnection",
3719                        self,
3720                        project,
3721                        SessionId("test".into()),
3722                        cx,
3723                    )
3724                })
3725                .unwrap()))
3726        }
3727
3728        fn auth_methods(&self) -> &[acp::AuthMethod] {
3729            &[]
3730        }
3731
3732        fn authenticate(
3733            &self,
3734            _method_id: acp::AuthMethodId,
3735            _cx: &mut App,
3736        ) -> Task<gpui::Result<()>> {
3737            unimplemented!()
3738        }
3739
3740        fn prompt(
3741            &self,
3742            _params: acp::PromptRequest,
3743            _cx: &mut App,
3744        ) -> Task<gpui::Result<acp::PromptResponse>> {
3745            Task::ready(Err(anyhow::anyhow!("Error prompting")))
3746        }
3747
3748        fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {
3749            unimplemented!()
3750        }
3751    }
3752
3753    fn init_test(cx: &mut TestAppContext) {
3754        cx.update(|cx| {
3755            let settings_store = SettingsStore::test(cx);
3756            cx.set_global(settings_store);
3757            language::init(cx);
3758            Project::init_settings(cx);
3759            AgentSettings::register(cx);
3760            workspace::init_settings(cx);
3761            ThemeSettings::register(cx);
3762            release_channel::init(SemanticVersion::default(), cx);
3763            EditorSettings::register(cx);
3764        });
3765    }
3766}