active_thread.rs

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