thread_view.rs

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