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