active_thread.rs

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