active_thread.rs

   1use crate::AssistantPanel;
   2use crate::context::{AssistantContext, ContextId};
   3use crate::context_picker::MentionLink;
   4use crate::thread::{
   5    LastRestoreCheckpoint, MessageId, MessageSegment, RequestKind, Thread, ThreadError,
   6    ThreadEvent, ThreadFeedback,
   7};
   8use crate::thread_store::ThreadStore;
   9use crate::tool_use::{PendingToolUseStatus, ToolUse, ToolUseStatus};
  10use crate::ui::{AddedContext, AgentNotification, AgentNotificationEvent, ContextPill};
  11use anyhow::Context as _;
  12use assistant_settings::{AssistantSettings, NotifyWhenAgentWaiting};
  13use collections::{HashMap, HashSet};
  14use editor::scroll::Autoscroll;
  15use editor::{Editor, MultiBuffer};
  16use gpui::{
  17    AbsoluteLength, Animation, AnimationExt, AnyElement, App, ClickEvent, ClipboardItem,
  18    DefiniteLength, EdgesRefinement, Empty, Entity, Focusable, Hsla, ListAlignment, ListState,
  19    MouseButton, PlatformDisplay, ScrollHandle, Stateful, StyleRefinement, Subscription, Task,
  20    TextStyleRefinement, Transformation, UnderlineStyle, WeakEntity, WindowHandle,
  21    linear_color_stop, linear_gradient, list, percentage, pulsating_between,
  22};
  23use language::{Buffer, LanguageRegistry};
  24use language_model::{ConfiguredModel, LanguageModelRegistry, LanguageModelToolUseId, Role};
  25use markdown::parser::CodeBlockKind;
  26use markdown::{Markdown, MarkdownElement, MarkdownStyle, ParsedMarkdown, without_fences};
  27use project::ProjectItem as _;
  28use rope::Point;
  29use settings::{Settings as _, update_settings_file};
  30use std::ops::Range;
  31use std::path::Path;
  32use std::rc::Rc;
  33use std::sync::Arc;
  34use std::time::Duration;
  35use text::ToPoint;
  36use theme::ThemeSettings;
  37use ui::{Disclosure, IconButton, KeyBinding, Scrollbar, ScrollbarState, Tooltip, prelude::*};
  38use util::ResultExt as _;
  39use workspace::{OpenOptions, Workspace};
  40
  41use crate::context_store::ContextStore;
  42
  43pub struct ActiveThread {
  44    language_registry: Arc<LanguageRegistry>,
  45    thread_store: Entity<ThreadStore>,
  46    thread: Entity<Thread>,
  47    context_store: Entity<ContextStore>,
  48    workspace: WeakEntity<Workspace>,
  49    save_thread_task: Option<Task<()>>,
  50    messages: Vec<MessageId>,
  51    list_state: ListState,
  52    scrollbar_state: ScrollbarState,
  53    show_scrollbar: bool,
  54    hide_scrollbar_task: Option<Task<()>>,
  55    rendered_messages_by_id: HashMap<MessageId, RenderedMessage>,
  56    rendered_tool_uses: HashMap<LanguageModelToolUseId, RenderedToolUse>,
  57    editing_message: Option<(MessageId, EditMessageState)>,
  58    expanded_tool_uses: HashMap<LanguageModelToolUseId, bool>,
  59    expanded_thinking_segments: HashMap<(MessageId, usize), bool>,
  60    last_error: Option<ThreadError>,
  61    notifications: Vec<WindowHandle<AgentNotification>>,
  62    copied_code_block_ids: HashSet<(MessageId, usize)>,
  63    _subscriptions: Vec<Subscription>,
  64    notification_subscriptions: HashMap<WindowHandle<AgentNotification>, Vec<Subscription>>,
  65    feedback_message_editor: Option<Entity<Editor>>,
  66}
  67
  68struct RenderedMessage {
  69    language_registry: Arc<LanguageRegistry>,
  70    segments: Vec<RenderedMessageSegment>,
  71}
  72
  73#[derive(Clone)]
  74struct RenderedToolUse {
  75    label: Entity<Markdown>,
  76    input: Entity<Markdown>,
  77    output: Entity<Markdown>,
  78}
  79
  80impl RenderedMessage {
  81    fn from_segments(
  82        segments: &[MessageSegment],
  83        language_registry: Arc<LanguageRegistry>,
  84        cx: &mut App,
  85    ) -> Self {
  86        let mut this = Self {
  87            language_registry,
  88            segments: Vec::with_capacity(segments.len()),
  89        };
  90        for segment in segments {
  91            this.push_segment(segment, cx);
  92        }
  93        this
  94    }
  95
  96    fn append_thinking(&mut self, text: &String, cx: &mut App) {
  97        if let Some(RenderedMessageSegment::Thinking {
  98            content,
  99            scroll_handle,
 100        }) = self.segments.last_mut()
 101        {
 102            content.update(cx, |markdown, cx| {
 103                markdown.append(text, cx);
 104            });
 105            scroll_handle.scroll_to_bottom();
 106        } else {
 107            self.segments.push(RenderedMessageSegment::Thinking {
 108                content: parse_markdown(text.into(), self.language_registry.clone(), cx),
 109                scroll_handle: ScrollHandle::default(),
 110            });
 111        }
 112    }
 113
 114    fn append_text(&mut self, text: &String, cx: &mut App) {
 115        if let Some(RenderedMessageSegment::Text(markdown)) = self.segments.last_mut() {
 116            markdown.update(cx, |markdown, cx| markdown.append(text, cx));
 117        } else {
 118            self.segments
 119                .push(RenderedMessageSegment::Text(parse_markdown(
 120                    SharedString::from(text),
 121                    self.language_registry.clone(),
 122                    cx,
 123                )));
 124        }
 125    }
 126
 127    fn push_segment(&mut self, segment: &MessageSegment, cx: &mut App) {
 128        let rendered_segment = match segment {
 129            MessageSegment::Thinking(text) => RenderedMessageSegment::Thinking {
 130                content: parse_markdown(text.into(), self.language_registry.clone(), cx),
 131                scroll_handle: ScrollHandle::default(),
 132            },
 133            MessageSegment::Text(text) => RenderedMessageSegment::Text(parse_markdown(
 134                text.into(),
 135                self.language_registry.clone(),
 136                cx,
 137            )),
 138        };
 139        self.segments.push(rendered_segment);
 140    }
 141}
 142
 143enum RenderedMessageSegment {
 144    Thinking {
 145        content: Entity<Markdown>,
 146        scroll_handle: ScrollHandle,
 147    },
 148    Text(Entity<Markdown>),
 149}
 150
 151fn parse_markdown(
 152    text: SharedString,
 153    language_registry: Arc<LanguageRegistry>,
 154    cx: &mut App,
 155) -> Entity<Markdown> {
 156    cx.new(|cx| Markdown::new(text, Some(language_registry), None, cx))
 157}
 158
 159fn default_markdown_style(window: &Window, cx: &App) -> MarkdownStyle {
 160    let theme_settings = ThemeSettings::get_global(cx);
 161    let colors = cx.theme().colors();
 162    let ui_font_size = TextSize::Default.rems(cx);
 163    let buffer_font_size = TextSize::Small.rems(cx);
 164    let mut text_style = window.text_style();
 165
 166    text_style.refine(&TextStyleRefinement {
 167        font_family: Some(theme_settings.ui_font.family.clone()),
 168        font_fallbacks: theme_settings.ui_font.fallbacks.clone(),
 169        font_features: Some(theme_settings.ui_font.features.clone()),
 170        font_size: Some(ui_font_size.into()),
 171        color: Some(cx.theme().colors().text),
 172        ..Default::default()
 173    });
 174
 175    MarkdownStyle {
 176        base_text_style: text_style,
 177        syntax: cx.theme().syntax().clone(),
 178        selection_background_color: cx.theme().players().local().selection,
 179        code_block_overflow_x_scroll: true,
 180        table_overflow_x_scroll: true,
 181        code_block: StyleRefinement {
 182            padding: EdgesRefinement {
 183                top: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
 184                left: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
 185                right: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
 186                bottom: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
 187            },
 188            background: Some(colors.editor_background.into()),
 189            text: Some(TextStyleRefinement {
 190                font_family: Some(theme_settings.buffer_font.family.clone()),
 191                font_fallbacks: theme_settings.buffer_font.fallbacks.clone(),
 192                font_features: Some(theme_settings.buffer_font.features.clone()),
 193                font_size: Some(buffer_font_size.into()),
 194                ..Default::default()
 195            }),
 196            ..Default::default()
 197        },
 198        inline_code: TextStyleRefinement {
 199            font_family: Some(theme_settings.buffer_font.family.clone()),
 200            font_fallbacks: theme_settings.buffer_font.fallbacks.clone(),
 201            font_features: Some(theme_settings.buffer_font.features.clone()),
 202            font_size: Some(buffer_font_size.into()),
 203            background_color: Some(colors.editor_foreground.opacity(0.08)),
 204            ..Default::default()
 205        },
 206        link: TextStyleRefinement {
 207            background_color: Some(colors.editor_foreground.opacity(0.025)),
 208            underline: Some(UnderlineStyle {
 209                color: Some(colors.text_accent.opacity(0.5)),
 210                thickness: px(1.),
 211                ..Default::default()
 212            }),
 213            ..Default::default()
 214        },
 215        link_callback: Some(Rc::new(move |url, cx| {
 216            if MentionLink::is_valid(url) {
 217                let colors = cx.theme().colors();
 218                Some(TextStyleRefinement {
 219                    background_color: Some(colors.element_background),
 220                    ..Default::default()
 221                })
 222            } else {
 223                None
 224            }
 225        })),
 226        ..Default::default()
 227    }
 228}
 229
 230fn render_tool_use_markdown(
 231    text: SharedString,
 232    language_registry: Arc<LanguageRegistry>,
 233    cx: &mut App,
 234) -> Entity<Markdown> {
 235    cx.new(|cx| Markdown::new(text, Some(language_registry), None, cx))
 236}
 237
 238fn tool_use_markdown_style(window: &Window, cx: &mut App) -> MarkdownStyle {
 239    let theme_settings = ThemeSettings::get_global(cx);
 240    let colors = cx.theme().colors();
 241    let ui_font_size = TextSize::Default.rems(cx);
 242    let buffer_font_size = TextSize::Small.rems(cx);
 243    let mut text_style = window.text_style();
 244
 245    text_style.refine(&TextStyleRefinement {
 246        font_family: Some(theme_settings.ui_font.family.clone()),
 247        font_fallbacks: theme_settings.ui_font.fallbacks.clone(),
 248        font_features: Some(theme_settings.ui_font.features.clone()),
 249        font_size: Some(ui_font_size.into()),
 250        color: Some(cx.theme().colors().text),
 251        ..Default::default()
 252    });
 253
 254    MarkdownStyle {
 255        base_text_style: text_style,
 256        syntax: cx.theme().syntax().clone(),
 257        selection_background_color: cx.theme().players().local().selection,
 258        code_block_overflow_x_scroll: true,
 259        code_block: StyleRefinement {
 260            margin: EdgesRefinement::default(),
 261            padding: EdgesRefinement::default(),
 262            background: Some(colors.editor_background.into()),
 263            border_color: None,
 264            border_widths: EdgesRefinement::default(),
 265            text: Some(TextStyleRefinement {
 266                font_family: Some(theme_settings.buffer_font.family.clone()),
 267                font_fallbacks: theme_settings.buffer_font.fallbacks.clone(),
 268                font_features: Some(theme_settings.buffer_font.features.clone()),
 269                font_size: Some(buffer_font_size.into()),
 270                ..Default::default()
 271            }),
 272            ..Default::default()
 273        },
 274        inline_code: TextStyleRefinement {
 275            font_family: Some(theme_settings.buffer_font.family.clone()),
 276            font_fallbacks: theme_settings.buffer_font.fallbacks.clone(),
 277            font_features: Some(theme_settings.buffer_font.features.clone()),
 278            font_size: Some(TextSize::XSmall.rems(cx).into()),
 279            ..Default::default()
 280        },
 281        heading: StyleRefinement {
 282            text: Some(TextStyleRefinement {
 283                font_size: Some(ui_font_size.into()),
 284                ..Default::default()
 285            }),
 286            ..Default::default()
 287        },
 288        ..Default::default()
 289    }
 290}
 291
 292fn render_markdown_code_block(
 293    message_id: MessageId,
 294    ix: usize,
 295    kind: &CodeBlockKind,
 296    parsed_markdown: &ParsedMarkdown,
 297    codeblock_range: Range<usize>,
 298    active_thread: Entity<ActiveThread>,
 299    workspace: WeakEntity<Workspace>,
 300    _window: &mut Window,
 301    cx: &App,
 302) -> Div {
 303    let label = match kind {
 304        CodeBlockKind::Indented => None,
 305        CodeBlockKind::Fenced => Some(
 306            h_flex()
 307                .gap_1()
 308                .child(
 309                    Icon::new(IconName::Code)
 310                        .color(Color::Muted)
 311                        .size(IconSize::XSmall),
 312                )
 313                .child(Label::new("untitled").size(LabelSize::Small))
 314                .into_any_element(),
 315        ),
 316        CodeBlockKind::FencedLang(raw_language_name) => Some(
 317            h_flex()
 318                .gap_1()
 319                .children(
 320                    parsed_markdown
 321                        .languages_by_name
 322                        .get(raw_language_name)
 323                        .and_then(|language| {
 324                            language
 325                                .config()
 326                                .matcher
 327                                .path_suffixes
 328                                .iter()
 329                                .find_map(|extension| {
 330                                    file_icons::FileIcons::get_icon(Path::new(extension), cx)
 331                                })
 332                                .map(Icon::from_path)
 333                                .map(|icon| icon.color(Color::Muted).size(IconSize::Small))
 334                        }),
 335                )
 336                .child(
 337                    Label::new(
 338                        parsed_markdown
 339                            .languages_by_name
 340                            .get(raw_language_name)
 341                            .map(|language| language.name().into())
 342                            .clone()
 343                            .unwrap_or_else(|| raw_language_name.clone()),
 344                    )
 345                    .size(LabelSize::Small),
 346                )
 347                .into_any_element(),
 348        ),
 349        CodeBlockKind::FencedSrc(path_range) => path_range.path.file_name().map(|file_name| {
 350            let content = if let Some(parent) = path_range.path.parent() {
 351                h_flex()
 352                    .ml_1()
 353                    .gap_1()
 354                    .child(
 355                        Label::new(file_name.to_string_lossy().to_string()).size(LabelSize::Small),
 356                    )
 357                    .child(
 358                        Label::new(parent.to_string_lossy().to_string())
 359                            .color(Color::Muted)
 360                            .size(LabelSize::Small),
 361                    )
 362                    .into_any_element()
 363            } else {
 364                Label::new(path_range.path.to_string_lossy().to_string())
 365                    .size(LabelSize::Small)
 366                    .ml_1()
 367                    .into_any_element()
 368            };
 369
 370            h_flex()
 371                .id(("code-block-header-label", ix))
 372                .w_full()
 373                .max_w_full()
 374                .px_1()
 375                .gap_0p5()
 376                .cursor_pointer()
 377                .rounded_sm()
 378                .hover(|item| item.bg(cx.theme().colors().element_hover.opacity(0.5)))
 379                .tooltip(Tooltip::text("Jump to File"))
 380                .children(
 381                    file_icons::FileIcons::get_icon(&path_range.path, cx)
 382                        .map(Icon::from_path)
 383                        .map(|icon| icon.color(Color::Muted).size(IconSize::XSmall)),
 384                )
 385                .child(content)
 386                .child(
 387                    Icon::new(IconName::ArrowUpRight)
 388                        .size(IconSize::XSmall)
 389                        .color(Color::Ignored),
 390                )
 391                .on_click({
 392                    let path_range = path_range.clone();
 393                    move |_, window, cx| {
 394                        workspace
 395                            .update(cx, {
 396                                |workspace, cx| {
 397                                    if let Some(project_path) = workspace
 398                                        .project()
 399                                        .read(cx)
 400                                        .find_project_path(&path_range.path, cx)
 401                                    {
 402                                        let target = path_range.range.as_ref().map(|range| {
 403                                            Point::new(
 404                                                // Line number is 1-based
 405                                                range.start.line.saturating_sub(1),
 406                                                range.start.col.unwrap_or(0),
 407                                            )
 408                                        });
 409                                        let open_task = workspace.open_path(
 410                                            project_path,
 411                                            None,
 412                                            true,
 413                                            window,
 414                                            cx,
 415                                        );
 416                                        window
 417                                            .spawn(cx, async move |cx| {
 418                                                let item = open_task.await?;
 419                                                if let Some(target) = target {
 420                                                    if let Some(active_editor) =
 421                                                        item.downcast::<Editor>()
 422                                                    {
 423                                                        active_editor
 424                                                            .downgrade()
 425                                                            .update_in(cx, |editor, window, cx| {
 426                                                                editor
 427                                                                    .go_to_singleton_buffer_point(
 428                                                                        target, window, cx,
 429                                                                    );
 430                                                            })
 431                                                            .log_err();
 432                                                    }
 433                                                }
 434                                                anyhow::Ok(())
 435                                            })
 436                                            .detach_and_log_err(cx);
 437                                    }
 438                                }
 439                            })
 440                            .ok();
 441                    }
 442                })
 443                .into_any_element()
 444        }),
 445    };
 446
 447    let codeblock_header_bg = cx
 448        .theme()
 449        .colors()
 450        .element_background
 451        .blend(cx.theme().colors().editor_foreground.opacity(0.01));
 452
 453    let codeblock_was_copied = active_thread
 454        .read(cx)
 455        .copied_code_block_ids
 456        .contains(&(message_id, ix));
 457
 458    let codeblock_header = h_flex()
 459        .group("codeblock_header")
 460        .p_1()
 461        .gap_1()
 462        .justify_between()
 463        .border_b_1()
 464        .border_color(cx.theme().colors().border_variant)
 465        .bg(codeblock_header_bg)
 466        .rounded_t_md()
 467        .children(label)
 468        .child(
 469            div().visible_on_hover("codeblock_header").child(
 470                IconButton::new(
 471                    ("copy-markdown-code", ix),
 472                    if codeblock_was_copied {
 473                        IconName::Check
 474                    } else {
 475                        IconName::Copy
 476                    },
 477                )
 478                .icon_color(Color::Muted)
 479                .shape(ui::IconButtonShape::Square)
 480                .tooltip(Tooltip::text("Copy Code"))
 481                .on_click({
 482                    let active_thread = active_thread.clone();
 483                    let parsed_markdown = parsed_markdown.clone();
 484                    move |_event, _window, cx| {
 485                        active_thread.update(cx, |this, cx| {
 486                            this.copied_code_block_ids.insert((message_id, ix));
 487
 488                            let code =
 489                                without_fences(&parsed_markdown.source()[codeblock_range.clone()])
 490                                    .to_string();
 491
 492                            cx.write_to_clipboard(ClipboardItem::new_string(code.clone()));
 493
 494                            cx.spawn(async move |this, cx| {
 495                                cx.background_executor().timer(Duration::from_secs(2)).await;
 496
 497                                cx.update(|cx| {
 498                                    this.update(cx, |this, cx| {
 499                                        this.copied_code_block_ids.remove(&(message_id, ix));
 500                                        cx.notify();
 501                                    })
 502                                })
 503                                .ok();
 504                            })
 505                            .detach();
 506                        });
 507                    }
 508                }),
 509            ),
 510        );
 511
 512    v_flex()
 513        .mb_2()
 514        .relative()
 515        .overflow_hidden()
 516        .rounded_lg()
 517        .border_1()
 518        .border_color(cx.theme().colors().border_variant)
 519        .child(codeblock_header)
 520}
 521
 522fn open_markdown_link(
 523    text: SharedString,
 524    workspace: WeakEntity<Workspace>,
 525    window: &mut Window,
 526    cx: &mut App,
 527) {
 528    let Some(workspace) = workspace.upgrade() else {
 529        cx.open_url(&text);
 530        return;
 531    };
 532
 533    match MentionLink::try_parse(&text, &workspace, cx) {
 534        Some(MentionLink::File(path, entry)) => workspace.update(cx, |workspace, cx| {
 535            if entry.is_dir() {
 536                workspace.project().update(cx, |_, cx| {
 537                    cx.emit(project::Event::RevealInProjectPanel(entry.id));
 538                })
 539            } else {
 540                workspace
 541                    .open_path(path, None, true, window, cx)
 542                    .detach_and_log_err(cx);
 543            }
 544        }),
 545        Some(MentionLink::Symbol(path, symbol_name)) => {
 546            let open_task = workspace.update(cx, |workspace, cx| {
 547                workspace.open_path(path, None, true, window, cx)
 548            });
 549            window
 550                .spawn(cx, async move |cx| {
 551                    let active_editor = open_task
 552                        .await?
 553                        .downcast::<Editor>()
 554                        .context("Item is not an editor")?;
 555                    active_editor.update_in(cx, |editor, window, cx| {
 556                        let symbol_range = editor
 557                            .buffer()
 558                            .read(cx)
 559                            .snapshot(cx)
 560                            .outline(None)
 561                            .and_then(|outline| {
 562                                outline
 563                                    .find_most_similar(&symbol_name)
 564                                    .map(|(_, item)| item.range.clone())
 565                            })
 566                            .context("Could not find matching symbol")?;
 567
 568                        editor.change_selections(Some(Autoscroll::center()), window, cx, |s| {
 569                            s.select_anchor_ranges([symbol_range.start..symbol_range.start])
 570                        });
 571                        anyhow::Ok(())
 572                    })
 573                })
 574                .detach_and_log_err(cx);
 575        }
 576        Some(MentionLink::Thread(thread_id)) => workspace.update(cx, |workspace, cx| {
 577            if let Some(panel) = workspace.panel::<AssistantPanel>(cx) {
 578                panel.update(cx, |panel, cx| {
 579                    panel
 580                        .open_thread(&thread_id, window, cx)
 581                        .detach_and_log_err(cx)
 582                });
 583            }
 584        }),
 585        Some(MentionLink::Fetch(url)) => cx.open_url(&url),
 586        None => cx.open_url(&text),
 587    }
 588}
 589
 590struct EditMessageState {
 591    editor: Entity<Editor>,
 592}
 593
 594impl ActiveThread {
 595    pub fn new(
 596        thread: Entity<Thread>,
 597        thread_store: Entity<ThreadStore>,
 598        language_registry: Arc<LanguageRegistry>,
 599        context_store: Entity<ContextStore>,
 600        workspace: WeakEntity<Workspace>,
 601        window: &mut Window,
 602        cx: &mut Context<Self>,
 603    ) -> Self {
 604        let subscriptions = vec![
 605            cx.observe(&thread, |_, _, cx| cx.notify()),
 606            cx.subscribe_in(&thread, window, Self::handle_thread_event),
 607        ];
 608
 609        let list_state = ListState::new(0, ListAlignment::Bottom, px(2048.), {
 610            let this = cx.entity().downgrade();
 611            move |ix, window: &mut Window, cx: &mut App| {
 612                this.update(cx, |this, cx| this.render_message(ix, window, cx))
 613                    .unwrap()
 614            }
 615        });
 616
 617        let mut this = Self {
 618            language_registry,
 619            thread_store,
 620            thread: thread.clone(),
 621            context_store,
 622            workspace,
 623            save_thread_task: None,
 624            messages: Vec::new(),
 625            rendered_messages_by_id: HashMap::default(),
 626            rendered_tool_uses: HashMap::default(),
 627            expanded_tool_uses: HashMap::default(),
 628            expanded_thinking_segments: HashMap::default(),
 629            list_state: list_state.clone(),
 630            scrollbar_state: ScrollbarState::new(list_state),
 631            show_scrollbar: false,
 632            hide_scrollbar_task: None,
 633            editing_message: None,
 634            last_error: None,
 635            copied_code_block_ids: HashSet::default(),
 636            notifications: Vec::new(),
 637            _subscriptions: subscriptions,
 638            notification_subscriptions: HashMap::default(),
 639            feedback_message_editor: None,
 640        };
 641
 642        for message in thread.read(cx).messages().cloned().collect::<Vec<_>>() {
 643            this.push_message(&message.id, &message.segments, window, cx);
 644
 645            for tool_use in thread.read(cx).tool_uses_for_message(message.id, cx) {
 646                this.render_tool_use_markdown(
 647                    tool_use.id.clone(),
 648                    tool_use.ui_text.clone(),
 649                    &tool_use.input,
 650                    tool_use.status.text(),
 651                    cx,
 652                );
 653            }
 654        }
 655
 656        this
 657    }
 658
 659    pub fn thread(&self) -> &Entity<Thread> {
 660        &self.thread
 661    }
 662
 663    pub fn is_empty(&self) -> bool {
 664        self.messages.is_empty()
 665    }
 666
 667    pub fn summary(&self, cx: &App) -> Option<SharedString> {
 668        self.thread.read(cx).summary()
 669    }
 670
 671    pub fn summary_or_default(&self, cx: &App) -> SharedString {
 672        self.thread.read(cx).summary_or_default()
 673    }
 674
 675    pub fn cancel_last_completion(&mut self, cx: &mut App) -> bool {
 676        self.last_error.take();
 677        self.thread
 678            .update(cx, |thread, cx| thread.cancel_last_completion(cx))
 679    }
 680
 681    pub fn last_error(&self) -> Option<ThreadError> {
 682        self.last_error.clone()
 683    }
 684
 685    pub fn clear_last_error(&mut self) {
 686        self.last_error.take();
 687    }
 688
 689    fn push_message(
 690        &mut self,
 691        id: &MessageId,
 692        segments: &[MessageSegment],
 693        _window: &mut Window,
 694        cx: &mut Context<Self>,
 695    ) {
 696        let old_len = self.messages.len();
 697        self.messages.push(*id);
 698        self.list_state.splice(old_len..old_len, 1);
 699
 700        let rendered_message =
 701            RenderedMessage::from_segments(segments, self.language_registry.clone(), cx);
 702        self.rendered_messages_by_id.insert(*id, rendered_message);
 703    }
 704
 705    fn edited_message(
 706        &mut self,
 707        id: &MessageId,
 708        segments: &[MessageSegment],
 709        _window: &mut Window,
 710        cx: &mut Context<Self>,
 711    ) {
 712        let Some(index) = self.messages.iter().position(|message_id| message_id == id) else {
 713            return;
 714        };
 715        self.list_state.splice(index..index + 1, 1);
 716        let rendered_message =
 717            RenderedMessage::from_segments(segments, self.language_registry.clone(), cx);
 718        self.rendered_messages_by_id.insert(*id, rendered_message);
 719    }
 720
 721    fn deleted_message(&mut self, id: &MessageId) {
 722        let Some(index) = self.messages.iter().position(|message_id| message_id == id) else {
 723            return;
 724        };
 725        self.messages.remove(index);
 726        self.list_state.splice(index..index + 1, 0);
 727        self.rendered_messages_by_id.remove(id);
 728    }
 729
 730    fn render_tool_use_markdown(
 731        &mut self,
 732        tool_use_id: LanguageModelToolUseId,
 733        tool_label: impl Into<SharedString>,
 734        tool_input: &serde_json::Value,
 735        tool_output: SharedString,
 736        cx: &mut Context<Self>,
 737    ) {
 738        let rendered = RenderedToolUse {
 739            label: render_tool_use_markdown(tool_label.into(), self.language_registry.clone(), cx),
 740            input: render_tool_use_markdown(
 741                format!(
 742                    "```json\n{}\n```",
 743                    serde_json::to_string_pretty(tool_input).unwrap_or_default()
 744                )
 745                .into(),
 746                self.language_registry.clone(),
 747                cx,
 748            ),
 749            output: render_tool_use_markdown(tool_output, self.language_registry.clone(), cx),
 750        };
 751        self.rendered_tool_uses
 752            .insert(tool_use_id.clone(), rendered);
 753    }
 754
 755    fn handle_thread_event(
 756        &mut self,
 757        _thread: &Entity<Thread>,
 758        event: &ThreadEvent,
 759        window: &mut Window,
 760        cx: &mut Context<Self>,
 761    ) {
 762        match event {
 763            ThreadEvent::ShowError(error) => {
 764                self.last_error = Some(error.clone());
 765            }
 766            ThreadEvent::StreamedCompletion
 767            | ThreadEvent::SummaryGenerated
 768            | ThreadEvent::SummaryChanged => {
 769                self.save_thread(cx);
 770            }
 771            ThreadEvent::DoneStreaming => {
 772                let thread = self.thread.read(cx);
 773
 774                if !thread.is_generating() {
 775                    self.show_notification(
 776                        if thread.used_tools_since_last_user_message() {
 777                            "Finished running tools"
 778                        } else {
 779                            "New message"
 780                        },
 781                        IconName::ZedAssistant,
 782                        window,
 783                        cx,
 784                    );
 785                }
 786            }
 787            ThreadEvent::ToolConfirmationNeeded => {
 788                self.show_notification("Waiting for tool confirmation", IconName::Info, window, cx);
 789            }
 790            ThreadEvent::StreamedAssistantText(message_id, text) => {
 791                if let Some(rendered_message) = self.rendered_messages_by_id.get_mut(&message_id) {
 792                    rendered_message.append_text(text, cx);
 793                }
 794            }
 795            ThreadEvent::StreamedAssistantThinking(message_id, text) => {
 796                if let Some(rendered_message) = self.rendered_messages_by_id.get_mut(&message_id) {
 797                    rendered_message.append_thinking(text, cx);
 798                }
 799            }
 800            ThreadEvent::MessageAdded(message_id) => {
 801                if let Some(message_segments) = self
 802                    .thread
 803                    .read(cx)
 804                    .message(*message_id)
 805                    .map(|message| message.segments.clone())
 806                {
 807                    self.push_message(message_id, &message_segments, window, cx);
 808                }
 809
 810                self.save_thread(cx);
 811                cx.notify();
 812            }
 813            ThreadEvent::MessageEdited(message_id) => {
 814                if let Some(message_segments) = self
 815                    .thread
 816                    .read(cx)
 817                    .message(*message_id)
 818                    .map(|message| message.segments.clone())
 819                {
 820                    self.edited_message(message_id, &message_segments, window, cx);
 821                }
 822
 823                self.save_thread(cx);
 824                cx.notify();
 825            }
 826            ThreadEvent::MessageDeleted(message_id) => {
 827                self.deleted_message(message_id);
 828                self.save_thread(cx);
 829                cx.notify();
 830            }
 831            ThreadEvent::UsePendingTools => {
 832                let tool_uses = self
 833                    .thread
 834                    .update(cx, |thread, cx| thread.use_pending_tools(cx));
 835
 836                for tool_use in tool_uses {
 837                    self.render_tool_use_markdown(
 838                        tool_use.id.clone(),
 839                        tool_use.ui_text.clone(),
 840                        &tool_use.input,
 841                        "".into(),
 842                        cx,
 843                    );
 844                }
 845            }
 846            ThreadEvent::ToolFinished {
 847                pending_tool_use,
 848                canceled,
 849                ..
 850            } => {
 851                let canceled = *canceled;
 852                if let Some(tool_use) = pending_tool_use {
 853                    self.render_tool_use_markdown(
 854                        tool_use.id.clone(),
 855                        tool_use.ui_text.clone(),
 856                        &tool_use.input,
 857                        self.thread
 858                            .read(cx)
 859                            .tool_result(&tool_use.id)
 860                            .map(|result| result.content.clone().into())
 861                            .unwrap_or("".into()),
 862                        cx,
 863                    );
 864                }
 865
 866                if self.thread.read(cx).all_tools_finished() {
 867                    let model_registry = LanguageModelRegistry::read_global(cx);
 868                    if let Some(ConfiguredModel { model, .. }) = model_registry.default_model() {
 869                        self.thread.update(cx, |thread, cx| {
 870                            thread.attach_tool_results(cx);
 871                            if !canceled {
 872                                thread.send_to_model(model, RequestKind::Chat, cx);
 873                            }
 874                        });
 875                    }
 876                }
 877            }
 878            ThreadEvent::CheckpointChanged => cx.notify(),
 879        }
 880    }
 881
 882    fn show_notification(
 883        &mut self,
 884        caption: impl Into<SharedString>,
 885        icon: IconName,
 886        window: &mut Window,
 887        cx: &mut Context<ActiveThread>,
 888    ) {
 889        if window.is_window_active() || !self.notifications.is_empty() {
 890            return;
 891        }
 892
 893        let title = self
 894            .thread
 895            .read(cx)
 896            .summary()
 897            .unwrap_or("Agent Panel".into());
 898
 899        match AssistantSettings::get_global(cx).notify_when_agent_waiting {
 900            NotifyWhenAgentWaiting::PrimaryScreen => {
 901                if let Some(primary) = cx.primary_display() {
 902                    self.pop_up(icon, caption.into(), title.clone(), window, primary, cx);
 903                }
 904            }
 905            NotifyWhenAgentWaiting::AllScreens => {
 906                let caption = caption.into();
 907                for screen in cx.displays() {
 908                    self.pop_up(icon, caption.clone(), title.clone(), window, screen, cx);
 909                }
 910            }
 911            NotifyWhenAgentWaiting::Never => {
 912                // Don't show anything
 913            }
 914        }
 915    }
 916
 917    fn pop_up(
 918        &mut self,
 919        icon: IconName,
 920        caption: SharedString,
 921        title: SharedString,
 922        window: &mut Window,
 923        screen: Rc<dyn PlatformDisplay>,
 924        cx: &mut Context<'_, ActiveThread>,
 925    ) {
 926        let options = AgentNotification::window_options(screen, cx);
 927
 928        if let Some(screen_window) = cx
 929            .open_window(options, |_, cx| {
 930                cx.new(|_| AgentNotification::new(title.clone(), caption.clone(), icon))
 931            })
 932            .log_err()
 933        {
 934            if let Some(pop_up) = screen_window.entity(cx).log_err() {
 935                self.notification_subscriptions
 936                    .entry(screen_window)
 937                    .or_insert_with(Vec::new)
 938                    .push(cx.subscribe_in(&pop_up, window, {
 939                        |this, _, event, window, cx| match event {
 940                            AgentNotificationEvent::Accepted => {
 941                                let handle = window.window_handle();
 942                                cx.activate(true); // Switch back to the Zed application
 943
 944                                let workspace_handle = this.workspace.clone();
 945
 946                                // If there are multiple Zed windows, activate the correct one.
 947                                cx.defer(move |cx| {
 948                                    handle
 949                                        .update(cx, |_view, window, _cx| {
 950                                            window.activate_window();
 951
 952                                            if let Some(workspace) = workspace_handle.upgrade() {
 953                                                workspace.update(_cx, |workspace, cx| {
 954                                                    workspace
 955                                                        .focus_panel::<AssistantPanel>(window, cx);
 956                                                });
 957                                            }
 958                                        })
 959                                        .log_err();
 960                                });
 961
 962                                this.dismiss_notifications(cx);
 963                            }
 964                            AgentNotificationEvent::Dismissed => {
 965                                this.dismiss_notifications(cx);
 966                            }
 967                        }
 968                    }));
 969
 970                self.notifications.push(screen_window);
 971
 972                // If the user manually refocuses the original window, dismiss the popup.
 973                self.notification_subscriptions
 974                    .entry(screen_window)
 975                    .or_insert_with(Vec::new)
 976                    .push({
 977                        let pop_up_weak = pop_up.downgrade();
 978
 979                        cx.observe_window_activation(window, move |_, window, cx| {
 980                            if window.is_window_active() {
 981                                if let Some(pop_up) = pop_up_weak.upgrade() {
 982                                    pop_up.update(cx, |_, cx| {
 983                                        cx.emit(AgentNotificationEvent::Dismissed);
 984                                    });
 985                                }
 986                            }
 987                        })
 988                    });
 989            }
 990        }
 991    }
 992
 993    /// Spawns a task to save the active thread.
 994    ///
 995    /// Only one task to save the thread will be in flight at a time.
 996    fn save_thread(&mut self, cx: &mut Context<Self>) {
 997        let thread = self.thread.clone();
 998        self.save_thread_task = Some(cx.spawn(async move |this, cx| {
 999            let task = this
1000                .update(cx, |this, cx| {
1001                    this.thread_store
1002                        .update(cx, |thread_store, cx| thread_store.save_thread(&thread, cx))
1003                })
1004                .ok();
1005
1006            if let Some(task) = task {
1007                task.await.log_err();
1008            }
1009        }));
1010    }
1011
1012    fn start_editing_message(
1013        &mut self,
1014        message_id: MessageId,
1015        message_segments: &[MessageSegment],
1016        window: &mut Window,
1017        cx: &mut Context<Self>,
1018    ) {
1019        // User message should always consist of a single text segment,
1020        // therefore we can skip returning early if it's not a text segment.
1021        let Some(MessageSegment::Text(message_text)) = message_segments.first() else {
1022            return;
1023        };
1024
1025        let buffer = cx.new(|cx| {
1026            MultiBuffer::singleton(cx.new(|cx| Buffer::local(message_text.clone(), cx)), cx)
1027        });
1028        let editor = cx.new(|cx| {
1029            let mut editor = Editor::new(
1030                editor::EditorMode::AutoHeight { max_lines: 8 },
1031                buffer,
1032                None,
1033                window,
1034                cx,
1035            );
1036            editor.focus_handle(cx).focus(window);
1037            editor.move_to_end(&editor::actions::MoveToEnd, window, cx);
1038            editor
1039        });
1040        self.editing_message = Some((
1041            message_id,
1042            EditMessageState {
1043                editor: editor.clone(),
1044            },
1045        ));
1046        cx.notify();
1047    }
1048
1049    fn cancel_editing_message(&mut self, _: &menu::Cancel, _: &mut Window, cx: &mut Context<Self>) {
1050        self.editing_message.take();
1051        cx.notify();
1052    }
1053
1054    fn confirm_editing_message(
1055        &mut self,
1056        _: &menu::Confirm,
1057        _: &mut Window,
1058        cx: &mut Context<Self>,
1059    ) {
1060        let Some((message_id, state)) = self.editing_message.take() else {
1061            return;
1062        };
1063        let edited_text = state.editor.read(cx).text(cx);
1064        self.thread.update(cx, |thread, cx| {
1065            thread.edit_message(
1066                message_id,
1067                Role::User,
1068                vec![MessageSegment::Text(edited_text)],
1069                cx,
1070            );
1071            for message_id in self.messages_after(message_id) {
1072                thread.delete_message(*message_id, cx);
1073            }
1074        });
1075
1076        let Some(model) = LanguageModelRegistry::read_global(cx).default_model() else {
1077            return;
1078        };
1079
1080        if model.provider.must_accept_terms(cx) {
1081            cx.notify();
1082            return;
1083        }
1084
1085        self.thread.update(cx, |thread, cx| {
1086            thread.send_to_model(model.model, RequestKind::Chat, cx)
1087        });
1088        cx.notify();
1089    }
1090
1091    fn messages_after(&self, message_id: MessageId) -> &[MessageId] {
1092        self.messages
1093            .iter()
1094            .position(|id| *id == message_id)
1095            .map(|index| &self.messages[index + 1..])
1096            .unwrap_or(&[])
1097    }
1098
1099    fn handle_cancel_click(&mut self, _: &ClickEvent, window: &mut Window, cx: &mut Context<Self>) {
1100        self.cancel_editing_message(&menu::Cancel, window, cx);
1101    }
1102
1103    fn handle_regenerate_click(
1104        &mut self,
1105        _: &ClickEvent,
1106        window: &mut Window,
1107        cx: &mut Context<Self>,
1108    ) {
1109        self.confirm_editing_message(&menu::Confirm, window, cx);
1110    }
1111
1112    fn handle_feedback_click(
1113        &mut self,
1114        feedback: ThreadFeedback,
1115        window: &mut Window,
1116        cx: &mut Context<Self>,
1117    ) {
1118        match feedback {
1119            ThreadFeedback::Positive => {
1120                let report = self
1121                    .thread
1122                    .update(cx, |thread, cx| thread.report_feedback(feedback, cx));
1123
1124                let this = cx.entity().downgrade();
1125                cx.spawn(async move |_, cx| {
1126                    report.await?;
1127                    this.update(cx, |_this, cx| cx.notify())
1128                })
1129                .detach_and_log_err(cx);
1130            }
1131            ThreadFeedback::Negative => {
1132                self.handle_show_feedback_comments(window, cx);
1133            }
1134        }
1135    }
1136
1137    fn handle_show_feedback_comments(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1138        if self.feedback_message_editor.is_some() {
1139            return;
1140        }
1141
1142        let buffer = cx.new(|cx| {
1143            let empty_string = String::new();
1144            MultiBuffer::singleton(cx.new(|cx| Buffer::local(empty_string, cx)), cx)
1145        });
1146
1147        let editor = cx.new(|cx| {
1148            let mut editor = Editor::new(
1149                editor::EditorMode::AutoHeight { max_lines: 4 },
1150                buffer,
1151                None,
1152                window,
1153                cx,
1154            );
1155            editor.set_placeholder_text(
1156                "What went wrong? Share your feedback so we can improve.",
1157                cx,
1158            );
1159            editor
1160        });
1161
1162        editor.read(cx).focus_handle(cx).focus(window);
1163        self.feedback_message_editor = Some(editor);
1164        cx.notify();
1165    }
1166
1167    fn submit_feedback_message(&mut self, cx: &mut Context<Self>) {
1168        let Some(editor) = self.feedback_message_editor.clone() else {
1169            return;
1170        };
1171
1172        let report_task = self.thread.update(cx, |thread, cx| {
1173            thread.report_feedback(ThreadFeedback::Negative, cx)
1174        });
1175
1176        let comments = editor.read(cx).text(cx);
1177        if !comments.is_empty() {
1178            let thread_id = self.thread.read(cx).id().clone();
1179
1180            telemetry::event!("Assistant Thread Feedback Comments", thread_id, comments);
1181        }
1182
1183        self.feedback_message_editor = None;
1184
1185        let this = cx.entity().downgrade();
1186        cx.spawn(async move |_, cx| {
1187            report_task.await?;
1188            this.update(cx, |_this, cx| cx.notify())
1189        })
1190        .detach_and_log_err(cx);
1191    }
1192
1193    fn render_message(&self, ix: usize, window: &mut Window, cx: &mut Context<Self>) -> AnyElement {
1194        let message_id = self.messages[ix];
1195        let Some(message) = self.thread.read(cx).message(message_id) else {
1196            return Empty.into_any();
1197        };
1198
1199        let Some(rendered_message) = self.rendered_messages_by_id.get(&message_id) else {
1200            return Empty.into_any();
1201        };
1202
1203        let context_store = self.context_store.clone();
1204        let workspace = self.workspace.clone();
1205        let thread = self.thread.read(cx);
1206
1207        // Get all the data we need from thread before we start using it in closures
1208        let checkpoint = thread.checkpoint_for_message(message_id);
1209        let context = thread.context_for_message(message_id).collect::<Vec<_>>();
1210
1211        let tool_uses = thread.tool_uses_for_message(message_id, cx);
1212        let has_tool_uses = !tool_uses.is_empty();
1213        let is_generating = thread.is_generating();
1214
1215        let is_first_message = ix == 0;
1216        let is_last_message = ix == self.messages.len() - 1;
1217        let show_feedback = is_last_message && message.role != Role::User;
1218
1219        let needs_confirmation = tool_uses.iter().any(|tool_use| tool_use.needs_confirmation);
1220
1221        let generating_label = (is_generating && is_last_message).then(|| {
1222            Label::new("Generating")
1223                .color(Color::Muted)
1224                .size(LabelSize::Small)
1225                .with_animation(
1226                    "generating-label",
1227                    Animation::new(Duration::from_secs(1)).repeat(),
1228                    |mut label, delta| {
1229                        let text = match delta {
1230                            d if d < 0.25 => "Generating",
1231                            d if d < 0.5 => "Generating.",
1232                            d if d < 0.75 => "Generating..",
1233                            _ => "Generating...",
1234                        };
1235                        label.set_text(text);
1236                        label
1237                    },
1238                )
1239                .with_animation(
1240                    "pulsating-label",
1241                    Animation::new(Duration::from_secs(2))
1242                        .repeat()
1243                        .with_easing(pulsating_between(0.6, 1.)),
1244                    |label, delta| label.map_element(|label| label.alpha(delta)),
1245                )
1246        });
1247
1248        // Don't render user messages that are just there for returning tool results.
1249        if message.role == Role::User && thread.message_has_tool_results(message_id) {
1250            if let Some(generating_label) = generating_label {
1251                return h_flex()
1252                    .w_full()
1253                    .h_10()
1254                    .py_1p5()
1255                    .pl_4()
1256                    .pb_3()
1257                    .child(generating_label)
1258                    .into_any_element();
1259            }
1260
1261            return Empty.into_any();
1262        }
1263
1264        let allow_editing_message = message.role == Role::User;
1265
1266        let edit_message_editor = self
1267            .editing_message
1268            .as_ref()
1269            .filter(|(id, _)| *id == message_id)
1270            .map(|(_, state)| state.editor.clone());
1271
1272        let colors = cx.theme().colors();
1273        let active_color = colors.element_active;
1274        let editor_bg_color = colors.editor_background;
1275        let bg_user_message_header = editor_bg_color.blend(active_color.opacity(0.25));
1276
1277        let feedback_container = h_flex().pt_2().pb_4().px_4().gap_1().justify_between();
1278        let feedback_items = match self.thread.read(cx).feedback() {
1279            Some(feedback) => feedback_container
1280                .child(
1281                    Label::new(match feedback {
1282                        ThreadFeedback::Positive => "Thanks for your feedback!",
1283                        ThreadFeedback::Negative => {
1284                            "We appreciate your feedback and will use it to improve."
1285                        }
1286                    })
1287                    .color(Color::Muted)
1288                    .size(LabelSize::XSmall),
1289                )
1290                .child(
1291                    h_flex()
1292                        .gap_1()
1293                        .child(
1294                            IconButton::new("feedback-thumbs-up", IconName::ThumbsUp)
1295                                .icon_size(IconSize::XSmall)
1296                                .icon_color(match feedback {
1297                                    ThreadFeedback::Positive => Color::Accent,
1298                                    ThreadFeedback::Negative => Color::Ignored,
1299                                })
1300                                .shape(ui::IconButtonShape::Square)
1301                                .tooltip(Tooltip::text("Helpful Response"))
1302                                .on_click(cx.listener(move |this, _, window, cx| {
1303                                    this.handle_feedback_click(
1304                                        ThreadFeedback::Positive,
1305                                        window,
1306                                        cx,
1307                                    );
1308                                })),
1309                        )
1310                        .child(
1311                            IconButton::new("feedback-thumbs-down", IconName::ThumbsDown)
1312                                .icon_size(IconSize::XSmall)
1313                                .icon_color(match feedback {
1314                                    ThreadFeedback::Positive => Color::Ignored,
1315                                    ThreadFeedback::Negative => Color::Accent,
1316                                })
1317                                .shape(ui::IconButtonShape::Square)
1318                                .tooltip(Tooltip::text("Not Helpful"))
1319                                .on_click(cx.listener(move |this, _, window, cx| {
1320                                    this.handle_feedback_click(
1321                                        ThreadFeedback::Negative,
1322                                        window,
1323                                        cx,
1324                                    );
1325                                })),
1326                        ),
1327                )
1328                .into_any_element(),
1329            None => feedback_container
1330                .child(
1331                    Label::new(
1332                        "Rating the thread sends all of your current conversation to the Zed team.",
1333                    )
1334                    .color(Color::Muted)
1335                    .size(LabelSize::XSmall),
1336                )
1337                .child(
1338                    h_flex()
1339                        .gap_1()
1340                        .child(
1341                            IconButton::new("feedback-thumbs-up", IconName::ThumbsUp)
1342                                .icon_size(IconSize::XSmall)
1343                                .icon_color(Color::Ignored)
1344                                .shape(ui::IconButtonShape::Square)
1345                                .tooltip(Tooltip::text("Helpful Response"))
1346                                .on_click(cx.listener(move |this, _, window, cx| {
1347                                    this.handle_feedback_click(
1348                                        ThreadFeedback::Positive,
1349                                        window,
1350                                        cx,
1351                                    );
1352                                })),
1353                        )
1354                        .child(
1355                            IconButton::new("feedback-thumbs-down", IconName::ThumbsDown)
1356                                .icon_size(IconSize::XSmall)
1357                                .icon_color(Color::Ignored)
1358                                .shape(ui::IconButtonShape::Square)
1359                                .tooltip(Tooltip::text("Not Helpful"))
1360                                .on_click(cx.listener(move |this, _, window, cx| {
1361                                    this.handle_feedback_click(
1362                                        ThreadFeedback::Negative,
1363                                        window,
1364                                        cx,
1365                                    );
1366                                })),
1367                        ),
1368                )
1369                .into_any_element(),
1370        };
1371
1372        let message_is_empty = message.should_display_content();
1373        let has_content = !message_is_empty || !context.is_empty();
1374
1375        let message_content =
1376            has_content.then(|| {
1377                v_flex()
1378                    .gap_1p5()
1379                    .when(!message_is_empty, |parent| {
1380                        parent.child(
1381                            if let Some(edit_message_editor) = edit_message_editor.clone() {
1382                                div()
1383                                    .key_context("EditMessageEditor")
1384                                    .on_action(cx.listener(Self::cancel_editing_message))
1385                                    .on_action(cx.listener(Self::confirm_editing_message))
1386                                    .min_h_6()
1387                                    .child(edit_message_editor)
1388                                    .into_any()
1389                            } else {
1390                                div()
1391                                    .min_h_6()
1392                                    .text_ui(cx)
1393                                    .child(self.render_message_content(
1394                                        message_id,
1395                                        rendered_message,
1396                                        has_tool_uses,
1397                                        workspace.clone(),
1398                                        window,
1399                                        cx,
1400                                    ))
1401                                    .into_any()
1402                            },
1403                        )
1404                    })
1405                    .when(!context.is_empty(), |parent| {
1406                        parent.child(h_flex().flex_wrap().gap_1().children(
1407                            context.into_iter().map(|context| {
1408                                let context_id = context.id();
1409                                ContextPill::added(
1410                                    AddedContext::new(context, cx),
1411                                    false,
1412                                    false,
1413                                    None,
1414                                )
1415                                .on_click(Rc::new(cx.listener({
1416                                    let workspace = workspace.clone();
1417                                    let context_store = context_store.clone();
1418                                    move |_, _, window, cx| {
1419                                        if let Some(workspace) = workspace.upgrade() {
1420                                            open_context(
1421                                                context_id,
1422                                                context_store.clone(),
1423                                                workspace,
1424                                                window,
1425                                                cx,
1426                                            );
1427                                            cx.notify();
1428                                        }
1429                                    }
1430                                })))
1431                            }),
1432                        ))
1433                    })
1434            });
1435
1436        let styled_message = match message.role {
1437            Role::User => v_flex()
1438                .id(("message-container", ix))
1439                .map(|this| {
1440                    if is_first_message {
1441                        this.pt_2()
1442                    } else {
1443                        this.pt_4()
1444                    }
1445                })
1446                .pb_4()
1447                .pl_2()
1448                .pr_2p5()
1449                .child(
1450                    v_flex()
1451                        .bg(colors.editor_background)
1452                        .rounded_lg()
1453                        .border_1()
1454                        .border_color(colors.border)
1455                        .shadow_md()
1456                        .child(
1457                            h_flex()
1458                                .py_1()
1459                                .pl_2()
1460                                .pr_1()
1461                                .bg(bg_user_message_header)
1462                                .border_b_1()
1463                                .border_color(colors.border)
1464                                .justify_between()
1465                                .rounded_t_md()
1466                                .child(
1467                                    h_flex()
1468                                        .gap_1p5()
1469                                        .child(
1470                                            Icon::new(IconName::PersonCircle)
1471                                                .size(IconSize::XSmall)
1472                                                .color(Color::Muted),
1473                                        )
1474                                        .child(
1475                                            Label::new("You")
1476                                                .size(LabelSize::Small)
1477                                                .color(Color::Muted),
1478                                        ),
1479                                )
1480                                .child(
1481                                    h_flex()
1482                                        .gap_1()
1483                                        .when_some(
1484                                            edit_message_editor.clone(),
1485                                            |this, edit_message_editor| {
1486                                                let focus_handle =
1487                                                    edit_message_editor.focus_handle(cx);
1488                                                this.child(
1489                                                    Button::new("cancel-edit-message", "Cancel")
1490                                                        .label_size(LabelSize::Small)
1491                                                        .key_binding(
1492                                                            KeyBinding::for_action_in(
1493                                                                &menu::Cancel,
1494                                                                &focus_handle,
1495                                                                window,
1496                                                                cx,
1497                                                            )
1498                                                            .map(|kb| kb.size(rems_from_px(12.))),
1499                                                        )
1500                                                        .on_click(
1501                                                            cx.listener(Self::handle_cancel_click),
1502                                                        ),
1503                                                )
1504                                                .child(
1505                                                    Button::new(
1506                                                        "confirm-edit-message",
1507                                                        "Regenerate",
1508                                                    )
1509                                                    .label_size(LabelSize::Small)
1510                                                    .key_binding(
1511                                                        KeyBinding::for_action_in(
1512                                                            &menu::Confirm,
1513                                                            &focus_handle,
1514                                                            window,
1515                                                            cx,
1516                                                        )
1517                                                        .map(|kb| kb.size(rems_from_px(12.))),
1518                                                    )
1519                                                    .on_click(
1520                                                        cx.listener(Self::handle_regenerate_click),
1521                                                    ),
1522                                                )
1523                                            },
1524                                        )
1525                                        .when(
1526                                            edit_message_editor.is_none() && allow_editing_message,
1527                                            |this| {
1528                                                this.child(
1529                                                    Button::new("edit-message", "Edit")
1530                                                        .label_size(LabelSize::Small)
1531                                                        .on_click(cx.listener({
1532                                                            let message_segments =
1533                                                                message.segments.clone();
1534                                                            move |this, _, window, cx| {
1535                                                                this.start_editing_message(
1536                                                                    message_id,
1537                                                                    &message_segments,
1538                                                                    window,
1539                                                                    cx,
1540                                                                );
1541                                                            }
1542                                                        })),
1543                                                )
1544                                            },
1545                                        ),
1546                                ),
1547                        )
1548                        .child(div().p_2().children(message_content)),
1549                ),
1550            Role::Assistant => v_flex()
1551                .id(("message-container", ix))
1552                .ml_2()
1553                .pl_2()
1554                .pr_4()
1555                .border_l_1()
1556                .border_color(cx.theme().colors().border_variant)
1557                .children(message_content)
1558                .when(has_tool_uses, |parent| {
1559                    parent.children(
1560                        tool_uses
1561                            .into_iter()
1562                            .map(|tool_use| self.render_tool_use(tool_use, window, cx)),
1563                    )
1564                }),
1565            Role::System => div().id(("message-container", ix)).py_1().px_2().child(
1566                v_flex()
1567                    .bg(colors.editor_background)
1568                    .rounded_sm()
1569                    .child(div().p_4().children(message_content)),
1570            ),
1571        };
1572
1573        v_flex()
1574            .w_full()
1575            .when_some(checkpoint, |parent, checkpoint| {
1576                let mut is_pending = false;
1577                let mut error = None;
1578                if let Some(last_restore_checkpoint) =
1579                    self.thread.read(cx).last_restore_checkpoint()
1580                {
1581                    if last_restore_checkpoint.message_id() == message_id {
1582                        match last_restore_checkpoint {
1583                            LastRestoreCheckpoint::Pending { .. } => is_pending = true,
1584                            LastRestoreCheckpoint::Error { error: err, .. } => {
1585                                error = Some(err.clone());
1586                            }
1587                        }
1588                    }
1589                }
1590
1591                let restore_checkpoint_button =
1592                    Button::new(("restore-checkpoint", ix), "Restore Checkpoint")
1593                        .icon(if error.is_some() {
1594                            IconName::XCircle
1595                        } else {
1596                            IconName::Undo
1597                        })
1598                        .icon_size(IconSize::XSmall)
1599                        .icon_position(IconPosition::Start)
1600                        .icon_color(if error.is_some() {
1601                            Some(Color::Error)
1602                        } else {
1603                            None
1604                        })
1605                        .label_size(LabelSize::XSmall)
1606                        .disabled(is_pending)
1607                        .on_click(cx.listener(move |this, _, _window, cx| {
1608                            this.thread.update(cx, |thread, cx| {
1609                                thread
1610                                    .restore_checkpoint(checkpoint.clone(), cx)
1611                                    .detach_and_log_err(cx);
1612                            });
1613                        }));
1614
1615                let restore_checkpoint_button = if is_pending {
1616                    restore_checkpoint_button
1617                        .with_animation(
1618                            ("pulsating-restore-checkpoint-button", ix),
1619                            Animation::new(Duration::from_secs(2))
1620                                .repeat()
1621                                .with_easing(pulsating_between(0.6, 1.)),
1622                            |label, delta| label.alpha(delta),
1623                        )
1624                        .into_any_element()
1625                } else if let Some(error) = error {
1626                    restore_checkpoint_button
1627                        .tooltip(Tooltip::text(error.to_string()))
1628                        .into_any_element()
1629                } else {
1630                    restore_checkpoint_button.into_any_element()
1631                };
1632
1633                parent.child(
1634                    h_flex()
1635                        .pt_2p5()
1636                        .px_2p5()
1637                        .w_full()
1638                        .gap_1()
1639                        .child(ui::Divider::horizontal())
1640                        .child(restore_checkpoint_button)
1641                        .child(ui::Divider::horizontal()),
1642                )
1643            })
1644            .when(is_first_message, |parent| {
1645                parent.child(self.render_rules_item(cx))
1646            })
1647            .child(styled_message)
1648            .when(!needs_confirmation && generating_label.is_some(), |this| {
1649                this.child(
1650                    h_flex()
1651                        .h_8()
1652                        .mt_2()
1653                        .mb_4()
1654                        .ml_4()
1655                        .py_1p5()
1656                        .child(generating_label.unwrap()),
1657                )
1658            })
1659            .when(show_feedback && !is_generating, |parent| {
1660                parent.child(feedback_items).when_some(
1661                    self.feedback_message_editor.clone(),
1662                    |parent, feedback_editor| {
1663                        let focus_handle = feedback_editor.focus_handle(cx);
1664                        parent.child(
1665                            v_flex()
1666                                .key_context("AgentFeedbackMessageEditor")
1667                                .on_action(cx.listener(|this, _: &menu::Cancel, _, cx| {
1668                                    this.feedback_message_editor = None;
1669                                    cx.notify();
1670                                }))
1671                                .on_action(cx.listener(|this, _: &menu::Confirm, _, cx| {
1672                                    this.submit_feedback_message(cx);
1673                                    cx.notify();
1674                                }))
1675                                .on_action(cx.listener(Self::confirm_editing_message))
1676                                .my_3()
1677                                .mx_4()
1678                                .p_2()
1679                                .rounded_md()
1680                                .border_1()
1681                                .border_color(cx.theme().colors().border)
1682                                .bg(cx.theme().colors().editor_background)
1683                                .child(feedback_editor)
1684                                .child(
1685                                    h_flex()
1686                                        .gap_1()
1687                                        .justify_end()
1688                                        .child(
1689                                            Button::new("dismiss-feedback-message", "Cancel")
1690                                                .label_size(LabelSize::Small)
1691                                                .key_binding(
1692                                                    KeyBinding::for_action_in(
1693                                                        &menu::Cancel,
1694                                                        &focus_handle,
1695                                                        window,
1696                                                        cx,
1697                                                    )
1698                                                    .map(|kb| kb.size(rems_from_px(10.))),
1699                                                )
1700                                                .on_click(cx.listener(|this, _, _, cx| {
1701                                                    this.feedback_message_editor = None;
1702                                                    cx.notify();
1703                                                })),
1704                                        )
1705                                        .child(
1706                                            Button::new(
1707                                                "submit-feedback-message",
1708                                                "Share Feedback",
1709                                            )
1710                                            .style(ButtonStyle::Tinted(ui::TintColor::Accent))
1711                                            .label_size(LabelSize::Small)
1712                                            .key_binding(
1713                                                KeyBinding::for_action_in(
1714                                                    &menu::Confirm,
1715                                                    &focus_handle,
1716                                                    window,
1717                                                    cx,
1718                                                )
1719                                                .map(|kb| kb.size(rems_from_px(10.))),
1720                                            )
1721                                            .on_click(
1722                                                cx.listener(|this, _, _, cx| {
1723                                                    this.submit_feedback_message(cx);
1724                                                    cx.notify();
1725                                                }),
1726                                            ),
1727                                        ),
1728                                ),
1729                        )
1730                    },
1731                )
1732            })
1733            .into_any()
1734    }
1735
1736    fn render_message_content(
1737        &self,
1738        message_id: MessageId,
1739        rendered_message: &RenderedMessage,
1740        has_tool_uses: bool,
1741        workspace: WeakEntity<Workspace>,
1742        window: &Window,
1743        cx: &Context<Self>,
1744    ) -> impl IntoElement {
1745        let is_last_message = self.messages.last() == Some(&message_id);
1746        let is_generating = self.thread.read(cx).is_generating();
1747        let pending_thinking_segment_index = if is_generating && is_last_message && !has_tool_uses {
1748            rendered_message
1749                .segments
1750                .iter()
1751                .enumerate()
1752                .next_back()
1753                .filter(|(_, segment)| matches!(segment, RenderedMessageSegment::Thinking { .. }))
1754                .map(|(index, _)| index)
1755        } else {
1756            None
1757        };
1758
1759        v_flex()
1760            .text_ui(cx)
1761            .gap_2()
1762            .children(
1763                rendered_message.segments.iter().enumerate().map(
1764                    |(index, segment)| match segment {
1765                        RenderedMessageSegment::Thinking {
1766                            content,
1767                            scroll_handle,
1768                        } => self
1769                            .render_message_thinking_segment(
1770                                message_id,
1771                                index,
1772                                content.clone(),
1773                                &scroll_handle,
1774                                Some(index) == pending_thinking_segment_index,
1775                                window,
1776                                cx,
1777                            )
1778                            .into_any_element(),
1779                        RenderedMessageSegment::Text(markdown) => div()
1780                            .child(
1781                                MarkdownElement::new(
1782                                    markdown.clone(),
1783                                    default_markdown_style(window, cx),
1784                                )
1785                                .code_block_renderer(markdown::CodeBlockRenderer::Custom {
1786                                    render: Arc::new({
1787                                        let workspace = workspace.clone();
1788                                        let active_thread = cx.entity();
1789                                        move |id, kind, parsed_markdown, range, window, cx| {
1790                                            render_markdown_code_block(
1791                                                message_id,
1792                                                id,
1793                                                kind,
1794                                                parsed_markdown,
1795                                                range,
1796                                                active_thread.clone(),
1797                                                workspace.clone(),
1798                                                window,
1799                                                cx,
1800                                            )
1801                                        }
1802                                    }),
1803                                })
1804                                .on_url_click({
1805                                    let workspace = self.workspace.clone();
1806                                    move |text, window, cx| {
1807                                        open_markdown_link(text, workspace.clone(), window, cx);
1808                                    }
1809                                }),
1810                            )
1811                            .into_any_element(),
1812                    },
1813                ),
1814            )
1815    }
1816
1817    fn tool_card_border_color(&self, cx: &Context<Self>) -> Hsla {
1818        cx.theme().colors().border.opacity(0.5)
1819    }
1820
1821    fn tool_card_header_bg(&self, cx: &Context<Self>) -> Hsla {
1822        cx.theme()
1823            .colors()
1824            .element_background
1825            .blend(cx.theme().colors().editor_foreground.opacity(0.025))
1826    }
1827
1828    fn render_message_thinking_segment(
1829        &self,
1830        message_id: MessageId,
1831        ix: usize,
1832        markdown: Entity<Markdown>,
1833        scroll_handle: &ScrollHandle,
1834        pending: bool,
1835        window: &Window,
1836        cx: &Context<Self>,
1837    ) -> impl IntoElement {
1838        let is_open = self
1839            .expanded_thinking_segments
1840            .get(&(message_id, ix))
1841            .copied()
1842            .unwrap_or_default();
1843
1844        let editor_bg = cx.theme().colors().panel_background;
1845
1846        div().map(|this| {
1847            if pending {
1848                this.v_flex()
1849                    .mt_neg_2()
1850                    .mb_1p5()
1851                    .child(
1852                        h_flex()
1853                            .group("disclosure-header")
1854                            .justify_between()
1855                            .child(
1856                                h_flex()
1857                                    .gap_1p5()
1858                                    .child(
1859                                        Icon::new(IconName::LightBulb)
1860                                            .size(IconSize::XSmall)
1861                                            .color(Color::Muted),
1862                                    )
1863                                    .child({
1864                                        Label::new("Thinking")
1865                                            .color(Color::Muted)
1866                                            .size(LabelSize::Small)
1867                                            .with_animation(
1868                                                "generating-label",
1869                                                Animation::new(Duration::from_secs(1)).repeat(),
1870                                                |mut label, delta| {
1871                                                    let text = match delta {
1872                                                        d if d < 0.25 => "Thinking",
1873                                                        d if d < 0.5 => "Thinking.",
1874                                                        d if d < 0.75 => "Thinking..",
1875                                                        _ => "Thinking...",
1876                                                    };
1877                                                    label.set_text(text);
1878                                                    label
1879                                                },
1880                                            )
1881                                            .with_animation(
1882                                                "pulsating-label",
1883                                                Animation::new(Duration::from_secs(2))
1884                                                    .repeat()
1885                                                    .with_easing(pulsating_between(0.6, 1.)),
1886                                                |label, delta| {
1887                                                    label.map_element(|label| label.alpha(delta))
1888                                                },
1889                                            )
1890                                    }),
1891                            )
1892                            .child(
1893                                h_flex()
1894                                    .gap_1()
1895                                    .child(
1896                                        div().visible_on_hover("disclosure-header").child(
1897                                            Disclosure::new("thinking-disclosure", is_open)
1898                                                .opened_icon(IconName::ChevronUp)
1899                                                .closed_icon(IconName::ChevronDown)
1900                                                .on_click(cx.listener({
1901                                                    move |this, _event, _window, _cx| {
1902                                                        let is_open = this
1903                                                            .expanded_thinking_segments
1904                                                            .entry((message_id, ix))
1905                                                            .or_insert(false);
1906
1907                                                        *is_open = !*is_open;
1908                                                    }
1909                                                })),
1910                                        ),
1911                                    )
1912                                    .child({
1913                                        Icon::new(IconName::ArrowCircle)
1914                                            .color(Color::Accent)
1915                                            .size(IconSize::Small)
1916                                            .with_animation(
1917                                                "arrow-circle",
1918                                                Animation::new(Duration::from_secs(2)).repeat(),
1919                                                |icon, delta| {
1920                                                    icon.transform(Transformation::rotate(
1921                                                        percentage(delta),
1922                                                    ))
1923                                                },
1924                                            )
1925                                    }),
1926                            ),
1927                    )
1928                    .when(!is_open, |this| {
1929                        let gradient_overlay = div()
1930                            .rounded_b_lg()
1931                            .h_full()
1932                            .absolute()
1933                            .w_full()
1934                            .bottom_0()
1935                            .left_0()
1936                            .bg(linear_gradient(
1937                                180.,
1938                                linear_color_stop(editor_bg, 1.),
1939                                linear_color_stop(editor_bg.opacity(0.2), 0.),
1940                            ));
1941
1942                        this.child(
1943                            div()
1944                                .relative()
1945                                .bg(editor_bg)
1946                                .rounded_b_lg()
1947                                .mt_2()
1948                                .pl_4()
1949                                .child(
1950                                    div()
1951                                        .id(("thinking-content", ix))
1952                                        .max_h_20()
1953                                        .track_scroll(scroll_handle)
1954                                        .text_ui_sm(cx)
1955                                        .overflow_hidden()
1956                                        .child(
1957                                            MarkdownElement::new(
1958                                                markdown.clone(),
1959                                                default_markdown_style(window, cx),
1960                                            )
1961                                            .on_url_click({
1962                                                let workspace = self.workspace.clone();
1963                                                move |text, window, cx| {
1964                                                    open_markdown_link(
1965                                                        text,
1966                                                        workspace.clone(),
1967                                                        window,
1968                                                        cx,
1969                                                    );
1970                                                }
1971                                            }),
1972                                        ),
1973                                )
1974                                .child(gradient_overlay),
1975                        )
1976                    })
1977                    .when(is_open, |this| {
1978                        this.child(
1979                            div()
1980                                .id(("thinking-content", ix))
1981                                .h_full()
1982                                .bg(editor_bg)
1983                                .text_ui_sm(cx)
1984                                .child(
1985                                    MarkdownElement::new(
1986                                        markdown.clone(),
1987                                        default_markdown_style(window, cx),
1988                                    )
1989                                    .on_url_click({
1990                                        let workspace = self.workspace.clone();
1991                                        move |text, window, cx| {
1992                                            open_markdown_link(text, workspace.clone(), window, cx);
1993                                        }
1994                                    }),
1995                                ),
1996                        )
1997                    })
1998            } else {
1999                this.v_flex()
2000                    .mt_neg_2()
2001                    .child(
2002                        h_flex()
2003                            .group("disclosure-header")
2004                            .pr_1()
2005                            .justify_between()
2006                            .opacity(0.8)
2007                            .hover(|style| style.opacity(1.))
2008                            .child(
2009                                h_flex()
2010                                    .gap_1p5()
2011                                    .child(
2012                                        Icon::new(IconName::LightBulb)
2013                                            .size(IconSize::XSmall)
2014                                            .color(Color::Muted),
2015                                    )
2016                                    .child(Label::new("Thought Process").size(LabelSize::Small)),
2017                            )
2018                            .child(
2019                                div().visible_on_hover("disclosure-header").child(
2020                                    Disclosure::new("thinking-disclosure", is_open)
2021                                        .opened_icon(IconName::ChevronUp)
2022                                        .closed_icon(IconName::ChevronDown)
2023                                        .on_click(cx.listener({
2024                                            move |this, _event, _window, _cx| {
2025                                                let is_open = this
2026                                                    .expanded_thinking_segments
2027                                                    .entry((message_id, ix))
2028                                                    .or_insert(false);
2029
2030                                                *is_open = !*is_open;
2031                                            }
2032                                        })),
2033                                ),
2034                            ),
2035                    )
2036                    .child(
2037                        div()
2038                            .id(("thinking-content", ix))
2039                            .relative()
2040                            .mt_1p5()
2041                            .ml_1p5()
2042                            .pl_2p5()
2043                            .border_l_1()
2044                            .border_color(cx.theme().colors().border_variant)
2045                            .text_ui_sm(cx)
2046                            .when(is_open, |this| {
2047                                this.child(
2048                                    MarkdownElement::new(
2049                                        markdown.clone(),
2050                                        default_markdown_style(window, cx),
2051                                    )
2052                                    .on_url_click({
2053                                        let workspace = self.workspace.clone();
2054                                        move |text, window, cx| {
2055                                            open_markdown_link(text, workspace.clone(), window, cx);
2056                                        }
2057                                    }),
2058                                )
2059                            }),
2060                    )
2061            }
2062        })
2063    }
2064
2065    fn render_tool_use(
2066        &self,
2067        tool_use: ToolUse,
2068        window: &mut Window,
2069        cx: &mut Context<Self>,
2070    ) -> impl IntoElement + use<> {
2071        let is_open = self
2072            .expanded_tool_uses
2073            .get(&tool_use.id)
2074            .copied()
2075            .unwrap_or_default();
2076
2077        let is_status_finished = matches!(&tool_use.status, ToolUseStatus::Finished(_));
2078
2079        let fs = self
2080            .workspace
2081            .upgrade()
2082            .map(|workspace| workspace.read(cx).app_state().fs.clone());
2083        let needs_confirmation = matches!(&tool_use.status, ToolUseStatus::NeedsConfirmation);
2084        let edit_tools = tool_use.needs_confirmation;
2085
2086        let status_icons = div().child(match &tool_use.status {
2087            ToolUseStatus::Pending | ToolUseStatus::NeedsConfirmation => {
2088                let icon = Icon::new(IconName::Warning)
2089                    .color(Color::Warning)
2090                    .size(IconSize::Small);
2091                icon.into_any_element()
2092            }
2093            ToolUseStatus::Running => {
2094                let icon = Icon::new(IconName::ArrowCircle)
2095                    .color(Color::Accent)
2096                    .size(IconSize::Small);
2097                icon.with_animation(
2098                    "arrow-circle",
2099                    Animation::new(Duration::from_secs(2)).repeat(),
2100                    |icon, delta| icon.transform(Transformation::rotate(percentage(delta))),
2101                )
2102                .into_any_element()
2103            }
2104            ToolUseStatus::Finished(_) => div().w_0().into_any_element(),
2105            ToolUseStatus::Error(_) => {
2106                let icon = Icon::new(IconName::Close)
2107                    .color(Color::Error)
2108                    .size(IconSize::Small);
2109                icon.into_any_element()
2110            }
2111        });
2112
2113        let rendered_tool_use = self.rendered_tool_uses.get(&tool_use.id).cloned();
2114        let results_content_container = || v_flex().p_2().gap_0p5();
2115
2116        let results_content = v_flex()
2117            .gap_1()
2118            .child(
2119                results_content_container()
2120                    .child(
2121                        Label::new("Input")
2122                            .size(LabelSize::XSmall)
2123                            .color(Color::Muted)
2124                            .buffer_font(cx),
2125                    )
2126                    .child(
2127                        div()
2128                            .w_full()
2129                            .text_ui_sm(cx)
2130                            .children(rendered_tool_use.as_ref().map(|rendered| {
2131                                MarkdownElement::new(
2132                                    rendered.input.clone(),
2133                                    tool_use_markdown_style(window, cx),
2134                                )
2135                                .on_url_click({
2136                                    let workspace = self.workspace.clone();
2137                                    move |text, window, cx| {
2138                                        open_markdown_link(text, workspace.clone(), window, cx);
2139                                    }
2140                                })
2141                            })),
2142                    ),
2143            )
2144            .map(|container| match tool_use.status {
2145                ToolUseStatus::Finished(_) => container.child(
2146                    results_content_container()
2147                        .border_t_1()
2148                        .border_color(self.tool_card_border_color(cx))
2149                        .child(
2150                            Label::new("Result")
2151                                .size(LabelSize::XSmall)
2152                                .color(Color::Muted)
2153                                .buffer_font(cx),
2154                        )
2155                        .child(div().w_full().text_ui_sm(cx).children(
2156                            rendered_tool_use.as_ref().map(|rendered| {
2157                                MarkdownElement::new(
2158                                    rendered.output.clone(),
2159                                    tool_use_markdown_style(window, cx),
2160                                )
2161                                .on_url_click({
2162                                    let workspace = self.workspace.clone();
2163                                    move |text, window, cx| {
2164                                        open_markdown_link(text, workspace.clone(), window, cx);
2165                                    }
2166                                })
2167                            }),
2168                        )),
2169                ),
2170                ToolUseStatus::Running => container.child(
2171                    results_content_container().child(
2172                        h_flex()
2173                            .gap_1()
2174                            .pb_1()
2175                            .border_t_1()
2176                            .border_color(self.tool_card_border_color(cx))
2177                            .child(
2178                                Icon::new(IconName::ArrowCircle)
2179                                    .size(IconSize::Small)
2180                                    .color(Color::Accent)
2181                                    .with_animation(
2182                                        "arrow-circle",
2183                                        Animation::new(Duration::from_secs(2)).repeat(),
2184                                        |icon, delta| {
2185                                            icon.transform(Transformation::rotate(percentage(
2186                                                delta,
2187                                            )))
2188                                        },
2189                                    ),
2190                            )
2191                            .child(
2192                                Label::new("Running…")
2193                                    .size(LabelSize::XSmall)
2194                                    .color(Color::Muted)
2195                                    .buffer_font(cx),
2196                            ),
2197                    ),
2198                ),
2199                ToolUseStatus::Error(_) => container.child(
2200                    results_content_container()
2201                        .border_t_1()
2202                        .border_color(self.tool_card_border_color(cx))
2203                        .child(
2204                            Label::new("Error")
2205                                .size(LabelSize::XSmall)
2206                                .color(Color::Muted)
2207                                .buffer_font(cx),
2208                        )
2209                        .child(
2210                            div()
2211                                .text_ui_sm(cx)
2212                                .children(rendered_tool_use.as_ref().map(|rendered| {
2213                                    MarkdownElement::new(
2214                                        rendered.output.clone(),
2215                                        tool_use_markdown_style(window, cx),
2216                                    )
2217                                    .on_url_click({
2218                                        let workspace = self.workspace.clone();
2219                                        move |text, window, cx| {
2220                                            open_markdown_link(text, workspace.clone(), window, cx);
2221                                        }
2222                                    })
2223                                })),
2224                        ),
2225                ),
2226                ToolUseStatus::Pending => container,
2227                ToolUseStatus::NeedsConfirmation => container.child(
2228                    results_content_container()
2229                        .border_t_1()
2230                        .border_color(self.tool_card_border_color(cx))
2231                        .child(
2232                            Label::new("Asking Permission")
2233                                .size(LabelSize::Small)
2234                                .color(Color::Muted)
2235                                .buffer_font(cx),
2236                        ),
2237                ),
2238            });
2239
2240        let gradient_overlay = |color: Hsla| {
2241            div()
2242                .h_full()
2243                .absolute()
2244                .w_12()
2245                .bottom_0()
2246                .map(|element| {
2247                    if is_status_finished {
2248                        element.right_6()
2249                    } else {
2250                        element.right(px(44.))
2251                    }
2252                })
2253                .bg(linear_gradient(
2254                    90.,
2255                    linear_color_stop(color, 1.),
2256                    linear_color_stop(color.opacity(0.2), 0.),
2257                ))
2258        };
2259
2260        div().map(|element| {
2261            if !edit_tools {
2262                element.child(
2263                    v_flex()
2264                        .my_2()
2265                        .child(
2266                            h_flex()
2267                                .group("disclosure-header")
2268                                .relative()
2269                                .gap_1p5()
2270                                .justify_between()
2271                                .opacity(0.8)
2272                                .hover(|style| style.opacity(1.))
2273                                .when(!is_status_finished, |this| this.pr_2())
2274                                .child(
2275                                    h_flex()
2276                                        .id("tool-label-container")
2277                                        .gap_1p5()
2278                                        .max_w_full()
2279                                        .overflow_x_scroll()
2280                                        .child(
2281                                            Icon::new(tool_use.icon)
2282                                                .size(IconSize::XSmall)
2283                                                .color(Color::Muted),
2284                                        )
2285                                        .child(
2286                                            h_flex().pr_8().text_ui_sm(cx).children(
2287                                                rendered_tool_use.map(|rendered| MarkdownElement::new(rendered.label, tool_use_markdown_style(window, cx)).on_url_click({let workspace = self.workspace.clone(); move |text, window, cx| {
2288                                                    open_markdown_link(text, workspace.clone(), window, cx);
2289                                                }}))
2290                                            ),
2291                                        ),
2292                                )
2293                                .child(
2294                                    h_flex()
2295                                        .gap_1()
2296                                        .child(
2297                                            div().visible_on_hover("disclosure-header").child(
2298                                                Disclosure::new("tool-use-disclosure", is_open)
2299                                                    .opened_icon(IconName::ChevronUp)
2300                                                    .closed_icon(IconName::ChevronDown)
2301                                                    .on_click(cx.listener({
2302                                                        let tool_use_id = tool_use.id.clone();
2303                                                        move |this, _event, _window, _cx| {
2304                                                            let is_open = this
2305                                                                .expanded_tool_uses
2306                                                                .entry(tool_use_id.clone())
2307                                                                .or_insert(false);
2308
2309                                                            *is_open = !*is_open;
2310                                                        }
2311                                                    })),
2312                                            ),
2313                                        )
2314                                        .child(status_icons),
2315                                )
2316                                .child(gradient_overlay(cx.theme().colors().panel_background)),
2317                        )
2318                        .map(|parent| {
2319                            if !is_open {
2320                                return parent;
2321                            }
2322
2323                            parent.child(
2324                                v_flex()
2325                                    .mt_1()
2326                                    .border_1()
2327                                    .border_color(self.tool_card_border_color(cx))
2328                                    .bg(cx.theme().colors().editor_background)
2329                                    .rounded_lg()
2330                                    .child(results_content),
2331                            )
2332                        }),
2333                )
2334            } else {
2335                v_flex()
2336                    .my_3()
2337                    .rounded_lg()
2338                    .border_1()
2339                    .border_color(self.tool_card_border_color(cx))
2340                    .overflow_hidden()
2341                    .child(
2342                        h_flex()
2343                            .group("disclosure-header")
2344                            .relative()
2345                            .justify_between()
2346                            .py_1()
2347                            .map(|element| {
2348                                if is_status_finished {
2349                                    element.pl_2().pr_0p5()
2350                                } else {
2351                                    element.px_2()
2352                                }
2353                            })
2354                            .bg(self.tool_card_header_bg(cx))
2355                            .map(|element| {
2356                                if is_open {
2357                                    element.border_b_1().rounded_t_md()
2358                                } else if needs_confirmation {
2359                                    element.rounded_t_md()
2360                                } else {
2361                                    element.rounded_md()
2362                                }
2363                            })
2364                            .border_color(self.tool_card_border_color(cx))
2365                            .child(
2366                                h_flex()
2367                                    .id("tool-label-container")
2368                                    .gap_1p5()
2369                                    .max_w_full()
2370                                    .overflow_x_scroll()
2371                                    .child(
2372                                        Icon::new(tool_use.icon)
2373                                            .size(IconSize::XSmall)
2374                                            .color(Color::Muted),
2375                                    )
2376                                    .child(
2377                                        h_flex().pr_8().text_ui_sm(cx).children(
2378                                            rendered_tool_use.map(|rendered| MarkdownElement::new(rendered.label, tool_use_markdown_style(window, cx)).on_url_click({let workspace = self.workspace.clone(); move |text, window, cx| {
2379                                                open_markdown_link(text, workspace.clone(), window, cx);
2380                                            }}))
2381                                        ),
2382                                    ),
2383                            )
2384                            .child(
2385                                h_flex()
2386                                    .gap_1()
2387                                    .child(
2388                                        div().visible_on_hover("disclosure-header").child(
2389                                            Disclosure::new("tool-use-disclosure", is_open)
2390                                                .opened_icon(IconName::ChevronUp)
2391                                                .closed_icon(IconName::ChevronDown)
2392                                                .on_click(cx.listener({
2393                                                    let tool_use_id = tool_use.id.clone();
2394                                                    move |this, _event, _window, _cx| {
2395                                                        let is_open = this
2396                                                            .expanded_tool_uses
2397                                                            .entry(tool_use_id.clone())
2398                                                            .or_insert(false);
2399
2400                                                        *is_open = !*is_open;
2401                                                    }
2402                                                })),
2403                                        ),
2404                                    )
2405                                    .child(status_icons),
2406                            )
2407                            .child(gradient_overlay(self.tool_card_header_bg(cx))),
2408                    )
2409                    .map(|parent| {
2410                        if !is_open {
2411                            return parent;
2412                        }
2413
2414                        parent.child(
2415                            v_flex()
2416                                .bg(cx.theme().colors().editor_background)
2417                                .map(|element| {
2418                                    if  needs_confirmation {
2419                                        element.rounded_none()
2420                                    } else {
2421                                        element.rounded_b_lg()
2422                                    }
2423                                })
2424                                .child(results_content),
2425                        )
2426                    })
2427                    .when(needs_confirmation, |this| {
2428                        this.child(
2429                            h_flex()
2430                                .py_1()
2431                                .pl_2()
2432                                .pr_1()
2433                                .gap_1()
2434                                .justify_between()
2435                                .bg(cx.theme().colors().editor_background)
2436                                .border_t_1()
2437                                .border_color(self.tool_card_border_color(cx))
2438                                .rounded_b_lg()
2439                                .child(
2440                                    Label::new("Waiting for Confirmation…")
2441                                        .color(Color::Muted)
2442                                        .size(LabelSize::Small)
2443                                        .with_animation(
2444                                            "generating-label",
2445                                            Animation::new(Duration::from_secs(1)).repeat(),
2446                                            |mut label, delta| {
2447                                                let text = match delta {
2448                                                    d if d < 0.25 => "Waiting for Confirmation",
2449                                                    d if d < 0.5 => "Waiting for Confirmation.",
2450                                                    d if d < 0.75 => "Waiting for Confirmation..",
2451                                                    _ => "Waiting for Confirmation...",
2452                                                };
2453                                                label.set_text(text);
2454                                                label
2455                                            },
2456                                        )
2457                                        .with_animation(
2458                                            "pulsating-label",
2459                                            Animation::new(Duration::from_secs(2))
2460                                                .repeat()
2461                                                .with_easing(pulsating_between(0.6, 1.)),
2462                                            |label, delta| label.map_element(|label| label.alpha(delta)),
2463                                        ),
2464                                )
2465                                .child(
2466                                    h_flex()
2467                                        .gap_0p5()
2468                                        .child({
2469                                            let tool_id = tool_use.id.clone();
2470                                            Button::new(
2471                                                "always-allow-tool-action",
2472                                                "Always Allow",
2473                                            )
2474                                            .label_size(LabelSize::Small)
2475                                            .icon(IconName::CheckDouble)
2476                                            .icon_position(IconPosition::Start)
2477                                            .icon_size(IconSize::Small)
2478                                            .icon_color(Color::Success)
2479                                            .tooltip(move |window, cx|  {
2480                                                Tooltip::with_meta(
2481                                                    "Never ask for permission",
2482                                                    None,
2483                                                    "Restore the original behavior in your Agent Panel settings",
2484                                                    window,
2485                                                    cx,
2486                                                )
2487                                            })
2488                                            .on_click(cx.listener(
2489                                                move |this, event, window, cx| {
2490                                                    if let Some(fs) = fs.clone() {
2491                                                        update_settings_file::<AssistantSettings>(
2492                                                            fs.clone(),
2493                                                            cx,
2494                                                            |settings, _| {
2495                                                                settings.set_always_allow_tool_actions(true);
2496                                                            },
2497                                                        );
2498                                                    }
2499                                                    this.handle_allow_tool(
2500                                                        tool_id.clone(),
2501                                                        event,
2502                                                        window,
2503                                                        cx,
2504                                                    )
2505                                                },
2506                                            ))
2507                                        })
2508                                        .child(ui::Divider::vertical())
2509                                        .child({
2510                                            let tool_id = tool_use.id.clone();
2511                                            Button::new("allow-tool-action", "Allow")
2512                                                .label_size(LabelSize::Small)
2513                                                .icon(IconName::Check)
2514                                                .icon_position(IconPosition::Start)
2515                                                .icon_size(IconSize::Small)
2516                                                .icon_color(Color::Success)
2517                                                .on_click(cx.listener(
2518                                                    move |this, event, window, cx| {
2519                                                        this.handle_allow_tool(
2520                                                            tool_id.clone(),
2521                                                            event,
2522                                                            window,
2523                                                            cx,
2524                                                        )
2525                                                    },
2526                                                ))
2527                                        })
2528                                        .child({
2529                                            let tool_id = tool_use.id.clone();
2530                                            let tool_name: Arc<str> = tool_use.name.into();
2531                                            Button::new("deny-tool", "Deny")
2532                                                .label_size(LabelSize::Small)
2533                                                .icon(IconName::Close)
2534                                                .icon_position(IconPosition::Start)
2535                                                .icon_size(IconSize::Small)
2536                                                .icon_color(Color::Error)
2537                                                .on_click(cx.listener(
2538                                                    move |this, event, window, cx| {
2539                                                        this.handle_deny_tool(
2540                                                            tool_id.clone(),
2541                                                            tool_name.clone(),
2542                                                            event,
2543                                                            window,
2544                                                            cx,
2545                                                        )
2546                                                    },
2547                                                ))
2548                                        }),
2549                                ),
2550                        )
2551                    })
2552            }
2553        })
2554    }
2555
2556    fn render_rules_item(&self, cx: &Context<Self>) -> AnyElement {
2557        let Some(system_prompt_context) = self.thread.read(cx).system_prompt_context().as_ref()
2558        else {
2559            return div().into_any();
2560        };
2561
2562        let rules_files = system_prompt_context
2563            .worktrees
2564            .iter()
2565            .filter_map(|worktree| worktree.rules_file.as_ref())
2566            .collect::<Vec<_>>();
2567
2568        let label_text = match rules_files.as_slice() {
2569            &[] => return div().into_any(),
2570            &[rules_file] => {
2571                format!("Using {:?} file", rules_file.rel_path)
2572            }
2573            rules_files => {
2574                format!("Using {} rules files", rules_files.len())
2575            }
2576        };
2577
2578        div()
2579            .pt_2()
2580            .px_2p5()
2581            .child(
2582                h_flex()
2583                    .w_full()
2584                    .gap_0p5()
2585                    .child(
2586                        h_flex()
2587                            .gap_1p5()
2588                            .child(
2589                                Icon::new(IconName::File)
2590                                    .size(IconSize::XSmall)
2591                                    .color(Color::Disabled),
2592                            )
2593                            .child(
2594                                Label::new(label_text)
2595                                    .size(LabelSize::XSmall)
2596                                    .color(Color::Muted)
2597                                    .buffer_font(cx),
2598                            ),
2599                    )
2600                    .child(
2601                        IconButton::new("open-rule", IconName::ArrowUpRightAlt)
2602                            .shape(ui::IconButtonShape::Square)
2603                            .icon_size(IconSize::XSmall)
2604                            .icon_color(Color::Ignored)
2605                            .on_click(cx.listener(Self::handle_open_rules))
2606                            .tooltip(Tooltip::text("View Rules")),
2607                    ),
2608            )
2609            .into_any()
2610    }
2611
2612    fn handle_allow_tool(
2613        &mut self,
2614        tool_use_id: LanguageModelToolUseId,
2615        _: &ClickEvent,
2616        _window: &mut Window,
2617        cx: &mut Context<Self>,
2618    ) {
2619        if let Some(PendingToolUseStatus::NeedsConfirmation(c)) = self
2620            .thread
2621            .read(cx)
2622            .pending_tool(&tool_use_id)
2623            .map(|tool_use| tool_use.status.clone())
2624        {
2625            self.thread.update(cx, |thread, cx| {
2626                thread.run_tool(
2627                    c.tool_use_id.clone(),
2628                    c.ui_text.clone(),
2629                    c.input.clone(),
2630                    &c.messages,
2631                    c.tool.clone(),
2632                    cx,
2633                );
2634            });
2635        }
2636    }
2637
2638    fn handle_deny_tool(
2639        &mut self,
2640        tool_use_id: LanguageModelToolUseId,
2641        tool_name: Arc<str>,
2642        _: &ClickEvent,
2643        _window: &mut Window,
2644        cx: &mut Context<Self>,
2645    ) {
2646        self.thread.update(cx, |thread, cx| {
2647            thread.deny_tool_use(tool_use_id, tool_name, cx);
2648        });
2649    }
2650
2651    fn handle_open_rules(&mut self, _: &ClickEvent, window: &mut Window, cx: &mut Context<Self>) {
2652        let Some(system_prompt_context) = self.thread.read(cx).system_prompt_context().as_ref()
2653        else {
2654            return;
2655        };
2656
2657        let abs_paths = system_prompt_context
2658            .worktrees
2659            .iter()
2660            .flat_map(|worktree| worktree.rules_file.as_ref())
2661            .map(|rules_file| rules_file.abs_path.to_path_buf())
2662            .collect::<Vec<_>>();
2663
2664        if let Ok(task) = self.workspace.update(cx, move |workspace, cx| {
2665            // TODO: Open a multibuffer instead? In some cases this doesn't make the set of rules
2666            // files clear. For example, if rules file 1 is already open but rules file 2 is not,
2667            // this would open and focus rules file 2 in a tab that is not next to rules file 1.
2668            workspace.open_paths(abs_paths, OpenOptions::default(), None, window, cx)
2669        }) {
2670            task.detach();
2671        }
2672    }
2673
2674    fn dismiss_notifications(&mut self, cx: &mut Context<ActiveThread>) {
2675        for window in self.notifications.drain(..) {
2676            window
2677                .update(cx, |_, window, _| {
2678                    window.remove_window();
2679                })
2680                .ok();
2681
2682            self.notification_subscriptions.remove(&window);
2683        }
2684    }
2685
2686    fn render_vertical_scrollbar(&self, cx: &mut Context<Self>) -> Option<Stateful<Div>> {
2687        if !self.show_scrollbar && !self.scrollbar_state.is_dragging() {
2688            return None;
2689        }
2690
2691        Some(
2692            div()
2693                .occlude()
2694                .id("active-thread-scrollbar")
2695                .on_mouse_move(cx.listener(|_, _, _, cx| {
2696                    cx.notify();
2697                    cx.stop_propagation()
2698                }))
2699                .on_hover(|_, _, cx| {
2700                    cx.stop_propagation();
2701                })
2702                .on_any_mouse_down(|_, _, cx| {
2703                    cx.stop_propagation();
2704                })
2705                .on_mouse_up(
2706                    MouseButton::Left,
2707                    cx.listener(|_, _, _, cx| {
2708                        cx.stop_propagation();
2709                    }),
2710                )
2711                .on_scroll_wheel(cx.listener(|_, _, _, cx| {
2712                    cx.notify();
2713                }))
2714                .h_full()
2715                .absolute()
2716                .right_1()
2717                .top_1()
2718                .bottom_0()
2719                .w(px(12.))
2720                .cursor_default()
2721                .children(Scrollbar::vertical(self.scrollbar_state.clone())),
2722        )
2723    }
2724
2725    fn hide_scrollbar_later(&mut self, cx: &mut Context<Self>) {
2726        const SCROLLBAR_SHOW_INTERVAL: Duration = Duration::from_secs(1);
2727        self.hide_scrollbar_task = Some(cx.spawn(async move |thread, cx| {
2728            cx.background_executor()
2729                .timer(SCROLLBAR_SHOW_INTERVAL)
2730                .await;
2731            thread
2732                .update(cx, |thread, cx| {
2733                    if !thread.scrollbar_state.is_dragging() {
2734                        thread.show_scrollbar = false;
2735                        cx.notify();
2736                    }
2737                })
2738                .log_err();
2739        }))
2740    }
2741}
2742
2743impl Render for ActiveThread {
2744    fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
2745        v_flex()
2746            .size_full()
2747            .relative()
2748            .on_mouse_move(cx.listener(|this, _, _, cx| {
2749                this.show_scrollbar = true;
2750                this.hide_scrollbar_later(cx);
2751                cx.notify();
2752            }))
2753            .on_scroll_wheel(cx.listener(|this, _, _, cx| {
2754                this.show_scrollbar = true;
2755                this.hide_scrollbar_later(cx);
2756                cx.notify();
2757            }))
2758            .on_mouse_up(
2759                MouseButton::Left,
2760                cx.listener(|this, _, _, cx| {
2761                    this.hide_scrollbar_later(cx);
2762                }),
2763            )
2764            .child(list(self.list_state.clone()).flex_grow())
2765            .when_some(self.render_vertical_scrollbar(cx), |this, scrollbar| {
2766                this.child(scrollbar)
2767            })
2768    }
2769}
2770
2771pub(crate) fn open_context(
2772    id: ContextId,
2773    context_store: Entity<ContextStore>,
2774    workspace: Entity<Workspace>,
2775    window: &mut Window,
2776    cx: &mut App,
2777) {
2778    let Some(context) = context_store.read(cx).context_for_id(id) else {
2779        return;
2780    };
2781
2782    match context {
2783        AssistantContext::File(file_context) => {
2784            if let Some(project_path) = file_context.context_buffer.buffer.read(cx).project_path(cx)
2785            {
2786                workspace.update(cx, |workspace, cx| {
2787                    workspace
2788                        .open_path(project_path, None, true, window, cx)
2789                        .detach_and_log_err(cx);
2790                });
2791            }
2792        }
2793        AssistantContext::Directory(directory_context) => {
2794            let path = directory_context.project_path.clone();
2795            workspace.update(cx, |workspace, cx| {
2796                workspace.project().update(cx, |project, cx| {
2797                    if let Some(entry) = project.entry_for_path(&path, cx) {
2798                        cx.emit(project::Event::RevealInProjectPanel(entry.id));
2799                    }
2800                })
2801            })
2802        }
2803        AssistantContext::Symbol(symbol_context) => {
2804            if let Some(project_path) = symbol_context
2805                .context_symbol
2806                .buffer
2807                .read(cx)
2808                .project_path(cx)
2809            {
2810                let snapshot = symbol_context.context_symbol.buffer.read(cx).snapshot();
2811                let target_position = symbol_context
2812                    .context_symbol
2813                    .id
2814                    .range
2815                    .start
2816                    .to_point(&snapshot);
2817
2818                let open_task = workspace.update(cx, |workspace, cx| {
2819                    workspace.open_path(project_path, None, true, window, cx)
2820                });
2821                window
2822                    .spawn(cx, async move |cx| {
2823                        if let Some(active_editor) = open_task
2824                            .await
2825                            .log_err()
2826                            .and_then(|item| item.downcast::<Editor>())
2827                        {
2828                            active_editor
2829                                .downgrade()
2830                                .update_in(cx, |editor, window, cx| {
2831                                    editor.go_to_singleton_buffer_point(
2832                                        target_position,
2833                                        window,
2834                                        cx,
2835                                    );
2836                                })
2837                                .log_err();
2838                        }
2839                    })
2840                    .detach();
2841            }
2842        }
2843        AssistantContext::FetchedUrl(fetched_url_context) => {
2844            cx.open_url(&fetched_url_context.url);
2845        }
2846        AssistantContext::Thread(thread_context) => {
2847            let thread_id = thread_context.thread.read(cx).id().clone();
2848            workspace.update(cx, |workspace, cx| {
2849                if let Some(panel) = workspace.panel::<AssistantPanel>(cx) {
2850                    panel.update(cx, |panel, cx| {
2851                        panel
2852                            .open_thread(&thread_id, window, cx)
2853                            .detach_and_log_err(cx)
2854                    });
2855                }
2856            })
2857        }
2858    }
2859}