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