active_thread.rs

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