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