active_thread.rs

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