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