thread_view.rs

   1use acp_thread::Plan;
   2use agent_servers::AgentServer;
   3use std::cell::RefCell;
   4use std::collections::BTreeMap;
   5use std::path::Path;
   6use std::rc::Rc;
   7use std::sync::Arc;
   8use std::time::Duration;
   9
  10use agent_client_protocol as acp;
  11use assistant_tool::ActionLog;
  12use buffer_diff::BufferDiff;
  13use collections::{HashMap, HashSet};
  14use editor::{
  15    AnchorRangeExt, ContextMenuOptions, ContextMenuPlacement, Editor, EditorElement, EditorMode,
  16    EditorStyle, MinimapVisibility, MultiBuffer, PathKey,
  17};
  18use file_icons::FileIcons;
  19use futures::channel::oneshot;
  20use gpui::{
  21    Action, Animation, AnimationExt, App, BorderStyle, EdgesRefinement, Empty, Entity, EntityId,
  22    FocusHandle, Focusable, Hsla, Length, ListOffset, ListState, SharedString, StyleRefinement,
  23    Subscription, Task, TextStyle, TextStyleRefinement, Transformation, UnderlineStyle, WeakEntity,
  24    Window, div, linear_color_stop, linear_gradient, list, percentage, point, prelude::*,
  25    pulsating_between,
  26};
  27use language::language_settings::SoftWrap;
  28use language::{Buffer, Language};
  29use markdown::{HeadingLevelStyles, Markdown, MarkdownElement, MarkdownStyle};
  30use parking_lot::Mutex;
  31use project::Project;
  32use settings::Settings as _;
  33use text::Anchor;
  34use theme::ThemeSettings;
  35use ui::{Disclosure, Divider, DividerColor, KeyBinding, Tooltip, prelude::*};
  36use util::ResultExt;
  37use workspace::{CollaboratorId, Workspace};
  38use zed_actions::agent::{Chat, NextHistoryMessage, PreviousHistoryMessage};
  39
  40use ::acp_thread::{
  41    AcpThread, AcpThreadEvent, AgentThreadEntry, AssistantMessage, AssistantMessageChunk, Diff,
  42    LoadError, MentionPath, ThreadStatus, ToolCall, ToolCallContent, ToolCallStatus,
  43};
  44
  45use crate::acp::completion_provider::{ContextPickerCompletionProvider, MentionSet};
  46use crate::acp::message_history::MessageHistory;
  47use crate::agent_diff::AgentDiff;
  48use crate::message_editor::{MAX_EDITOR_LINES, MIN_EDITOR_LINES};
  49use crate::{AgentDiffPane, ExpandMessageEditor, Follow, KeepAll, OpenAgentDiff, RejectAll};
  50
  51const RESPONSE_PADDING_X: Pixels = px(19.);
  52
  53pub struct AcpThreadView {
  54    agent: Rc<dyn AgentServer>,
  55    workspace: WeakEntity<Workspace>,
  56    project: Entity<Project>,
  57    thread_state: ThreadState,
  58    diff_editors: HashMap<EntityId, Entity<Editor>>,
  59    message_editor: Entity<Editor>,
  60    message_set_from_history: bool,
  61    _message_editor_subscription: Subscription,
  62    mention_set: Arc<Mutex<MentionSet>>,
  63    last_error: Option<Entity<Markdown>>,
  64    list_state: ListState,
  65    auth_task: Option<Task<()>>,
  66    expanded_tool_calls: HashSet<acp::ToolCallId>,
  67    expanded_thinking_blocks: HashSet<(usize, usize)>,
  68    edits_expanded: bool,
  69    plan_expanded: bool,
  70    editor_expanded: bool,
  71    message_history: Rc<RefCell<MessageHistory<Vec<acp::ContentBlock>>>>,
  72}
  73
  74enum ThreadState {
  75    Loading {
  76        _task: Task<()>,
  77    },
  78    Ready {
  79        thread: Entity<AcpThread>,
  80        _subscription: [Subscription; 2],
  81    },
  82    LoadError(LoadError),
  83    Unauthenticated,
  84}
  85
  86impl AcpThreadView {
  87    pub fn new(
  88        agent: Rc<dyn AgentServer>,
  89        workspace: WeakEntity<Workspace>,
  90        project: Entity<Project>,
  91        message_history: Rc<RefCell<MessageHistory<Vec<acp::ContentBlock>>>>,
  92        min_lines: usize,
  93        max_lines: Option<usize>,
  94        window: &mut Window,
  95        cx: &mut Context<Self>,
  96    ) -> Self {
  97        let language = Language::new(
  98            language::LanguageConfig {
  99                completion_query_characters: HashSet::from_iter(['.', '-', '_', '@']),
 100                ..Default::default()
 101            },
 102            None,
 103        );
 104
 105        let mention_set = Arc::new(Mutex::new(MentionSet::default()));
 106
 107        let message_editor = cx.new(|cx| {
 108            let buffer = cx.new(|cx| Buffer::local("", cx).with_language(Arc::new(language), cx));
 109            let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 110
 111            let mut editor = Editor::new(
 112                editor::EditorMode::AutoHeight {
 113                    min_lines,
 114                    max_lines: max_lines,
 115                },
 116                buffer,
 117                None,
 118                window,
 119                cx,
 120            );
 121            editor.set_placeholder_text("Message the agent - @ to include files", cx);
 122            editor.set_show_indent_guides(false, cx);
 123            editor.set_soft_wrap();
 124            editor.set_use_modal_editing(true);
 125            editor.set_completion_provider(Some(Rc::new(ContextPickerCompletionProvider::new(
 126                mention_set.clone(),
 127                workspace.clone(),
 128                cx.weak_entity(),
 129            ))));
 130            editor.set_context_menu_options(ContextMenuOptions {
 131                min_entries_visible: 12,
 132                max_entries_visible: 12,
 133                placement: Some(ContextMenuPlacement::Above),
 134            });
 135            editor
 136        });
 137
 138        let message_editor_subscription = cx.subscribe(&message_editor, |this, _, event, _| {
 139            if let editor::EditorEvent::BufferEdited = &event {
 140                if !this.message_set_from_history {
 141                    this.message_history.borrow_mut().reset_position();
 142                }
 143                this.message_set_from_history = false;
 144            }
 145        });
 146
 147        let mention_set = mention_set.clone();
 148
 149        let list_state = ListState::new(
 150            0,
 151            gpui::ListAlignment::Bottom,
 152            px(2048.0),
 153            cx.processor({
 154                move |this: &mut Self, index: usize, window, cx| {
 155                    let Some((entry, len)) = this.thread().and_then(|thread| {
 156                        let entries = &thread.read(cx).entries();
 157                        Some((entries.get(index)?, entries.len()))
 158                    }) else {
 159                        return Empty.into_any();
 160                    };
 161                    this.render_entry(index, len, entry, window, cx)
 162                }
 163            }),
 164        );
 165
 166        Self {
 167            agent: agent.clone(),
 168            workspace: workspace.clone(),
 169            project: project.clone(),
 170            thread_state: Self::initial_state(agent, workspace, project, window, cx),
 171            message_editor,
 172            message_set_from_history: false,
 173            _message_editor_subscription: message_editor_subscription,
 174            mention_set,
 175            diff_editors: Default::default(),
 176            list_state: list_state,
 177            last_error: None,
 178            auth_task: None,
 179            expanded_tool_calls: HashSet::default(),
 180            expanded_thinking_blocks: HashSet::default(),
 181            edits_expanded: false,
 182            plan_expanded: false,
 183            editor_expanded: false,
 184            message_history,
 185        }
 186    }
 187
 188    fn initial_state(
 189        agent: Rc<dyn AgentServer>,
 190        workspace: WeakEntity<Workspace>,
 191        project: Entity<Project>,
 192        window: &mut Window,
 193        cx: &mut Context<Self>,
 194    ) -> ThreadState {
 195        let root_dir = project
 196            .read(cx)
 197            .visible_worktrees(cx)
 198            .next()
 199            .map(|worktree| worktree.read(cx).abs_path())
 200            .unwrap_or_else(|| paths::home_dir().as_path().into());
 201
 202        let connect_task = agent.connect(&root_dir, &project, cx);
 203        let load_task = cx.spawn_in(window, async move |this, cx| {
 204            let connection = match connect_task.await {
 205                Ok(thread) => thread,
 206                Err(err) => {
 207                    this.update(cx, |this, cx| {
 208                        this.handle_load_error(err, cx);
 209                        cx.notify();
 210                    })
 211                    .log_err();
 212                    return;
 213                }
 214            };
 215
 216            let result = match connection
 217                .new_thread(project.clone(), &root_dir, connection.clone(), cx)
 218                .await
 219            {
 220                Err(e) => {
 221                    let mut cx = cx.clone();
 222                    if e.downcast_ref::<oneshot::Canceled>().is_some() {
 223                        // todo! get from connection
 224                        // let child_status = thread
 225                        //     .update(&mut cx, |thread, _| thread.child_status())
 226                        //     .ok()
 227                        //     .flatten();
 228                        // if let Some(child_status) = child_status {
 229                        //     match child_status.await {
 230                        //         Ok(_) => Err(e),
 231                        //         Err(e) => Err(e),
 232                        //     }
 233                        // } else {
 234                        Err(e)
 235                        // }
 236                    } else if e.downcast_ref::<acp_thread::Unauthenticated>().is_some() {
 237                        this.update(&mut cx, |this, cx| {
 238                            this.thread_state = ThreadState::Unauthenticated;
 239                            cx.notify();
 240                        })
 241                        .ok();
 242                        return;
 243                    } else {
 244                        Err(e)
 245                    }
 246                }
 247                Ok(session_id) => Ok(session_id),
 248            };
 249
 250            this.update_in(cx, |this, window, cx| {
 251                match result {
 252                    Ok(thread) => {
 253                        let thread_subscription =
 254                            cx.subscribe_in(&thread, window, Self::handle_thread_event);
 255
 256                        let action_log = thread.read(cx).action_log().clone();
 257                        let action_log_subscription =
 258                            cx.observe(&action_log, |_, _, cx| cx.notify());
 259
 260                        this.list_state
 261                            .splice(0..0, thread.read(cx).entries().len());
 262
 263                        AgentDiff::set_active_thread(&workspace, thread.clone(), window, cx);
 264
 265                        this.thread_state = ThreadState::Ready {
 266                            thread,
 267                            _subscription: [thread_subscription, action_log_subscription],
 268                        };
 269
 270                        cx.notify();
 271                    }
 272                    Err(err) => {
 273                        this.handle_load_error(err, cx);
 274                    }
 275                };
 276            })
 277            .log_err();
 278        });
 279
 280        ThreadState::Loading { _task: load_task }
 281    }
 282
 283    fn handle_load_error(&mut self, err: anyhow::Error, cx: &mut Context<Self>) {
 284        if let Some(load_err) = err.downcast_ref::<LoadError>() {
 285            self.thread_state = ThreadState::LoadError(load_err.clone());
 286        } else {
 287            self.thread_state = ThreadState::LoadError(LoadError::Other(err.to_string().into()))
 288        }
 289        cx.notify();
 290    }
 291
 292    pub fn thread(&self) -> Option<&Entity<AcpThread>> {
 293        match &self.thread_state {
 294            ThreadState::Ready { thread, .. } => Some(thread),
 295            // todo! we were previously returning a thread from Unauthenticated. check it's ok not to.
 296            ThreadState::Unauthenticated
 297            | ThreadState::Loading { .. }
 298            | ThreadState::LoadError(..) => None,
 299        }
 300    }
 301
 302    pub fn title(&self, cx: &App) -> SharedString {
 303        match &self.thread_state {
 304            ThreadState::Ready { thread, .. } => thread.read(cx).title(),
 305            ThreadState::Loading { .. } => "Loading…".into(),
 306            ThreadState::LoadError(_) => "Failed to load".into(),
 307            ThreadState::Unauthenticated { .. } => "Not authenticated".into(),
 308        }
 309    }
 310
 311    pub fn cancel(&mut self, cx: &mut Context<Self>) {
 312        self.last_error.take();
 313
 314        if let Some(thread) = self.thread() {
 315            thread.update(cx, |thread, cx| thread.cancel(cx)).detach();
 316        }
 317    }
 318
 319    pub fn expand_message_editor(
 320        &mut self,
 321        _: &ExpandMessageEditor,
 322        _window: &mut Window,
 323        cx: &mut Context<Self>,
 324    ) {
 325        self.set_editor_is_expanded(!self.editor_expanded, cx);
 326        cx.notify();
 327    }
 328
 329    fn set_editor_is_expanded(&mut self, is_expanded: bool, cx: &mut Context<Self>) {
 330        self.editor_expanded = is_expanded;
 331        self.message_editor.update(cx, |editor, _| {
 332            if self.editor_expanded {
 333                editor.set_mode(EditorMode::Full {
 334                    scale_ui_elements_with_buffer_font_size: false,
 335                    show_active_line_background: false,
 336                    sized_by_content: false,
 337                })
 338            } else {
 339                editor.set_mode(EditorMode::AutoHeight {
 340                    min_lines: MIN_EDITOR_LINES,
 341                    max_lines: Some(MAX_EDITOR_LINES),
 342                })
 343            }
 344        });
 345        cx.notify();
 346    }
 347
 348    fn chat(&mut self, _: &Chat, window: &mut Window, cx: &mut Context<Self>) {
 349        self.last_error.take();
 350
 351        let mut ix = 0;
 352        let mut chunks: Vec<acp::ContentBlock> = Vec::new();
 353        let project = self.project.clone();
 354        self.message_editor.update(cx, |editor, cx| {
 355            let text = editor.text(cx);
 356            editor.display_map.update(cx, |map, cx| {
 357                let snapshot = map.snapshot(cx);
 358                for (crease_id, crease) in snapshot.crease_snapshot.creases() {
 359                    if let Some(project_path) =
 360                        self.mention_set.lock().path_for_crease_id(crease_id)
 361                    {
 362                        let crease_range = crease.range().to_offset(&snapshot.buffer_snapshot);
 363                        if crease_range.start > ix {
 364                            chunks.push(text[ix..crease_range.start].into());
 365                        }
 366                        if let Some(abs_path) = project.read(cx).absolute_path(&project_path, cx) {
 367                            let path_str = abs_path.display().to_string();
 368                            chunks.push(acp::ContentBlock::ResourceLink(acp::ResourceLink {
 369                                uri: path_str.clone(),
 370                                name: path_str,
 371                                annotations: None,
 372                                description: None,
 373                                mime_type: None,
 374                                size: None,
 375                                title: None,
 376                            }));
 377                        }
 378                        ix = crease_range.end;
 379                    }
 380                }
 381
 382                if ix < text.len() {
 383                    let last_chunk = text[ix..].trim();
 384                    if !last_chunk.is_empty() {
 385                        chunks.push(last_chunk.into());
 386                    }
 387                }
 388            })
 389        });
 390
 391        if chunks.is_empty() {
 392            return;
 393        }
 394
 395        let Some(thread) = self.thread() else { return };
 396        let task = thread.update(cx, |thread, cx| thread.send(chunks.clone(), cx));
 397
 398        cx.spawn(async move |this, cx| {
 399            let result = task.await;
 400
 401            this.update(cx, |this, cx| {
 402                if let Err(err) = result {
 403                    this.last_error =
 404                        Some(cx.new(|cx| Markdown::new(err.to_string().into(), None, None, cx)))
 405                }
 406            })
 407        })
 408        .detach();
 409
 410        let mention_set = self.mention_set.clone();
 411
 412        self.set_editor_is_expanded(false, cx);
 413        self.message_editor.update(cx, |editor, cx| {
 414            editor.clear(window, cx);
 415            editor.remove_creases(mention_set.lock().drain(), cx)
 416        });
 417
 418        self.message_history.borrow_mut().push(chunks);
 419    }
 420
 421    fn previous_history_message(
 422        &mut self,
 423        _: &PreviousHistoryMessage,
 424        window: &mut Window,
 425        cx: &mut Context<Self>,
 426    ) {
 427        self.message_set_from_history = Self::set_draft_message(
 428            self.message_editor.clone(),
 429            self.mention_set.clone(),
 430            self.project.clone(),
 431            self.message_history.borrow_mut().prev(),
 432            window,
 433            cx,
 434        );
 435    }
 436
 437    fn next_history_message(
 438        &mut self,
 439        _: &NextHistoryMessage,
 440        window: &mut Window,
 441        cx: &mut Context<Self>,
 442    ) {
 443        self.message_set_from_history = Self::set_draft_message(
 444            self.message_editor.clone(),
 445            self.mention_set.clone(),
 446            self.project.clone(),
 447            self.message_history.borrow_mut().next(),
 448            window,
 449            cx,
 450        );
 451    }
 452
 453    fn open_agent_diff(&mut self, _: &OpenAgentDiff, window: &mut Window, cx: &mut Context<Self>) {
 454        if let Some(thread) = self.thread() {
 455            AgentDiffPane::deploy(thread.clone(), self.workspace.clone(), window, cx).log_err();
 456        }
 457    }
 458
 459    fn open_edited_buffer(
 460        &mut self,
 461        buffer: &Entity<Buffer>,
 462        window: &mut Window,
 463        cx: &mut Context<Self>,
 464    ) {
 465        let Some(thread) = self.thread() else {
 466            return;
 467        };
 468
 469        let Some(diff) =
 470            AgentDiffPane::deploy(thread.clone(), self.workspace.clone(), window, cx).log_err()
 471        else {
 472            return;
 473        };
 474
 475        diff.update(cx, |diff, cx| {
 476            diff.move_to_path(PathKey::for_buffer(&buffer, cx), window, cx)
 477        })
 478    }
 479
 480    fn set_draft_message(
 481        message_editor: Entity<Editor>,
 482        mention_set: Arc<Mutex<MentionSet>>,
 483        project: Entity<Project>,
 484        message: Option<&Vec<acp::ContentBlock>>,
 485        window: &mut Window,
 486        cx: &mut Context<Self>,
 487    ) -> bool {
 488        cx.notify();
 489
 490        let Some(message) = message else {
 491            return false;
 492        };
 493
 494        let mut text = String::new();
 495        let mut mentions = Vec::new();
 496
 497        for chunk in message {
 498            match chunk {
 499                acp::ContentBlock::Text(text_content) => {
 500                    text.push_str(&text_content.text);
 501                }
 502                acp::ContentBlock::ResourceLink(resource_link) => {
 503                    let path = Path::new(&resource_link.uri);
 504                    let start = text.len();
 505                    let content = MentionPath::new(&path).to_string();
 506                    text.push_str(&content);
 507                    let end = text.len();
 508                    if let Some(project_path) =
 509                        project.read(cx).project_path_for_absolute_path(&path, cx)
 510                    {
 511                        let filename: SharedString = path
 512                            .file_name()
 513                            .unwrap_or_default()
 514                            .to_string_lossy()
 515                            .to_string()
 516                            .into();
 517                        mentions.push((start..end, project_path, filename));
 518                    }
 519                }
 520                acp::ContentBlock::Image(_)
 521                | acp::ContentBlock::Audio(_)
 522                | acp::ContentBlock::Resource(_) => {}
 523            }
 524        }
 525
 526        let snapshot = message_editor.update(cx, |editor, cx| {
 527            editor.set_text(text, window, cx);
 528            editor.buffer().read(cx).snapshot(cx)
 529        });
 530
 531        for (range, project_path, filename) in mentions {
 532            let crease_icon_path = if project_path.path.is_dir() {
 533                FileIcons::get_folder_icon(false, cx)
 534                    .unwrap_or_else(|| IconName::Folder.path().into())
 535            } else {
 536                FileIcons::get_icon(Path::new(project_path.path.as_ref()), cx)
 537                    .unwrap_or_else(|| IconName::File.path().into())
 538            };
 539
 540            let anchor = snapshot.anchor_before(range.start);
 541            let crease_id = crate::context_picker::insert_crease_for_mention(
 542                anchor.excerpt_id,
 543                anchor.text_anchor,
 544                range.end - range.start,
 545                filename,
 546                crease_icon_path,
 547                message_editor.clone(),
 548                window,
 549                cx,
 550            );
 551            if let Some(crease_id) = crease_id {
 552                mention_set.lock().insert(crease_id, project_path);
 553            }
 554        }
 555
 556        true
 557    }
 558
 559    fn handle_thread_event(
 560        &mut self,
 561        thread: &Entity<AcpThread>,
 562        event: &AcpThreadEvent,
 563        window: &mut Window,
 564        cx: &mut Context<Self>,
 565    ) {
 566        let count = self.list_state.item_count();
 567        match event {
 568            AcpThreadEvent::NewEntry => {
 569                let index = thread.read(cx).entries().len() - 1;
 570                self.sync_thread_entry_view(index, window, cx);
 571                self.list_state.splice(count..count, 1);
 572            }
 573            AcpThreadEvent::EntryUpdated(index) => {
 574                let index = *index;
 575                self.sync_thread_entry_view(index, window, cx);
 576                self.list_state.splice(index..index + 1, 1);
 577            }
 578        }
 579        cx.notify();
 580    }
 581
 582    fn sync_thread_entry_view(
 583        &mut self,
 584        entry_ix: usize,
 585        window: &mut Window,
 586        cx: &mut Context<Self>,
 587    ) {
 588        let Some(multibuffer) = self.entry_diff_multibuffer(entry_ix, cx) else {
 589            return;
 590        };
 591
 592        if self.diff_editors.contains_key(&multibuffer.entity_id()) {
 593            return;
 594        }
 595
 596        let editor = cx.new(|cx| {
 597            let mut editor = Editor::new(
 598                EditorMode::Full {
 599                    scale_ui_elements_with_buffer_font_size: false,
 600                    show_active_line_background: false,
 601                    sized_by_content: true,
 602                },
 603                multibuffer.clone(),
 604                None,
 605                window,
 606                cx,
 607            );
 608            editor.set_show_gutter(false, cx);
 609            editor.disable_inline_diagnostics();
 610            editor.disable_expand_excerpt_buttons(cx);
 611            editor.set_show_vertical_scrollbar(false, cx);
 612            editor.set_minimap_visibility(MinimapVisibility::Disabled, window, cx);
 613            editor.set_soft_wrap_mode(SoftWrap::None, cx);
 614            editor.scroll_manager.set_forbid_vertical_scroll(true);
 615            editor.set_show_indent_guides(false, cx);
 616            editor.set_read_only(true);
 617            editor.set_show_breakpoints(false, cx);
 618            editor.set_show_code_actions(false, cx);
 619            editor.set_show_git_diff_gutter(false, cx);
 620            editor.set_expand_all_diff_hunks(cx);
 621            editor.set_text_style_refinement(TextStyleRefinement {
 622                font_size: Some(
 623                    TextSize::Small
 624                        .rems(cx)
 625                        .to_pixels(ThemeSettings::get_global(cx).agent_font_size(cx))
 626                        .into(),
 627                ),
 628                ..Default::default()
 629            });
 630            editor
 631        });
 632        let entity_id = multibuffer.entity_id();
 633        cx.observe_release(&multibuffer, move |this, _, _| {
 634            this.diff_editors.remove(&entity_id);
 635        })
 636        .detach();
 637
 638        self.diff_editors.insert(entity_id, editor);
 639    }
 640
 641    fn entry_diff_multibuffer(&self, entry_ix: usize, cx: &App) -> Option<Entity<MultiBuffer>> {
 642        let entry = self.thread()?.read(cx).entries().get(entry_ix)?;
 643        entry.first_diff().map(|diff| diff.multibuffer.clone())
 644    }
 645
 646    fn authenticate(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 647        let Some(thread) = self.thread().cloned() else {
 648            return;
 649        };
 650
 651        self.last_error.take();
 652        let authenticate = thread.update(cx, |thread, cx| thread.authenticate(cx));
 653        self.auth_task = Some(cx.spawn_in(window, {
 654            let project = self.project.clone();
 655            let agent = self.agent.clone();
 656            async move |this, cx| {
 657                let result = authenticate.await;
 658
 659                this.update_in(cx, |this, window, cx| {
 660                    if let Err(err) = result {
 661                        this.last_error = Some(cx.new(|cx| {
 662                            Markdown::new(format!("Error: {err}").into(), None, None, cx)
 663                        }))
 664                    } else {
 665                        this.thread_state = Self::initial_state(
 666                            agent,
 667                            this.workspace.clone(),
 668                            project.clone(),
 669                            window,
 670                            cx,
 671                        )
 672                    }
 673                    this.auth_task.take()
 674                })
 675                .ok();
 676            }
 677        }));
 678    }
 679
 680    fn authorize_tool_call(
 681        &mut self,
 682        tool_call_id: acp::ToolCallId,
 683        option_id: acp::PermissionOptionId,
 684        option_kind: acp::PermissionOptionKind,
 685        cx: &mut Context<Self>,
 686    ) {
 687        let Some(thread) = self.thread() else {
 688            return;
 689        };
 690        thread.update(cx, |thread, cx| {
 691            thread.authorize_tool_call(tool_call_id, option_id, option_kind, cx);
 692        });
 693        cx.notify();
 694    }
 695
 696    fn render_entry(
 697        &self,
 698        index: usize,
 699        total_entries: usize,
 700        entry: &AgentThreadEntry,
 701        window: &mut Window,
 702        cx: &Context<Self>,
 703    ) -> AnyElement {
 704        match &entry {
 705            AgentThreadEntry::UserMessage(message) => div()
 706                .py_4()
 707                .px_2()
 708                .child(
 709                    v_flex()
 710                        .p_3()
 711                        .gap_1p5()
 712                        .rounded_lg()
 713                        .shadow_md()
 714                        .bg(cx.theme().colors().editor_background)
 715                        .border_1()
 716                        .border_color(cx.theme().colors().border)
 717                        .text_xs()
 718                        .children(message.content.markdown().map(|md| {
 719                            self.render_markdown(
 720                                md.clone(),
 721                                user_message_markdown_style(window, cx),
 722                            )
 723                        })),
 724                )
 725                .into_any(),
 726            AgentThreadEntry::AssistantMessage(AssistantMessage { chunks }) => {
 727                let style = default_markdown_style(false, window, cx);
 728                let message_body = v_flex()
 729                    .w_full()
 730                    .gap_2p5()
 731                    .children(chunks.iter().enumerate().filter_map(
 732                        |(chunk_ix, chunk)| match chunk {
 733                            AssistantMessageChunk::Message { block } => {
 734                                block.markdown().map(|md| {
 735                                    self.render_markdown(md.clone(), style.clone())
 736                                        .into_any_element()
 737                                })
 738                            }
 739                            AssistantMessageChunk::Thought { block } => {
 740                                block.markdown().map(|md| {
 741                                    self.render_thinking_block(
 742                                        index,
 743                                        chunk_ix,
 744                                        md.clone(),
 745                                        window,
 746                                        cx,
 747                                    )
 748                                    .into_any_element()
 749                                })
 750                            }
 751                        },
 752                    ))
 753                    .into_any();
 754
 755                v_flex()
 756                    .px_5()
 757                    .py_1()
 758                    .when(index + 1 == total_entries, |this| this.pb_4())
 759                    .w_full()
 760                    .text_ui(cx)
 761                    .child(message_body)
 762                    .into_any()
 763            }
 764            AgentThreadEntry::ToolCall(tool_call) => div()
 765                .py_1p5()
 766                .px_5()
 767                .child(self.render_tool_call(index, tool_call, window, cx))
 768                .into_any(),
 769        }
 770    }
 771
 772    fn tool_card_header_bg(&self, cx: &Context<Self>) -> Hsla {
 773        cx.theme()
 774            .colors()
 775            .element_background
 776            .blend(cx.theme().colors().editor_foreground.opacity(0.025))
 777    }
 778
 779    fn tool_card_border_color(&self, cx: &Context<Self>) -> Hsla {
 780        cx.theme().colors().border.opacity(0.6)
 781    }
 782
 783    fn tool_name_font_size(&self) -> Rems {
 784        rems_from_px(13.)
 785    }
 786
 787    fn render_thinking_block(
 788        &self,
 789        entry_ix: usize,
 790        chunk_ix: usize,
 791        chunk: Entity<Markdown>,
 792        window: &Window,
 793        cx: &Context<Self>,
 794    ) -> AnyElement {
 795        let header_id = SharedString::from(format!("thinking-block-header-{}", entry_ix));
 796        let key = (entry_ix, chunk_ix);
 797        let is_open = self.expanded_thinking_blocks.contains(&key);
 798
 799        v_flex()
 800            .child(
 801                h_flex()
 802                    .id(header_id)
 803                    .group("disclosure-header")
 804                    .w_full()
 805                    .justify_between()
 806                    .opacity(0.8)
 807                    .hover(|style| style.opacity(1.))
 808                    .child(
 809                        h_flex()
 810                            .gap_1p5()
 811                            .child(
 812                                Icon::new(IconName::ToolBulb)
 813                                    .size(IconSize::Small)
 814                                    .color(Color::Muted),
 815                            )
 816                            .child(
 817                                div()
 818                                    .text_size(self.tool_name_font_size())
 819                                    .child("Thinking"),
 820                            ),
 821                    )
 822                    .child(
 823                        div().visible_on_hover("disclosure-header").child(
 824                            Disclosure::new("thinking-disclosure", is_open)
 825                                .opened_icon(IconName::ChevronUp)
 826                                .closed_icon(IconName::ChevronDown)
 827                                .on_click(cx.listener({
 828                                    move |this, _event, _window, cx| {
 829                                        if is_open {
 830                                            this.expanded_thinking_blocks.remove(&key);
 831                                        } else {
 832                                            this.expanded_thinking_blocks.insert(key);
 833                                        }
 834                                        cx.notify();
 835                                    }
 836                                })),
 837                        ),
 838                    )
 839                    .on_click(cx.listener({
 840                        move |this, _event, _window, cx| {
 841                            if is_open {
 842                                this.expanded_thinking_blocks.remove(&key);
 843                            } else {
 844                                this.expanded_thinking_blocks.insert(key);
 845                            }
 846                            cx.notify();
 847                        }
 848                    })),
 849            )
 850            .when(is_open, |this| {
 851                this.child(
 852                    div()
 853                        .relative()
 854                        .mt_1p5()
 855                        .ml(px(7.))
 856                        .pl_4()
 857                        .border_l_1()
 858                        .border_color(self.tool_card_border_color(cx))
 859                        .text_ui_sm(cx)
 860                        .child(
 861                            self.render_markdown(chunk, default_markdown_style(false, window, cx)),
 862                        ),
 863                )
 864            })
 865            .into_any_element()
 866    }
 867
 868    fn render_tool_call(
 869        &self,
 870        entry_ix: usize,
 871        tool_call: &ToolCall,
 872        window: &Window,
 873        cx: &Context<Self>,
 874    ) -> Div {
 875        let header_id = SharedString::from(format!("tool-call-header-{}", entry_ix));
 876
 877        let status_icon = match &tool_call.status {
 878            ToolCallStatus::WaitingForConfirmation { .. } => None,
 879            ToolCallStatus::Allowed {
 880                status: acp::ToolCallStatus::InProgress,
 881                ..
 882            } => Some(
 883                Icon::new(IconName::ArrowCircle)
 884                    .color(Color::Accent)
 885                    .size(IconSize::Small)
 886                    .with_animation(
 887                        "running",
 888                        Animation::new(Duration::from_secs(2)).repeat(),
 889                        |icon, delta| icon.transform(Transformation::rotate(percentage(delta))),
 890                    )
 891                    .into_any(),
 892            ),
 893            ToolCallStatus::Allowed {
 894                status: acp::ToolCallStatus::Completed,
 895                ..
 896            } => None,
 897            ToolCallStatus::Rejected
 898            | ToolCallStatus::Canceled
 899            | ToolCallStatus::Allowed {
 900                status: acp::ToolCallStatus::Failed,
 901                ..
 902            } => Some(
 903                Icon::new(IconName::X)
 904                    .color(Color::Error)
 905                    .size(IconSize::Small)
 906                    .into_any_element(),
 907            ),
 908        };
 909
 910        let needs_confirmation = match &tool_call.status {
 911            ToolCallStatus::WaitingForConfirmation { .. } => true,
 912            _ => tool_call
 913                .content
 914                .iter()
 915                .any(|content| matches!(content, ToolCallContent::Diff { .. })),
 916        };
 917
 918        let is_collapsible = !tool_call.content.is_empty() && !needs_confirmation;
 919        let is_open = !is_collapsible || self.expanded_tool_calls.contains(&tool_call.id);
 920
 921        v_flex()
 922            .when(needs_confirmation, |this| {
 923                this.rounded_lg()
 924                    .border_1()
 925                    .border_color(self.tool_card_border_color(cx))
 926                    .bg(cx.theme().colors().editor_background)
 927                    .overflow_hidden()
 928            })
 929            .child(
 930                h_flex()
 931                    .id(header_id)
 932                    .w_full()
 933                    .gap_1()
 934                    .justify_between()
 935                    .map(|this| {
 936                        if needs_confirmation {
 937                            this.px_2()
 938                                .py_1()
 939                                .rounded_t_md()
 940                                .bg(self.tool_card_header_bg(cx))
 941                                .border_b_1()
 942                                .border_color(self.tool_card_border_color(cx))
 943                        } else {
 944                            this.opacity(0.8).hover(|style| style.opacity(1.))
 945                        }
 946                    })
 947                    .child(
 948                        h_flex()
 949                            .id("tool-call-header")
 950                            .overflow_x_scroll()
 951                            .map(|this| {
 952                                if needs_confirmation {
 953                                    this.text_xs()
 954                                } else {
 955                                    this.text_size(self.tool_name_font_size())
 956                                }
 957                            })
 958                            .gap_1p5()
 959                            .child(
 960                                Icon::new(match tool_call.kind {
 961                                    acp::ToolKind::Read => IconName::ToolRead,
 962                                    acp::ToolKind::Edit => IconName::ToolPencil,
 963                                    acp::ToolKind::Search => IconName::ToolSearch,
 964                                    acp::ToolKind::Execute => IconName::ToolTerminal,
 965                                    acp::ToolKind::Think => IconName::ToolBulb,
 966                                    acp::ToolKind::Fetch => IconName::ToolWeb,
 967                                    acp::ToolKind::Other => IconName::ToolHammer,
 968                                })
 969                                .size(IconSize::Small)
 970                                .color(Color::Muted),
 971                            )
 972                            .child(if tool_call.locations.len() == 1 {
 973                                let name = tool_call.locations[0]
 974                                    .path
 975                                    .file_name()
 976                                    .unwrap_or_default()
 977                                    .display()
 978                                    .to_string();
 979
 980                                h_flex()
 981                                    .id(("open-tool-call-location", entry_ix))
 982                                    .child(name)
 983                                    .w_full()
 984                                    .max_w_full()
 985                                    .pr_1()
 986                                    .gap_0p5()
 987                                    .cursor_pointer()
 988                                    .rounded_sm()
 989                                    .opacity(0.8)
 990                                    .hover(|label| {
 991                                        label.opacity(1.).bg(cx
 992                                            .theme()
 993                                            .colors()
 994                                            .element_hover
 995                                            .opacity(0.5))
 996                                    })
 997                                    .tooltip(Tooltip::text("Jump to File"))
 998                                    .on_click(cx.listener(move |this, _, window, cx| {
 999                                        this.open_tool_call_location(entry_ix, 0, window, cx);
1000                                    }))
1001                                    .into_any_element()
1002                            } else {
1003                                self.render_markdown(
1004                                    tool_call.label.clone(),
1005                                    default_markdown_style(needs_confirmation, window, cx),
1006                                )
1007                                .into_any()
1008                            }),
1009                    )
1010                    .child(
1011                        h_flex()
1012                            .gap_0p5()
1013                            .when(is_collapsible, |this| {
1014                                this.child(
1015                                    Disclosure::new(("expand", entry_ix), is_open)
1016                                        .opened_icon(IconName::ChevronUp)
1017                                        .closed_icon(IconName::ChevronDown)
1018                                        .on_click(cx.listener({
1019                                            let id = tool_call.id.clone();
1020                                            move |this: &mut Self, _, _, cx: &mut Context<Self>| {
1021                                                if is_open {
1022                                                    this.expanded_tool_calls.remove(&id);
1023                                                } else {
1024                                                    this.expanded_tool_calls.insert(id.clone());
1025                                                }
1026                                                cx.notify();
1027                                            }
1028                                        })),
1029                                )
1030                            })
1031                            .children(status_icon),
1032                    )
1033                    .on_click(cx.listener({
1034                        let id = tool_call.id.clone();
1035                        move |this: &mut Self, _, _, cx: &mut Context<Self>| {
1036                            if is_open {
1037                                this.expanded_tool_calls.remove(&id);
1038                            } else {
1039                                this.expanded_tool_calls.insert(id.clone());
1040                            }
1041                            cx.notify();
1042                        }
1043                    })),
1044            )
1045            .when(is_open, |this| {
1046                this.child(
1047                    v_flex()
1048                        .text_xs()
1049                        .when(is_collapsible, |this| {
1050                            this.mt_1()
1051                                .border_1()
1052                                .border_color(self.tool_card_border_color(cx))
1053                                .bg(cx.theme().colors().editor_background)
1054                                .rounded_lg()
1055                        })
1056                        .map(|this| {
1057                            if is_open {
1058                                match &tool_call.status {
1059                                    ToolCallStatus::WaitingForConfirmation { options, .. } => this
1060                                        .children(tool_call.content.iter().map(|content| {
1061                                            div()
1062                                                .py_1p5()
1063                                                .child(
1064                                                    self.render_tool_call_content(
1065                                                        content, window, cx,
1066                                                    ),
1067                                                )
1068                                                .into_any_element()
1069                                        }))
1070                                        // todo! confirm this looks ok
1071                                        .child(self.render_permission_buttons(
1072                                            options,
1073                                            entry_ix,
1074                                            tool_call.id.clone(),
1075                                            cx,
1076                                        )),
1077                                    ToolCallStatus::Allowed { .. } | ToolCallStatus::Canceled => {
1078                                        this.children(tool_call.content.iter().map(|content| {
1079                                            div()
1080                                                .py_1p5()
1081                                                .child(
1082                                                    self.render_tool_call_content(
1083                                                        content, window, cx,
1084                                                    ),
1085                                                )
1086                                                .into_any_element()
1087                                        }))
1088                                    }
1089                                    ToolCallStatus::Rejected => this,
1090                                }
1091                            } else {
1092                                this
1093                            }
1094                        }),
1095                )
1096            })
1097    }
1098
1099    fn render_tool_call_content(
1100        &self,
1101        content: &ToolCallContent,
1102        window: &Window,
1103        cx: &Context<Self>,
1104    ) -> AnyElement {
1105        match content {
1106            ToolCallContent::ContentBlock { content } => {
1107                if let Some(md) = content.markdown() {
1108                    div()
1109                        .p_2()
1110                        .child(
1111                            self.render_markdown(
1112                                md.clone(),
1113                                default_markdown_style(false, window, cx),
1114                            ),
1115                        )
1116                        .into_any_element()
1117                } else {
1118                    Empty.into_any_element()
1119                }
1120            }
1121            ToolCallContent::Diff {
1122                diff: Diff { multibuffer, .. },
1123                ..
1124            } => self.render_diff_editor(multibuffer),
1125        }
1126    }
1127
1128    fn render_permission_buttons(
1129        &self,
1130        options: &[acp::PermissionOption],
1131        entry_ix: usize,
1132        tool_call_id: acp::ToolCallId,
1133        cx: &Context<Self>,
1134    ) -> Div {
1135        h_flex()
1136            .pt_1p5()
1137            .px_1p5()
1138            .gap_1()
1139            .justify_end()
1140            .border_t_1()
1141            .border_color(self.tool_card_border_color(cx))
1142            .children(options.iter().map(|option| {
1143                let option_id = SharedString::from(option.id.0.clone());
1144                Button::new((option_id, entry_ix), option.label.clone())
1145                    .map(|this| match option.kind {
1146                        acp::PermissionOptionKind::AllowOnce => {
1147                            this.icon(IconName::Check).icon_color(Color::Success)
1148                        }
1149                        acp::PermissionOptionKind::AllowAlways => {
1150                            this.icon(IconName::CheckDouble).icon_color(Color::Success)
1151                        }
1152                        acp::PermissionOptionKind::RejectOnce => {
1153                            this.icon(IconName::X).icon_color(Color::Error)
1154                        }
1155                        acp::PermissionOptionKind::RejectAlways => {
1156                            this.icon(IconName::X).icon_color(Color::Error)
1157                        }
1158                    })
1159                    .icon_position(IconPosition::Start)
1160                    .icon_size(IconSize::XSmall)
1161                    .on_click(cx.listener({
1162                        let tool_call_id = tool_call_id.clone();
1163                        let option_id = option.id.clone();
1164                        let option_kind = option.kind;
1165                        move |this, _, _, cx| {
1166                            this.authorize_tool_call(
1167                                tool_call_id.clone(),
1168                                option_id.clone(),
1169                                option_kind,
1170                                cx,
1171                            );
1172                        }
1173                    }))
1174            }))
1175    }
1176
1177    fn render_diff_editor(&self, multibuffer: &Entity<MultiBuffer>) -> AnyElement {
1178        v_flex()
1179            .h_full()
1180            .child(
1181                if let Some(editor) = self.diff_editors.get(&multibuffer.entity_id()) {
1182                    editor.clone().into_any_element()
1183                } else {
1184                    Empty.into_any()
1185                },
1186            )
1187            .into_any()
1188    }
1189
1190    fn render_agent_logo(&self) -> AnyElement {
1191        Icon::new(self.agent.logo())
1192            .color(Color::Muted)
1193            .size(IconSize::XLarge)
1194            .into_any_element()
1195    }
1196
1197    fn render_error_agent_logo(&self) -> AnyElement {
1198        let logo = Icon::new(self.agent.logo())
1199            .color(Color::Muted)
1200            .size(IconSize::XLarge)
1201            .into_any_element();
1202
1203        h_flex()
1204            .relative()
1205            .justify_center()
1206            .child(div().opacity(0.3).child(logo))
1207            .child(
1208                h_flex().absolute().right_1().bottom_0().child(
1209                    Icon::new(IconName::XCircle)
1210                        .color(Color::Error)
1211                        .size(IconSize::Small),
1212                ),
1213            )
1214            .into_any_element()
1215    }
1216
1217    fn render_empty_state(&self, cx: &App) -> AnyElement {
1218        let loading = matches!(&self.thread_state, ThreadState::Loading { .. });
1219
1220        v_flex()
1221            .size_full()
1222            .items_center()
1223            .justify_center()
1224            .child(if loading {
1225                h_flex()
1226                    .justify_center()
1227                    .child(self.render_agent_logo())
1228                    .with_animation(
1229                        "pulsating_icon",
1230                        Animation::new(Duration::from_secs(2))
1231                            .repeat()
1232                            .with_easing(pulsating_between(0.4, 1.0)),
1233                        |icon, delta| icon.opacity(delta),
1234                    )
1235                    .into_any()
1236            } else {
1237                self.render_agent_logo().into_any_element()
1238            })
1239            .child(h_flex().mt_4().mb_1().justify_center().child(if loading {
1240                div()
1241                    .child(LoadingLabel::new("").size(LabelSize::Large))
1242                    .into_any_element()
1243            } else {
1244                Headline::new(self.agent.empty_state_headline())
1245                    .size(HeadlineSize::Medium)
1246                    .into_any_element()
1247            }))
1248            .child(
1249                div()
1250                    .max_w_1_2()
1251                    .text_sm()
1252                    .text_center()
1253                    .map(|this| {
1254                        if loading {
1255                            this.invisible()
1256                        } else {
1257                            this.text_color(cx.theme().colors().text_muted)
1258                        }
1259                    })
1260                    .child(self.agent.empty_state_message()),
1261            )
1262            .into_any()
1263    }
1264
1265    fn render_pending_auth_state(&self) -> AnyElement {
1266        v_flex()
1267            .items_center()
1268            .justify_center()
1269            .child(self.render_error_agent_logo())
1270            .child(
1271                h_flex()
1272                    .mt_4()
1273                    .mb_1()
1274                    .justify_center()
1275                    .child(Headline::new("Not Authenticated").size(HeadlineSize::Medium)),
1276            )
1277            .into_any()
1278    }
1279
1280    fn render_error_state(&self, e: &LoadError, cx: &Context<Self>) -> AnyElement {
1281        let mut container = v_flex()
1282            .items_center()
1283            .justify_center()
1284            .child(self.render_error_agent_logo())
1285            .child(
1286                v_flex()
1287                    .mt_4()
1288                    .mb_2()
1289                    .gap_0p5()
1290                    .text_center()
1291                    .items_center()
1292                    .child(Headline::new("Failed to launch").size(HeadlineSize::Medium))
1293                    .child(
1294                        Label::new(e.to_string())
1295                            .size(LabelSize::Small)
1296                            .color(Color::Muted),
1297                    ),
1298            );
1299
1300        if let LoadError::Unsupported {
1301            upgrade_message,
1302            upgrade_command,
1303            ..
1304        } = &e
1305        {
1306            let upgrade_message = upgrade_message.clone();
1307            let upgrade_command = upgrade_command.clone();
1308            container = container.child(Button::new("upgrade", upgrade_message).on_click(
1309                cx.listener(move |this, _, window, cx| {
1310                    this.workspace
1311                        .update(cx, |workspace, cx| {
1312                            let project = workspace.project().read(cx);
1313                            let cwd = project.first_project_directory(cx);
1314                            let shell = project.terminal_settings(&cwd, cx).shell.clone();
1315                            let spawn_in_terminal = task::SpawnInTerminal {
1316                                id: task::TaskId("install".to_string()),
1317                                full_label: upgrade_command.clone(),
1318                                label: upgrade_command.clone(),
1319                                command: Some(upgrade_command.clone()),
1320                                args: Vec::new(),
1321                                command_label: upgrade_command.clone(),
1322                                cwd,
1323                                env: Default::default(),
1324                                use_new_terminal: true,
1325                                allow_concurrent_runs: true,
1326                                reveal: Default::default(),
1327                                reveal_target: Default::default(),
1328                                hide: Default::default(),
1329                                shell,
1330                                show_summary: true,
1331                                show_command: true,
1332                                show_rerun: false,
1333                            };
1334                            workspace
1335                                .spawn_in_terminal(spawn_in_terminal, window, cx)
1336                                .detach();
1337                        })
1338                        .ok();
1339                }),
1340            ));
1341        }
1342
1343        container.into_any()
1344    }
1345
1346    fn render_activity_bar(
1347        &self,
1348        thread_entity: &Entity<AcpThread>,
1349        window: &mut Window,
1350        cx: &Context<Self>,
1351    ) -> Option<AnyElement> {
1352        let thread = thread_entity.read(cx);
1353        let action_log = thread.action_log();
1354        let changed_buffers = action_log.read(cx).changed_buffers(cx);
1355        let plan = thread.plan();
1356
1357        if changed_buffers.is_empty() && plan.is_empty() {
1358            return None;
1359        }
1360
1361        let editor_bg_color = cx.theme().colors().editor_background;
1362        let active_color = cx.theme().colors().element_selected;
1363        let bg_edit_files_disclosure = editor_bg_color.blend(active_color.opacity(0.3));
1364
1365        let pending_edits = thread.has_pending_edit_tool_calls();
1366
1367        v_flex()
1368            .mt_1()
1369            .mx_2()
1370            .bg(bg_edit_files_disclosure)
1371            .border_1()
1372            .border_b_0()
1373            .border_color(cx.theme().colors().border)
1374            .rounded_t_md()
1375            .shadow(vec![gpui::BoxShadow {
1376                color: gpui::black().opacity(0.15),
1377                offset: point(px(1.), px(-1.)),
1378                blur_radius: px(3.),
1379                spread_radius: px(0.),
1380            }])
1381            .when(!plan.is_empty(), |this| {
1382                this.child(self.render_plan_summary(plan, window, cx))
1383                    .when(self.plan_expanded, |parent| {
1384                        parent.child(self.render_plan_entries(plan, window, cx))
1385                    })
1386            })
1387            .when(!changed_buffers.is_empty(), |this| {
1388                this.child(Divider::horizontal())
1389                    .child(self.render_edits_summary(
1390                        action_log,
1391                        &changed_buffers,
1392                        self.edits_expanded,
1393                        pending_edits,
1394                        window,
1395                        cx,
1396                    ))
1397                    .when(self.edits_expanded, |parent| {
1398                        parent.child(self.render_edited_files(
1399                            action_log,
1400                            &changed_buffers,
1401                            pending_edits,
1402                            cx,
1403                        ))
1404                    })
1405            })
1406            .into_any()
1407            .into()
1408    }
1409
1410    fn render_plan_summary(&self, plan: &Plan, window: &mut Window, cx: &Context<Self>) -> Div {
1411        let stats = plan.stats();
1412
1413        let title = if let Some(entry) = stats.in_progress_entry
1414            && !self.plan_expanded
1415        {
1416            h_flex()
1417                .w_full()
1418                .gap_1()
1419                .text_xs()
1420                .text_color(cx.theme().colors().text_muted)
1421                .justify_between()
1422                .child(
1423                    h_flex()
1424                        .gap_1()
1425                        .child(
1426                            Label::new("Current:")
1427                                .size(LabelSize::Small)
1428                                .color(Color::Muted),
1429                        )
1430                        .child(MarkdownElement::new(
1431                            entry.content.clone(),
1432                            plan_label_markdown_style(&entry.status, window, cx),
1433                        )),
1434                )
1435                .when(stats.pending > 0, |this| {
1436                    this.child(
1437                        Label::new(format!("{} left", stats.pending))
1438                            .size(LabelSize::Small)
1439                            .color(Color::Muted)
1440                            .mr_1(),
1441                    )
1442                })
1443        } else {
1444            let status_label = if stats.pending == 0 {
1445                "All Done".to_string()
1446            } else if stats.completed == 0 {
1447                format!("{}", plan.entries.len())
1448            } else {
1449                format!("{}/{}", stats.completed, plan.entries.len())
1450            };
1451
1452            h_flex()
1453                .w_full()
1454                .gap_1()
1455                .justify_between()
1456                .child(
1457                    Label::new("Plan")
1458                        .size(LabelSize::Small)
1459                        .color(Color::Muted),
1460                )
1461                .child(
1462                    Label::new(status_label)
1463                        .size(LabelSize::Small)
1464                        .color(Color::Muted)
1465                        .mr_1(),
1466                )
1467        };
1468
1469        h_flex()
1470            .p_1()
1471            .justify_between()
1472            .when(self.plan_expanded, |this| {
1473                this.border_b_1().border_color(cx.theme().colors().border)
1474            })
1475            .child(
1476                h_flex()
1477                    .id("plan_summary")
1478                    .w_full()
1479                    .gap_1()
1480                    .child(Disclosure::new("plan_disclosure", self.plan_expanded))
1481                    .child(title)
1482                    .on_click(cx.listener(|this, _, _, cx| {
1483                        this.plan_expanded = !this.plan_expanded;
1484                        cx.notify();
1485                    })),
1486            )
1487    }
1488
1489    fn render_plan_entries(&self, plan: &Plan, window: &mut Window, cx: &Context<Self>) -> Div {
1490        v_flex().children(plan.entries.iter().enumerate().flat_map(|(index, entry)| {
1491            let element = h_flex()
1492                .py_1()
1493                .px_2()
1494                .gap_2()
1495                .justify_between()
1496                .bg(cx.theme().colors().editor_background)
1497                .when(index < plan.entries.len() - 1, |parent| {
1498                    parent.border_color(cx.theme().colors().border).border_b_1()
1499                })
1500                .child(
1501                    h_flex()
1502                        .id(("plan_entry", index))
1503                        .gap_1p5()
1504                        .max_w_full()
1505                        .overflow_x_scroll()
1506                        .text_xs()
1507                        .text_color(cx.theme().colors().text_muted)
1508                        .child(match entry.status {
1509                            acp::PlanEntryStatus::Pending => Icon::new(IconName::TodoPending)
1510                                .size(IconSize::Small)
1511                                .color(Color::Muted)
1512                                .into_any_element(),
1513                            acp::PlanEntryStatus::InProgress => Icon::new(IconName::TodoProgress)
1514                                .size(IconSize::Small)
1515                                .color(Color::Accent)
1516                                .with_animation(
1517                                    "running",
1518                                    Animation::new(Duration::from_secs(2)).repeat(),
1519                                    |icon, delta| {
1520                                        icon.transform(Transformation::rotate(percentage(delta)))
1521                                    },
1522                                )
1523                                .into_any_element(),
1524                            acp::PlanEntryStatus::Completed => Icon::new(IconName::TodoComplete)
1525                                .size(IconSize::Small)
1526                                .color(Color::Success)
1527                                .into_any_element(),
1528                        })
1529                        .child(MarkdownElement::new(
1530                            entry.content.clone(),
1531                            plan_label_markdown_style(&entry.status, window, cx),
1532                        )),
1533                );
1534
1535            Some(element)
1536        }))
1537    }
1538
1539    fn render_edits_summary(
1540        &self,
1541        action_log: &Entity<ActionLog>,
1542        changed_buffers: &BTreeMap<Entity<Buffer>, Entity<BufferDiff>>,
1543        expanded: bool,
1544        pending_edits: bool,
1545        window: &mut Window,
1546        cx: &Context<Self>,
1547    ) -> Div {
1548        const EDIT_NOT_READY_TOOLTIP_LABEL: &str = "Wait until file edits are complete.";
1549
1550        let focus_handle = self.focus_handle(cx);
1551
1552        h_flex()
1553            .p_1()
1554            .justify_between()
1555            .when(expanded, |this| {
1556                this.border_b_1().border_color(cx.theme().colors().border)
1557            })
1558            .child(
1559                h_flex()
1560                    .id("edits-container")
1561                    .cursor_pointer()
1562                    .w_full()
1563                    .gap_1()
1564                    .child(Disclosure::new("edits-disclosure", expanded))
1565                    .map(|this| {
1566                        if pending_edits {
1567                            this.child(
1568                                Label::new(format!(
1569                                    "Editing {} {}",
1570                                    changed_buffers.len(),
1571                                    if changed_buffers.len() == 1 {
1572                                        "file"
1573                                    } else {
1574                                        "files"
1575                                    }
1576                                ))
1577                                .color(Color::Muted)
1578                                .size(LabelSize::Small)
1579                                .with_animation(
1580                                    "edit-label",
1581                                    Animation::new(Duration::from_secs(2))
1582                                        .repeat()
1583                                        .with_easing(pulsating_between(0.3, 0.7)),
1584                                    |label, delta| label.alpha(delta),
1585                                ),
1586                            )
1587                        } else {
1588                            this.child(
1589                                Label::new("Edits")
1590                                    .size(LabelSize::Small)
1591                                    .color(Color::Muted),
1592                            )
1593                            .child(Label::new("").size(LabelSize::XSmall).color(Color::Muted))
1594                            .child(
1595                                Label::new(format!(
1596                                    "{} {}",
1597                                    changed_buffers.len(),
1598                                    if changed_buffers.len() == 1 {
1599                                        "file"
1600                                    } else {
1601                                        "files"
1602                                    }
1603                                ))
1604                                .size(LabelSize::Small)
1605                                .color(Color::Muted),
1606                            )
1607                        }
1608                    })
1609                    .on_click(cx.listener(|this, _, _, cx| {
1610                        this.edits_expanded = !this.edits_expanded;
1611                        cx.notify();
1612                    })),
1613            )
1614            .child(
1615                h_flex()
1616                    .gap_1()
1617                    .child(
1618                        IconButton::new("review-changes", IconName::ListTodo)
1619                            .icon_size(IconSize::Small)
1620                            .tooltip({
1621                                let focus_handle = focus_handle.clone();
1622                                move |window, cx| {
1623                                    Tooltip::for_action_in(
1624                                        "Review Changes",
1625                                        &OpenAgentDiff,
1626                                        &focus_handle,
1627                                        window,
1628                                        cx,
1629                                    )
1630                                }
1631                            })
1632                            .on_click(cx.listener(|_, _, window, cx| {
1633                                window.dispatch_action(OpenAgentDiff.boxed_clone(), cx);
1634                            })),
1635                    )
1636                    .child(Divider::vertical().color(DividerColor::Border))
1637                    .child(
1638                        Button::new("reject-all-changes", "Reject All")
1639                            .label_size(LabelSize::Small)
1640                            .disabled(pending_edits)
1641                            .when(pending_edits, |this| {
1642                                this.tooltip(Tooltip::text(EDIT_NOT_READY_TOOLTIP_LABEL))
1643                            })
1644                            .key_binding(
1645                                KeyBinding::for_action_in(
1646                                    &RejectAll,
1647                                    &focus_handle.clone(),
1648                                    window,
1649                                    cx,
1650                                )
1651                                .map(|kb| kb.size(rems_from_px(10.))),
1652                            )
1653                            .on_click({
1654                                let action_log = action_log.clone();
1655                                cx.listener(move |_, _, _, cx| {
1656                                    action_log.update(cx, |action_log, cx| {
1657                                        action_log.reject_all_edits(cx).detach();
1658                                    })
1659                                })
1660                            }),
1661                    )
1662                    .child(
1663                        Button::new("keep-all-changes", "Keep All")
1664                            .label_size(LabelSize::Small)
1665                            .disabled(pending_edits)
1666                            .when(pending_edits, |this| {
1667                                this.tooltip(Tooltip::text(EDIT_NOT_READY_TOOLTIP_LABEL))
1668                            })
1669                            .key_binding(
1670                                KeyBinding::for_action_in(&KeepAll, &focus_handle, window, cx)
1671                                    .map(|kb| kb.size(rems_from_px(10.))),
1672                            )
1673                            .on_click({
1674                                let action_log = action_log.clone();
1675                                cx.listener(move |_, _, _, cx| {
1676                                    action_log.update(cx, |action_log, cx| {
1677                                        action_log.keep_all_edits(cx);
1678                                    })
1679                                })
1680                            }),
1681                    ),
1682            )
1683    }
1684
1685    fn render_edited_files(
1686        &self,
1687        action_log: &Entity<ActionLog>,
1688        changed_buffers: &BTreeMap<Entity<Buffer>, Entity<BufferDiff>>,
1689        pending_edits: bool,
1690        cx: &Context<Self>,
1691    ) -> Div {
1692        let editor_bg_color = cx.theme().colors().editor_background;
1693
1694        v_flex().children(changed_buffers.into_iter().enumerate().flat_map(
1695            |(index, (buffer, _diff))| {
1696                let file = buffer.read(cx).file()?;
1697                let path = file.path();
1698
1699                let file_path = path.parent().and_then(|parent| {
1700                    let parent_str = parent.to_string_lossy();
1701
1702                    if parent_str.is_empty() {
1703                        None
1704                    } else {
1705                        Some(
1706                            Label::new(format!("/{}{}", parent_str, std::path::MAIN_SEPARATOR_STR))
1707                                .color(Color::Muted)
1708                                .size(LabelSize::XSmall)
1709                                .buffer_font(cx),
1710                        )
1711                    }
1712                });
1713
1714                let file_name = path.file_name().map(|name| {
1715                    Label::new(name.to_string_lossy().to_string())
1716                        .size(LabelSize::XSmall)
1717                        .buffer_font(cx)
1718                });
1719
1720                let file_icon = FileIcons::get_icon(&path, cx)
1721                    .map(Icon::from_path)
1722                    .map(|icon| icon.color(Color::Muted).size(IconSize::Small))
1723                    .unwrap_or_else(|| {
1724                        Icon::new(IconName::File)
1725                            .color(Color::Muted)
1726                            .size(IconSize::Small)
1727                    });
1728
1729                let overlay_gradient = linear_gradient(
1730                    90.,
1731                    linear_color_stop(editor_bg_color, 1.),
1732                    linear_color_stop(editor_bg_color.opacity(0.2), 0.),
1733                );
1734
1735                let element = h_flex()
1736                    .group("edited-code")
1737                    .id(("file-container", index))
1738                    .relative()
1739                    .py_1()
1740                    .pl_2()
1741                    .pr_1()
1742                    .gap_2()
1743                    .justify_between()
1744                    .bg(editor_bg_color)
1745                    .when(index < changed_buffers.len() - 1, |parent| {
1746                        parent.border_color(cx.theme().colors().border).border_b_1()
1747                    })
1748                    .child(
1749                        h_flex()
1750                            .id(("file-name", index))
1751                            .pr_8()
1752                            .gap_1p5()
1753                            .max_w_full()
1754                            .overflow_x_scroll()
1755                            .child(file_icon)
1756                            .child(h_flex().gap_0p5().children(file_name).children(file_path))
1757                            .on_click({
1758                                let buffer = buffer.clone();
1759                                cx.listener(move |this, _, window, cx| {
1760                                    this.open_edited_buffer(&buffer, window, cx);
1761                                })
1762                            }),
1763                    )
1764                    .child(
1765                        h_flex()
1766                            .gap_1()
1767                            .visible_on_hover("edited-code")
1768                            .child(
1769                                Button::new("review", "Review")
1770                                    .label_size(LabelSize::Small)
1771                                    .on_click({
1772                                        let buffer = buffer.clone();
1773                                        cx.listener(move |this, _, window, cx| {
1774                                            this.open_edited_buffer(&buffer, window, cx);
1775                                        })
1776                                    }),
1777                            )
1778                            .child(Divider::vertical().color(DividerColor::BorderVariant))
1779                            .child(
1780                                Button::new("reject-file", "Reject")
1781                                    .label_size(LabelSize::Small)
1782                                    .disabled(pending_edits)
1783                                    .on_click({
1784                                        let buffer = buffer.clone();
1785                                        let action_log = action_log.clone();
1786                                        move |_, _, cx| {
1787                                            action_log.update(cx, |action_log, cx| {
1788                                                action_log
1789                                                    .reject_edits_in_ranges(
1790                                                        buffer.clone(),
1791                                                        vec![Anchor::MIN..Anchor::MAX],
1792                                                        cx,
1793                                                    )
1794                                                    .detach_and_log_err(cx);
1795                                            })
1796                                        }
1797                                    }),
1798                            )
1799                            .child(
1800                                Button::new("keep-file", "Keep")
1801                                    .label_size(LabelSize::Small)
1802                                    .disabled(pending_edits)
1803                                    .on_click({
1804                                        let buffer = buffer.clone();
1805                                        let action_log = action_log.clone();
1806                                        move |_, _, cx| {
1807                                            action_log.update(cx, |action_log, cx| {
1808                                                action_log.keep_edits_in_range(
1809                                                    buffer.clone(),
1810                                                    Anchor::MIN..Anchor::MAX,
1811                                                    cx,
1812                                                );
1813                                            })
1814                                        }
1815                                    }),
1816                            ),
1817                    )
1818                    .child(
1819                        div()
1820                            .id("gradient-overlay")
1821                            .absolute()
1822                            .h_full()
1823                            .w_12()
1824                            .top_0()
1825                            .bottom_0()
1826                            .right(px(152.))
1827                            .bg(overlay_gradient),
1828                    );
1829
1830                Some(element)
1831            },
1832        ))
1833    }
1834
1835    fn render_message_editor(&mut self, window: &mut Window, cx: &mut Context<Self>) -> AnyElement {
1836        let focus_handle = self.message_editor.focus_handle(cx);
1837        let editor_bg_color = cx.theme().colors().editor_background;
1838        let (expand_icon, expand_tooltip) = if self.editor_expanded {
1839            (IconName::Minimize, "Minimize Message Editor")
1840        } else {
1841            (IconName::Maximize, "Expand Message Editor")
1842        };
1843
1844        v_flex()
1845            .on_action(cx.listener(Self::expand_message_editor))
1846            .p_2()
1847            .gap_2()
1848            .border_t_1()
1849            .border_color(cx.theme().colors().border)
1850            .bg(editor_bg_color)
1851            .when(self.editor_expanded, |this| {
1852                this.h(vh(0.8, window)).size_full().justify_between()
1853            })
1854            .child(
1855                v_flex()
1856                    .relative()
1857                    .size_full()
1858                    .pt_1()
1859                    .pr_2p5()
1860                    .child(div().flex_1().child({
1861                        let settings = ThemeSettings::get_global(cx);
1862                        let font_size = TextSize::Small
1863                            .rems(cx)
1864                            .to_pixels(settings.agent_font_size(cx));
1865                        let line_height = settings.buffer_line_height.value() * font_size;
1866
1867                        let text_style = TextStyle {
1868                            color: cx.theme().colors().text,
1869                            font_family: settings.buffer_font.family.clone(),
1870                            font_fallbacks: settings.buffer_font.fallbacks.clone(),
1871                            font_features: settings.buffer_font.features.clone(),
1872                            font_size: font_size.into(),
1873                            line_height: line_height.into(),
1874                            ..Default::default()
1875                        };
1876
1877                        EditorElement::new(
1878                            &self.message_editor,
1879                            EditorStyle {
1880                                background: editor_bg_color,
1881                                local_player: cx.theme().players().local(),
1882                                text: text_style,
1883                                syntax: cx.theme().syntax().clone(),
1884                                ..Default::default()
1885                            },
1886                        )
1887                    }))
1888                    .child(
1889                        h_flex()
1890                            .absolute()
1891                            .top_0()
1892                            .right_0()
1893                            .opacity(0.5)
1894                            .hover(|this| this.opacity(1.0))
1895                            .child(
1896                                IconButton::new("toggle-height", expand_icon)
1897                                    .icon_size(IconSize::XSmall)
1898                                    .icon_color(Color::Muted)
1899                                    .tooltip({
1900                                        let focus_handle = focus_handle.clone();
1901                                        move |window, cx| {
1902                                            Tooltip::for_action_in(
1903                                                expand_tooltip,
1904                                                &ExpandMessageEditor,
1905                                                &focus_handle,
1906                                                window,
1907                                                cx,
1908                                            )
1909                                        }
1910                                    })
1911                                    .on_click(cx.listener(|_, _, window, cx| {
1912                                        window.dispatch_action(Box::new(ExpandMessageEditor), cx);
1913                                    })),
1914                            ),
1915                    ),
1916            )
1917            .child(
1918                h_flex()
1919                    .flex_none()
1920                    .justify_between()
1921                    .child(self.render_follow_toggle(cx))
1922                    .child(self.render_send_button(cx)),
1923            )
1924            .into_any()
1925    }
1926
1927    fn render_send_button(&self, cx: &mut Context<Self>) -> AnyElement {
1928        if self.thread().map_or(true, |thread| {
1929            thread.read(cx).status() == ThreadStatus::Idle
1930        }) {
1931            let is_editor_empty = self.message_editor.read(cx).is_empty(cx);
1932            IconButton::new("send-message", IconName::Send)
1933                .icon_color(Color::Accent)
1934                .style(ButtonStyle::Filled)
1935                .disabled(self.thread().is_none() || is_editor_empty)
1936                .on_click(cx.listener(|this, _, window, cx| {
1937                    this.chat(&Chat, window, cx);
1938                }))
1939                .when(!is_editor_empty, |button| {
1940                    button.tooltip(move |window, cx| Tooltip::for_action("Send", &Chat, window, cx))
1941                })
1942                .when(is_editor_empty, |button| {
1943                    button.tooltip(Tooltip::text("Type a message to submit"))
1944                })
1945                .into_any_element()
1946        } else {
1947            IconButton::new("stop-generation", IconName::StopFilled)
1948                .icon_color(Color::Error)
1949                .style(ButtonStyle::Tinted(ui::TintColor::Error))
1950                .tooltip(move |window, cx| {
1951                    Tooltip::for_action("Stop Generation", &editor::actions::Cancel, window, cx)
1952                })
1953                .on_click(cx.listener(|this, _event, _, cx| this.cancel(cx)))
1954                .into_any_element()
1955        }
1956    }
1957
1958    fn render_follow_toggle(&self, cx: &mut Context<Self>) -> impl IntoElement {
1959        let following = self
1960            .workspace
1961            .read_with(cx, |workspace, _| {
1962                workspace.is_being_followed(CollaboratorId::Agent)
1963            })
1964            .unwrap_or(false);
1965
1966        IconButton::new("follow-agent", IconName::Crosshair)
1967            .icon_size(IconSize::Small)
1968            .icon_color(Color::Muted)
1969            .toggle_state(following)
1970            .selected_icon_color(Some(Color::Custom(cx.theme().players().agent().cursor)))
1971            .tooltip(move |window, cx| {
1972                if following {
1973                    Tooltip::for_action("Stop Following Agent", &Follow, window, cx)
1974                } else {
1975                    Tooltip::with_meta(
1976                        "Follow Agent",
1977                        Some(&Follow),
1978                        "Track the agent's location as it reads and edits files.",
1979                        window,
1980                        cx,
1981                    )
1982                }
1983            })
1984            .on_click(cx.listener(move |this, _, window, cx| {
1985                this.workspace
1986                    .update(cx, |workspace, cx| {
1987                        if following {
1988                            workspace.unfollow(CollaboratorId::Agent, window, cx);
1989                        } else {
1990                            workspace.follow(CollaboratorId::Agent, window, cx);
1991                        }
1992                    })
1993                    .ok();
1994            }))
1995    }
1996
1997    fn render_markdown(&self, markdown: Entity<Markdown>, style: MarkdownStyle) -> MarkdownElement {
1998        let workspace = self.workspace.clone();
1999        MarkdownElement::new(markdown, style).on_url_click(move |text, window, cx| {
2000            Self::open_link(text, &workspace, window, cx);
2001        })
2002    }
2003
2004    fn open_link(
2005        url: SharedString,
2006        workspace: &WeakEntity<Workspace>,
2007        window: &mut Window,
2008        cx: &mut App,
2009    ) {
2010        let Some(workspace) = workspace.upgrade() else {
2011            cx.open_url(&url);
2012            return;
2013        };
2014
2015        if let Some(mention_path) = MentionPath::try_parse(&url) {
2016            workspace.update(cx, |workspace, cx| {
2017                let project = workspace.project();
2018                let Some((path, entry)) = project.update(cx, |project, cx| {
2019                    let path = project.find_project_path(mention_path.path(), cx)?;
2020                    let entry = project.entry_for_path(&path, cx)?;
2021                    Some((path, entry))
2022                }) else {
2023                    return;
2024                };
2025
2026                if entry.is_dir() {
2027                    project.update(cx, |_, cx| {
2028                        cx.emit(project::Event::RevealInProjectPanel(entry.id));
2029                    });
2030                } else {
2031                    workspace
2032                        .open_path(path, None, true, window, cx)
2033                        .detach_and_log_err(cx);
2034                }
2035            })
2036        } else {
2037            cx.open_url(&url);
2038        }
2039    }
2040
2041    fn open_tool_call_location(
2042        &self,
2043        entry_ix: usize,
2044        location_ix: usize,
2045        window: &mut Window,
2046        cx: &mut Context<Self>,
2047    ) -> Option<()> {
2048        let location = self
2049            .thread()?
2050            .read(cx)
2051            .entries()
2052            .get(entry_ix)?
2053            .locations()?
2054            .get(location_ix)?;
2055
2056        let project_path = self
2057            .project
2058            .read(cx)
2059            .find_project_path(&location.path, cx)?;
2060
2061        let open_task = self
2062            .workspace
2063            .update(cx, |worskpace, cx| {
2064                worskpace.open_path(project_path, None, true, window, cx)
2065            })
2066            .log_err()?;
2067
2068        window
2069            .spawn(cx, async move |cx| {
2070                let item = open_task.await?;
2071
2072                let Some(active_editor) = item.downcast::<Editor>() else {
2073                    return anyhow::Ok(());
2074                };
2075
2076                active_editor.update_in(cx, |editor, window, cx| {
2077                    let snapshot = editor.buffer().read(cx).snapshot(cx);
2078                    let first_hunk = editor
2079                        .diff_hunks_in_ranges(
2080                            &[editor::Anchor::min()..editor::Anchor::max()],
2081                            &snapshot,
2082                        )
2083                        .next();
2084                    if let Some(first_hunk) = first_hunk {
2085                        let first_hunk_start = first_hunk.multi_buffer_range().start;
2086                        editor.change_selections(Default::default(), window, cx, |selections| {
2087                            selections.select_anchor_ranges([first_hunk_start..first_hunk_start]);
2088                        })
2089                    }
2090                })?;
2091
2092                anyhow::Ok(())
2093            })
2094            .detach_and_log_err(cx);
2095
2096        None
2097    }
2098
2099    pub fn open_thread_as_markdown(
2100        &self,
2101        workspace: Entity<Workspace>,
2102        window: &mut Window,
2103        cx: &mut App,
2104    ) -> Task<anyhow::Result<()>> {
2105        let markdown_language_task = workspace
2106            .read(cx)
2107            .app_state()
2108            .languages
2109            .language_for_name("Markdown");
2110
2111        let (thread_summary, markdown) = if let Some(thread) = self.thread() {
2112            let thread = thread.read(cx);
2113            (thread.title().to_string(), thread.to_markdown(cx))
2114        } else {
2115            return Task::ready(Ok(()));
2116        };
2117
2118        window.spawn(cx, async move |cx| {
2119            let markdown_language = markdown_language_task.await?;
2120
2121            workspace.update_in(cx, |workspace, window, cx| {
2122                let project = workspace.project().clone();
2123
2124                if !project.read(cx).is_local() {
2125                    anyhow::bail!("failed to open active thread as markdown in remote project");
2126                }
2127
2128                let buffer = project.update(cx, |project, cx| {
2129                    project.create_local_buffer(&markdown, Some(markdown_language), cx)
2130                });
2131                let buffer = cx.new(|cx| {
2132                    MultiBuffer::singleton(buffer, cx).with_title(thread_summary.clone())
2133                });
2134
2135                workspace.add_item_to_active_pane(
2136                    Box::new(cx.new(|cx| {
2137                        let mut editor =
2138                            Editor::for_multibuffer(buffer, Some(project.clone()), window, cx);
2139                        editor.set_breadcrumb_header(thread_summary);
2140                        editor
2141                    })),
2142                    None,
2143                    true,
2144                    window,
2145                    cx,
2146                );
2147
2148                anyhow::Ok(())
2149            })??;
2150            anyhow::Ok(())
2151        })
2152    }
2153
2154    fn scroll_to_top(&mut self, cx: &mut Context<Self>) {
2155        self.list_state.scroll_to(ListOffset::default());
2156        cx.notify();
2157    }
2158}
2159
2160impl Focusable for AcpThreadView {
2161    fn focus_handle(&self, cx: &App) -> FocusHandle {
2162        self.message_editor.focus_handle(cx)
2163    }
2164}
2165
2166impl Render for AcpThreadView {
2167    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
2168        let open_as_markdown = IconButton::new("open-as-markdown", IconName::DocumentText)
2169            .icon_size(IconSize::XSmall)
2170            .icon_color(Color::Ignored)
2171            .tooltip(Tooltip::text("Open Thread as Markdown"))
2172            .on_click(cx.listener(move |this, _, window, cx| {
2173                if let Some(workspace) = this.workspace.upgrade() {
2174                    this.open_thread_as_markdown(workspace, window, cx)
2175                        .detach_and_log_err(cx);
2176                }
2177            }));
2178
2179        let scroll_to_top = IconButton::new("scroll_to_top", IconName::ArrowUpAlt)
2180            .icon_size(IconSize::XSmall)
2181            .icon_color(Color::Ignored)
2182            .tooltip(Tooltip::text("Scroll To Top"))
2183            .on_click(cx.listener(move |this, _, _, cx| {
2184                this.scroll_to_top(cx);
2185            }));
2186
2187        v_flex()
2188            .size_full()
2189            .key_context("AcpThread")
2190            .on_action(cx.listener(Self::chat))
2191            .on_action(cx.listener(Self::previous_history_message))
2192            .on_action(cx.listener(Self::next_history_message))
2193            .on_action(cx.listener(Self::open_agent_diff))
2194            .child(match &self.thread_state {
2195                ThreadState::Unauthenticated { .. } => {
2196                    v_flex()
2197                        .p_2()
2198                        .flex_1()
2199                        .items_center()
2200                        .justify_center()
2201                        .child(self.render_pending_auth_state())
2202                        .child(
2203                            h_flex().mt_1p5().justify_center().child(
2204                                Button::new("sign-in", format!("Sign in to {}", self.agent.name()))
2205                                    .on_click(cx.listener(|this, _, window, cx| {
2206                                        this.authenticate(window, cx)
2207                                    })),
2208                            ),
2209                        )
2210                }
2211                ThreadState::Loading { .. } => v_flex().flex_1().child(self.render_empty_state(cx)),
2212                ThreadState::LoadError(e) => v_flex()
2213                    .p_2()
2214                    .flex_1()
2215                    .items_center()
2216                    .justify_center()
2217                    .child(self.render_error_state(e, cx)),
2218                ThreadState::Ready { thread, .. } => v_flex().flex_1().map(|this| {
2219                    if self.list_state.item_count() > 0 {
2220                        this.child(
2221                            list(self.list_state.clone())
2222                                .with_sizing_behavior(gpui::ListSizingBehavior::Auto)
2223                                .flex_grow()
2224                                .into_any(),
2225                        )
2226                        .child(
2227                            h_flex()
2228                                .group("controls")
2229                                .mt_1()
2230                                .mr_1()
2231                                .py_2()
2232                                .px(RESPONSE_PADDING_X)
2233                                .opacity(0.4)
2234                                .hover(|style| style.opacity(1.))
2235                                .flex_wrap()
2236                                .justify_end()
2237                                .child(open_as_markdown)
2238                                .child(scroll_to_top)
2239                                .into_any_element(),
2240                        )
2241                        .children(match thread.read(cx).status() {
2242                            ThreadStatus::Idle | ThreadStatus::WaitingForToolConfirmation => None,
2243                            ThreadStatus::Generating => div()
2244                                .px_5()
2245                                .py_2()
2246                                .child(LoadingLabel::new("").size(LabelSize::Small))
2247                                .into(),
2248                        })
2249                        .children(self.render_activity_bar(&thread, window, cx))
2250                    } else {
2251                        this.child(self.render_empty_state(cx))
2252                    }
2253                }),
2254            })
2255            .when_some(self.last_error.clone(), |el, error| {
2256                el.child(
2257                    div()
2258                        .p_2()
2259                        .text_xs()
2260                        .border_t_1()
2261                        .border_color(cx.theme().colors().border)
2262                        .bg(cx.theme().status().error_background)
2263                        .child(
2264                            self.render_markdown(error, default_markdown_style(false, window, cx)),
2265                        ),
2266                )
2267            })
2268            .child(self.render_message_editor(window, cx))
2269    }
2270}
2271
2272fn user_message_markdown_style(window: &Window, cx: &App) -> MarkdownStyle {
2273    let mut style = default_markdown_style(false, window, cx);
2274    let mut text_style = window.text_style();
2275    let theme_settings = ThemeSettings::get_global(cx);
2276
2277    let buffer_font = theme_settings.buffer_font.family.clone();
2278    let buffer_font_size = TextSize::Small.rems(cx);
2279
2280    text_style.refine(&TextStyleRefinement {
2281        font_family: Some(buffer_font),
2282        font_size: Some(buffer_font_size.into()),
2283        ..Default::default()
2284    });
2285
2286    style.base_text_style = text_style;
2287    style.link_callback = Some(Rc::new(move |url, cx| {
2288        if MentionPath::try_parse(url).is_some() {
2289            let colors = cx.theme().colors();
2290            Some(TextStyleRefinement {
2291                background_color: Some(colors.element_background),
2292                ..Default::default()
2293            })
2294        } else {
2295            None
2296        }
2297    }));
2298    style
2299}
2300
2301fn default_markdown_style(buffer_font: bool, window: &Window, cx: &App) -> MarkdownStyle {
2302    let theme_settings = ThemeSettings::get_global(cx);
2303    let colors = cx.theme().colors();
2304
2305    let buffer_font_size = TextSize::Small.rems(cx);
2306
2307    let mut text_style = window.text_style();
2308    let line_height = buffer_font_size * 1.75;
2309
2310    let font_family = if buffer_font {
2311        theme_settings.buffer_font.family.clone()
2312    } else {
2313        theme_settings.ui_font.family.clone()
2314    };
2315
2316    let font_size = if buffer_font {
2317        TextSize::Small.rems(cx)
2318    } else {
2319        TextSize::Default.rems(cx)
2320    };
2321
2322    text_style.refine(&TextStyleRefinement {
2323        font_family: Some(font_family),
2324        font_fallbacks: theme_settings.ui_font.fallbacks.clone(),
2325        font_features: Some(theme_settings.ui_font.features.clone()),
2326        font_size: Some(font_size.into()),
2327        line_height: Some(line_height.into()),
2328        color: Some(cx.theme().colors().text),
2329        ..Default::default()
2330    });
2331
2332    MarkdownStyle {
2333        base_text_style: text_style.clone(),
2334        syntax: cx.theme().syntax().clone(),
2335        selection_background_color: cx.theme().colors().element_selection_background,
2336        code_block_overflow_x_scroll: true,
2337        table_overflow_x_scroll: true,
2338        heading_level_styles: Some(HeadingLevelStyles {
2339            h1: Some(TextStyleRefinement {
2340                font_size: Some(rems(1.15).into()),
2341                ..Default::default()
2342            }),
2343            h2: Some(TextStyleRefinement {
2344                font_size: Some(rems(1.1).into()),
2345                ..Default::default()
2346            }),
2347            h3: Some(TextStyleRefinement {
2348                font_size: Some(rems(1.05).into()),
2349                ..Default::default()
2350            }),
2351            h4: Some(TextStyleRefinement {
2352                font_size: Some(rems(1.).into()),
2353                ..Default::default()
2354            }),
2355            h5: Some(TextStyleRefinement {
2356                font_size: Some(rems(0.95).into()),
2357                ..Default::default()
2358            }),
2359            h6: Some(TextStyleRefinement {
2360                font_size: Some(rems(0.875).into()),
2361                ..Default::default()
2362            }),
2363        }),
2364        code_block: StyleRefinement {
2365            padding: EdgesRefinement {
2366                top: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
2367                left: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
2368                right: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
2369                bottom: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
2370            },
2371            margin: EdgesRefinement {
2372                top: Some(Length::Definite(Pixels(8.).into())),
2373                left: Some(Length::Definite(Pixels(0.).into())),
2374                right: Some(Length::Definite(Pixels(0.).into())),
2375                bottom: Some(Length::Definite(Pixels(12.).into())),
2376            },
2377            border_style: Some(BorderStyle::Solid),
2378            border_widths: EdgesRefinement {
2379                top: Some(AbsoluteLength::Pixels(Pixels(1.))),
2380                left: Some(AbsoluteLength::Pixels(Pixels(1.))),
2381                right: Some(AbsoluteLength::Pixels(Pixels(1.))),
2382                bottom: Some(AbsoluteLength::Pixels(Pixels(1.))),
2383            },
2384            border_color: Some(colors.border_variant),
2385            background: Some(colors.editor_background.into()),
2386            text: Some(TextStyleRefinement {
2387                font_family: Some(theme_settings.buffer_font.family.clone()),
2388                font_fallbacks: theme_settings.buffer_font.fallbacks.clone(),
2389                font_features: Some(theme_settings.buffer_font.features.clone()),
2390                font_size: Some(buffer_font_size.into()),
2391                ..Default::default()
2392            }),
2393            ..Default::default()
2394        },
2395        inline_code: TextStyleRefinement {
2396            font_family: Some(theme_settings.buffer_font.family.clone()),
2397            font_fallbacks: theme_settings.buffer_font.fallbacks.clone(),
2398            font_features: Some(theme_settings.buffer_font.features.clone()),
2399            font_size: Some(buffer_font_size.into()),
2400            background_color: Some(colors.editor_foreground.opacity(0.08)),
2401            ..Default::default()
2402        },
2403        link: TextStyleRefinement {
2404            background_color: Some(colors.editor_foreground.opacity(0.025)),
2405            underline: Some(UnderlineStyle {
2406                color: Some(colors.text_accent.opacity(0.5)),
2407                thickness: px(1.),
2408                ..Default::default()
2409            }),
2410            ..Default::default()
2411        },
2412        ..Default::default()
2413    }
2414}
2415
2416fn plan_label_markdown_style(
2417    status: &acp::PlanEntryStatus,
2418    window: &Window,
2419    cx: &App,
2420) -> MarkdownStyle {
2421    let default_md_style = default_markdown_style(false, window, cx);
2422
2423    MarkdownStyle {
2424        base_text_style: TextStyle {
2425            color: cx.theme().colors().text_muted,
2426            strikethrough: if matches!(status, acp::PlanEntryStatus::Completed) {
2427                Some(gpui::StrikethroughStyle {
2428                    thickness: px(1.),
2429                    color: Some(cx.theme().colors().text_muted.opacity(0.8)),
2430                })
2431            } else {
2432                None
2433            },
2434            ..default_md_style.base_text_style
2435        },
2436        ..default_md_style
2437    }
2438}