thread_view.rs

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