active_thread.rs

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