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            ThreadEvent::ReceivedTextChunk => {}
1034        }
1035    }
1036
1037    fn handle_rules_loading_error(
1038        &mut self,
1039        _thread_store: Entity<ThreadStore>,
1040        error: &RulesLoadingError,
1041        cx: &mut Context<Self>,
1042    ) {
1043        self.last_error = Some(ThreadError::Message {
1044            header: "Error loading rules file".into(),
1045            message: error.message.clone(),
1046        });
1047        cx.notify();
1048    }
1049
1050    fn show_notification(
1051        &mut self,
1052        caption: impl Into<SharedString>,
1053        icon: IconName,
1054        window: &mut Window,
1055        cx: &mut Context<ActiveThread>,
1056    ) {
1057        if window.is_window_active() || !self.notifications.is_empty() {
1058            return;
1059        }
1060
1061        let title = self
1062            .thread
1063            .read(cx)
1064            .summary()
1065            .unwrap_or("Agent Panel".into());
1066
1067        match AssistantSettings::get_global(cx).notify_when_agent_waiting {
1068            NotifyWhenAgentWaiting::PrimaryScreen => {
1069                if let Some(primary) = cx.primary_display() {
1070                    self.pop_up(icon, caption.into(), title.clone(), window, primary, cx);
1071                }
1072            }
1073            NotifyWhenAgentWaiting::AllScreens => {
1074                let caption = caption.into();
1075                for screen in cx.displays() {
1076                    self.pop_up(icon, caption.clone(), title.clone(), window, screen, cx);
1077                }
1078            }
1079            NotifyWhenAgentWaiting::Never => {
1080                // Don't show anything
1081            }
1082        }
1083    }
1084
1085    fn pop_up(
1086        &mut self,
1087        icon: IconName,
1088        caption: SharedString,
1089        title: SharedString,
1090        window: &mut Window,
1091        screen: Rc<dyn PlatformDisplay>,
1092        cx: &mut Context<'_, ActiveThread>,
1093    ) {
1094        let options = AgentNotification::window_options(screen, cx);
1095
1096        if let Some(screen_window) = cx
1097            .open_window(options, |_, cx| {
1098                cx.new(|_| AgentNotification::new(title.clone(), caption.clone(), icon))
1099            })
1100            .log_err()
1101        {
1102            if let Some(pop_up) = screen_window.entity(cx).log_err() {
1103                self.notification_subscriptions
1104                    .entry(screen_window)
1105                    .or_insert_with(Vec::new)
1106                    .push(cx.subscribe_in(&pop_up, window, {
1107                        |this, _, event, window, cx| match event {
1108                            AgentNotificationEvent::Accepted => {
1109                                let handle = window.window_handle();
1110                                cx.activate(true);
1111
1112                                let workspace_handle = this.workspace.clone();
1113
1114                                // If there are multiple Zed windows, activate the correct one.
1115                                cx.defer(move |cx| {
1116                                    handle
1117                                        .update(cx, |_view, window, _cx| {
1118                                            window.activate_window();
1119
1120                                            if let Some(workspace) = workspace_handle.upgrade() {
1121                                                workspace.update(_cx, |workspace, cx| {
1122                                                    workspace
1123                                                        .focus_panel::<AssistantPanel>(window, cx);
1124                                                });
1125                                            }
1126                                        })
1127                                        .log_err();
1128                                });
1129
1130                                this.dismiss_notifications(cx);
1131                            }
1132                            AgentNotificationEvent::Dismissed => {
1133                                this.dismiss_notifications(cx);
1134                            }
1135                        }
1136                    }));
1137
1138                self.notifications.push(screen_window);
1139
1140                // If the user manually refocuses the original window, dismiss the popup.
1141                self.notification_subscriptions
1142                    .entry(screen_window)
1143                    .or_insert_with(Vec::new)
1144                    .push({
1145                        let pop_up_weak = pop_up.downgrade();
1146
1147                        cx.observe_window_activation(window, move |_, window, cx| {
1148                            if window.is_window_active() {
1149                                if let Some(pop_up) = pop_up_weak.upgrade() {
1150                                    pop_up.update(cx, |_, cx| {
1151                                        cx.emit(AgentNotificationEvent::Dismissed);
1152                                    });
1153                                }
1154                            }
1155                        })
1156                    });
1157            }
1158        }
1159    }
1160
1161    /// Spawns a task to save the active thread.
1162    ///
1163    /// Only one task to save the thread will be in flight at a time.
1164    fn save_thread(&mut self, cx: &mut Context<Self>) {
1165        let thread = self.thread.clone();
1166        self.save_thread_task = Some(cx.spawn(async move |this, cx| {
1167            let task = this
1168                .update(cx, |this, cx| {
1169                    this.thread_store
1170                        .update(cx, |thread_store, cx| thread_store.save_thread(&thread, cx))
1171                })
1172                .ok();
1173
1174            if let Some(task) = task {
1175                task.await.log_err();
1176            }
1177        }));
1178    }
1179
1180    fn start_editing_message(
1181        &mut self,
1182        message_id: MessageId,
1183        message_segments: &[MessageSegment],
1184        window: &mut Window,
1185        cx: &mut Context<Self>,
1186    ) {
1187        // User message should always consist of a single text segment,
1188        // therefore we can skip returning early if it's not a text segment.
1189        let Some(MessageSegment::Text(message_text)) = message_segments.first() else {
1190            return;
1191        };
1192
1193        let buffer = cx.new(|cx| {
1194            MultiBuffer::singleton(cx.new(|cx| Buffer::local(message_text.clone(), cx)), cx)
1195        });
1196        let editor = cx.new(|cx| {
1197            let mut editor = Editor::new(
1198                editor::EditorMode::AutoHeight { max_lines: 8 },
1199                buffer,
1200                None,
1201                window,
1202                cx,
1203            );
1204            editor.focus_handle(cx).focus(window);
1205            editor.move_to_end(&editor::actions::MoveToEnd, window, cx);
1206            editor
1207        });
1208        let subscription = cx.subscribe(&editor, |this, _, event, cx| match event {
1209            EditorEvent::BufferEdited => {
1210                this.update_editing_message_token_count(true, cx);
1211            }
1212            _ => {}
1213        });
1214        self.editing_message = Some((
1215            message_id,
1216            EditMessageState {
1217                editor: editor.clone(),
1218                last_estimated_token_count: None,
1219                _subscription: subscription,
1220                _update_token_count_task: None,
1221            },
1222        ));
1223        self.update_editing_message_token_count(false, cx);
1224        cx.notify();
1225    }
1226
1227    fn update_editing_message_token_count(&mut self, debounce: bool, cx: &mut Context<Self>) {
1228        let Some((message_id, state)) = self.editing_message.as_mut() else {
1229            return;
1230        };
1231
1232        cx.emit(ActiveThreadEvent::EditingMessageTokenCountChanged);
1233        state._update_token_count_task.take();
1234
1235        let Some(default_model) = LanguageModelRegistry::read_global(cx).default_model() else {
1236            state.last_estimated_token_count.take();
1237            return;
1238        };
1239
1240        let editor = state.editor.clone();
1241        let thread = self.thread.clone();
1242        let message_id = *message_id;
1243
1244        state._update_token_count_task = Some(cx.spawn(async move |this, cx| {
1245            if debounce {
1246                cx.background_executor()
1247                    .timer(Duration::from_millis(200))
1248                    .await;
1249            }
1250
1251            let token_count = if let Some(task) = cx.update(|cx| {
1252                let context = thread.read(cx).context_for_message(message_id);
1253                let new_context = thread.read(cx).filter_new_context(context);
1254                let context_text =
1255                    format_context_as_string(new_context, cx).unwrap_or(String::new());
1256                let message_text = editor.read(cx).text(cx);
1257
1258                let content = context_text + &message_text;
1259
1260                if content.is_empty() {
1261                    return None;
1262                }
1263
1264                let request = language_model::LanguageModelRequest {
1265                    thread_id: None,
1266                    prompt_id: None,
1267                    messages: vec![LanguageModelRequestMessage {
1268                        role: language_model::Role::User,
1269                        content: vec![content.into()],
1270                        cache: false,
1271                    }],
1272                    tools: vec![],
1273                    stop: vec![],
1274                    temperature: None,
1275                };
1276
1277                Some(default_model.model.count_tokens(request, cx))
1278            })? {
1279                task.await?
1280            } else {
1281                0
1282            };
1283
1284            this.update(cx, |this, cx| {
1285                let Some((_message_id, state)) = this.editing_message.as_mut() else {
1286                    return;
1287                };
1288
1289                state.last_estimated_token_count = Some(token_count);
1290                cx.emit(ActiveThreadEvent::EditingMessageTokenCountChanged);
1291            })
1292        }));
1293    }
1294
1295    fn cancel_editing_message(&mut self, _: &menu::Cancel, _: &mut Window, cx: &mut Context<Self>) {
1296        self.editing_message.take();
1297        cx.notify();
1298    }
1299
1300    fn confirm_editing_message(
1301        &mut self,
1302        _: &menu::Confirm,
1303        _: &mut Window,
1304        cx: &mut Context<Self>,
1305    ) {
1306        let Some((message_id, state)) = self.editing_message.take() else {
1307            return;
1308        };
1309        let edited_text = state.editor.read(cx).text(cx);
1310        self.thread.update(cx, |thread, cx| {
1311            thread.edit_message(
1312                message_id,
1313                Role::User,
1314                vec![MessageSegment::Text(edited_text)],
1315                cx,
1316            );
1317            for message_id in self.messages_after(message_id) {
1318                thread.delete_message(*message_id, cx);
1319            }
1320        });
1321
1322        let Some(model) = LanguageModelRegistry::read_global(cx).default_model() else {
1323            return;
1324        };
1325
1326        if model.provider.must_accept_terms(cx) {
1327            cx.notify();
1328            return;
1329        }
1330
1331        self.thread.update(cx, |thread, cx| {
1332            thread.advance_prompt_id();
1333            thread.send_to_model(model.model, cx)
1334        });
1335        cx.notify();
1336    }
1337
1338    fn messages_after(&self, message_id: MessageId) -> &[MessageId] {
1339        self.messages
1340            .iter()
1341            .position(|id| *id == message_id)
1342            .map(|index| &self.messages[index + 1..])
1343            .unwrap_or(&[])
1344    }
1345
1346    fn handle_cancel_click(&mut self, _: &ClickEvent, window: &mut Window, cx: &mut Context<Self>) {
1347        self.cancel_editing_message(&menu::Cancel, window, cx);
1348    }
1349
1350    fn handle_regenerate_click(
1351        &mut self,
1352        _: &ClickEvent,
1353        window: &mut Window,
1354        cx: &mut Context<Self>,
1355    ) {
1356        self.confirm_editing_message(&menu::Confirm, window, cx);
1357    }
1358
1359    fn handle_feedback_click(
1360        &mut self,
1361        message_id: MessageId,
1362        feedback: ThreadFeedback,
1363        window: &mut Window,
1364        cx: &mut Context<Self>,
1365    ) {
1366        let report = self.thread.update(cx, |thread, cx| {
1367            thread.report_message_feedback(message_id, feedback, cx)
1368        });
1369
1370        cx.spawn(async move |this, cx| {
1371            report.await?;
1372            this.update(cx, |_this, cx| cx.notify())
1373        })
1374        .detach_and_log_err(cx);
1375
1376        match feedback {
1377            ThreadFeedback::Positive => {
1378                self.open_feedback_editors.remove(&message_id);
1379            }
1380            ThreadFeedback::Negative => {
1381                self.handle_show_feedback_comments(message_id, window, cx);
1382            }
1383        }
1384    }
1385
1386    fn handle_show_feedback_comments(
1387        &mut self,
1388        message_id: MessageId,
1389        window: &mut Window,
1390        cx: &mut Context<Self>,
1391    ) {
1392        let buffer = cx.new(|cx| {
1393            let empty_string = String::new();
1394            MultiBuffer::singleton(cx.new(|cx| Buffer::local(empty_string, cx)), cx)
1395        });
1396
1397        let editor = cx.new(|cx| {
1398            let mut editor = Editor::new(
1399                editor::EditorMode::AutoHeight { max_lines: 4 },
1400                buffer,
1401                None,
1402                window,
1403                cx,
1404            );
1405            editor.set_placeholder_text(
1406                "What went wrong? Share your feedback so we can improve.",
1407                cx,
1408            );
1409            editor
1410        });
1411
1412        editor.read(cx).focus_handle(cx).focus(window);
1413        self.open_feedback_editors.insert(message_id, editor);
1414        cx.notify();
1415    }
1416
1417    fn submit_feedback_message(&mut self, message_id: MessageId, cx: &mut Context<Self>) {
1418        let Some(editor) = self.open_feedback_editors.get(&message_id) else {
1419            return;
1420        };
1421
1422        let report_task = self.thread.update(cx, |thread, cx| {
1423            thread.report_message_feedback(message_id, ThreadFeedback::Negative, cx)
1424        });
1425
1426        let comments = editor.read(cx).text(cx);
1427        if !comments.is_empty() {
1428            let thread_id = self.thread.read(cx).id().clone();
1429            let comments_value = String::from(comments.as_str());
1430
1431            let message_content = self
1432                .thread
1433                .read(cx)
1434                .message(message_id)
1435                .map(|msg| msg.to_string())
1436                .unwrap_or_default();
1437
1438            telemetry::event!(
1439                "Assistant Thread Feedback Comments",
1440                thread_id,
1441                message_id = message_id.0,
1442                message_content,
1443                comments = comments_value
1444            );
1445
1446            self.open_feedback_editors.remove(&message_id);
1447
1448            cx.spawn(async move |this, cx| {
1449                report_task.await?;
1450                this.update(cx, |_this, cx| cx.notify())
1451            })
1452            .detach_and_log_err(cx);
1453        }
1454    }
1455
1456    fn render_message(&self, ix: usize, window: &mut Window, cx: &mut Context<Self>) -> AnyElement {
1457        let message_id = self.messages[ix];
1458        let Some(message) = self.thread.read(cx).message(message_id) else {
1459            return Empty.into_any();
1460        };
1461
1462        let Some(rendered_message) = self.rendered_messages_by_id.get(&message_id) else {
1463            return Empty.into_any();
1464        };
1465
1466        let context_store = self.context_store.clone();
1467        let workspace = self.workspace.clone();
1468        let thread = self.thread.read(cx);
1469
1470        // Get all the data we need from thread before we start using it in closures
1471        let checkpoint = thread.checkpoint_for_message(message_id);
1472        let context = thread.context_for_message(message_id).collect::<Vec<_>>();
1473
1474        let tool_uses = thread.tool_uses_for_message(message_id, cx);
1475        let has_tool_uses = !tool_uses.is_empty();
1476        let is_generating = thread.is_generating();
1477
1478        let is_first_message = ix == 0;
1479        let is_last_message = ix == self.messages.len() - 1;
1480
1481        let show_feedback = (!is_generating && is_last_message && message.role != Role::User)
1482            || self.messages.get(ix + 1).map_or(false, |next_id| {
1483                self.thread
1484                    .read(cx)
1485                    .message(*next_id)
1486                    .map_or(false, |next_message| {
1487                        next_message.role == Role::User
1488                            && thread.tool_uses_for_message(*next_id, cx).is_empty()
1489                            && thread.tool_results_for_message(*next_id).is_empty()
1490                    })
1491            });
1492
1493        let needs_confirmation = tool_uses.iter().any(|tool_use| tool_use.needs_confirmation);
1494
1495        let generating_label = (is_generating && is_last_message).then(|| {
1496            Label::new("Generating")
1497                .color(Color::Muted)
1498                .size(LabelSize::Small)
1499                .with_animations(
1500                    "generating-label",
1501                    vec![
1502                        Animation::new(Duration::from_secs(1)),
1503                        Animation::new(Duration::from_secs(1)).repeat(),
1504                    ],
1505                    |mut label, animation_ix, delta| {
1506                        match animation_ix {
1507                            0 => {
1508                                let chars_to_show = (delta * 10.).ceil() as usize;
1509                                let text = &"Generating"[0..chars_to_show];
1510                                label.set_text(text);
1511                            }
1512                            1 => {
1513                                let text = match delta {
1514                                    d if d < 0.25 => "Generating",
1515                                    d if d < 0.5 => "Generating.",
1516                                    d if d < 0.75 => "Generating..",
1517                                    _ => "Generating...",
1518                                };
1519                                label.set_text(text);
1520                            }
1521                            _ => {}
1522                        }
1523                        label
1524                    },
1525                )
1526                .with_animation(
1527                    "pulsating-label",
1528                    Animation::new(Duration::from_secs(2))
1529                        .repeat()
1530                        .with_easing(pulsating_between(0.6, 1.)),
1531                    |label, delta| label.map_element(|label| label.alpha(delta)),
1532                )
1533        });
1534
1535        // Don't render user messages that are just there for returning tool results.
1536        if message.role == Role::User && thread.message_has_tool_results(message_id) {
1537            if let Some(generating_label) = generating_label {
1538                return h_flex()
1539                    .w_full()
1540                    .h_10()
1541                    .py_1p5()
1542                    .pl_4()
1543                    .pb_3()
1544                    .child(generating_label)
1545                    .into_any_element();
1546            }
1547
1548            return Empty.into_any();
1549        }
1550
1551        let allow_editing_message = message.role == Role::User;
1552
1553        let edit_message_editor = self
1554            .editing_message
1555            .as_ref()
1556            .filter(|(id, _)| *id == message_id)
1557            .map(|(_, state)| state.editor.clone());
1558
1559        let colors = cx.theme().colors();
1560        let active_color = colors.element_active;
1561        let editor_bg_color = colors.editor_background;
1562        let bg_user_message_header = editor_bg_color.blend(active_color.opacity(0.25));
1563
1564        let open_as_markdown = IconButton::new(("open-as-markdown", ix), IconName::FileCode)
1565            .shape(ui::IconButtonShape::Square)
1566            .icon_size(IconSize::XSmall)
1567            .icon_color(Color::Ignored)
1568            .tooltip(Tooltip::text("Open Thread as Markdown"))
1569            .on_click(|_, window, cx| {
1570                window.dispatch_action(Box::new(OpenActiveThreadAsMarkdown), cx)
1571            });
1572
1573        // For all items that should be aligned with the Assistant's response.
1574        const RESPONSE_PADDING_X: Pixels = px(18.);
1575
1576        let feedback_container = h_flex()
1577            .py_2()
1578            .px(RESPONSE_PADDING_X)
1579            .gap_1()
1580            .justify_between();
1581        let feedback_items = match self.thread.read(cx).message_feedback(message_id) {
1582            Some(feedback) => feedback_container
1583                .child(
1584                    Label::new(match feedback {
1585                        ThreadFeedback::Positive => "Thanks for your feedback!",
1586                        ThreadFeedback::Negative => {
1587                            "We appreciate your feedback and will use it to improve."
1588                        }
1589                    })
1590                    .color(Color::Muted)
1591                    .size(LabelSize::XSmall),
1592                )
1593                .child(
1594                    h_flex()
1595                        .pr_1()
1596                        .gap_1()
1597                        .child(
1598                            IconButton::new(("feedback-thumbs-up", ix), IconName::ThumbsUp)
1599                                .shape(ui::IconButtonShape::Square)
1600                                .icon_size(IconSize::XSmall)
1601                                .icon_color(match feedback {
1602                                    ThreadFeedback::Positive => Color::Accent,
1603                                    ThreadFeedback::Negative => Color::Ignored,
1604                                })
1605                                .tooltip(Tooltip::text("Helpful Response"))
1606                                .on_click(cx.listener(move |this, _, window, cx| {
1607                                    this.handle_feedback_click(
1608                                        message_id,
1609                                        ThreadFeedback::Positive,
1610                                        window,
1611                                        cx,
1612                                    );
1613                                })),
1614                        )
1615                        .child(
1616                            IconButton::new(("feedback-thumbs-down", ix), IconName::ThumbsDown)
1617                                .shape(ui::IconButtonShape::Square)
1618                                .icon_size(IconSize::XSmall)
1619                                .icon_color(match feedback {
1620                                    ThreadFeedback::Positive => Color::Ignored,
1621                                    ThreadFeedback::Negative => Color::Accent,
1622                                })
1623                                .tooltip(Tooltip::text("Not Helpful"))
1624                                .on_click(cx.listener(move |this, _, window, cx| {
1625                                    this.handle_feedback_click(
1626                                        message_id,
1627                                        ThreadFeedback::Negative,
1628                                        window,
1629                                        cx,
1630                                    );
1631                                })),
1632                        )
1633                        .child(open_as_markdown),
1634                )
1635                .into_any_element(),
1636            None => feedback_container
1637                .child(
1638                    Label::new(
1639                        "Rating the thread sends all of your current conversation to the Zed team.",
1640                    )
1641                    .color(Color::Muted)
1642                    .size(LabelSize::XSmall),
1643                )
1644                .child(
1645                    h_flex()
1646                        .pr_1()
1647                        .gap_1()
1648                        .child(
1649                            IconButton::new(("feedback-thumbs-up", ix), IconName::ThumbsUp)
1650                                .icon_size(IconSize::XSmall)
1651                                .icon_color(Color::Ignored)
1652                                .shape(ui::IconButtonShape::Square)
1653                                .tooltip(Tooltip::text("Helpful Response"))
1654                                .on_click(cx.listener(move |this, _, window, cx| {
1655                                    this.handle_feedback_click(
1656                                        message_id,
1657                                        ThreadFeedback::Positive,
1658                                        window,
1659                                        cx,
1660                                    );
1661                                })),
1662                        )
1663                        .child(
1664                            IconButton::new(("feedback-thumbs-down", ix), IconName::ThumbsDown)
1665                                .icon_size(IconSize::XSmall)
1666                                .icon_color(Color::Ignored)
1667                                .shape(ui::IconButtonShape::Square)
1668                                .tooltip(Tooltip::text("Not Helpful"))
1669                                .on_click(cx.listener(move |this, _, window, cx| {
1670                                    this.handle_feedback_click(
1671                                        message_id,
1672                                        ThreadFeedback::Negative,
1673                                        window,
1674                                        cx,
1675                                    );
1676                                })),
1677                        )
1678                        .child(open_as_markdown),
1679                )
1680                .into_any_element(),
1681        };
1682
1683        let message_is_empty = message.should_display_content();
1684        let has_content = !message_is_empty || !context.is_empty();
1685
1686        let message_content =
1687            has_content.then(|| {
1688                v_flex()
1689                    .gap_1p5()
1690                    .when(!message_is_empty, |parent| {
1691                        parent.child(
1692                            if let Some(edit_message_editor) = edit_message_editor.clone() {
1693                                let settings = ThemeSettings::get_global(cx);
1694                                let font_size = TextSize::Small.rems(cx);
1695                                let line_height = font_size.to_pixels(window.rem_size()) * 1.5;
1696
1697                                let text_style = TextStyle {
1698                                    color: cx.theme().colors().text,
1699                                    font_family: settings.buffer_font.family.clone(),
1700                                    font_fallbacks: settings.buffer_font.fallbacks.clone(),
1701                                    font_features: settings.buffer_font.features.clone(),
1702                                    font_size: font_size.into(),
1703                                    line_height: line_height.into(),
1704                                    ..Default::default()
1705                                };
1706
1707                                div()
1708                                    .key_context("EditMessageEditor")
1709                                    .on_action(cx.listener(Self::cancel_editing_message))
1710                                    .on_action(cx.listener(Self::confirm_editing_message))
1711                                    .min_h_6()
1712                                    .pt_1()
1713                                    .child(EditorElement::new(
1714                                        &edit_message_editor,
1715                                        EditorStyle {
1716                                            background: colors.editor_background,
1717                                            local_player: cx.theme().players().local(),
1718                                            text: text_style,
1719                                            syntax: cx.theme().syntax().clone(),
1720                                            ..Default::default()
1721                                        },
1722                                    ))
1723                                    .into_any()
1724                            } else {
1725                                div()
1726                                    .min_h_6()
1727                                    .text_ui(cx)
1728                                    .child(self.render_message_content(
1729                                        message_id,
1730                                        rendered_message,
1731                                        has_tool_uses,
1732                                        workspace.clone(),
1733                                        window,
1734                                        cx,
1735                                    ))
1736                                    .into_any()
1737                            },
1738                        )
1739                    })
1740                    .when(!context.is_empty(), |parent| {
1741                        parent.child(h_flex().flex_wrap().gap_1().children(
1742                            context.into_iter().map(|context| {
1743                                let context_id = context.id();
1744                                ContextPill::added(
1745                                    AddedContext::new(context, cx),
1746                                    false,
1747                                    false,
1748                                    None,
1749                                )
1750                                .on_click(Rc::new(cx.listener({
1751                                    let workspace = workspace.clone();
1752                                    let context_store = context_store.clone();
1753                                    move |_, _, window, cx| {
1754                                        if let Some(workspace) = workspace.upgrade() {
1755                                            open_context(
1756                                                context_id,
1757                                                context_store.clone(),
1758                                                workspace,
1759                                                window,
1760                                                cx,
1761                                            );
1762                                            cx.notify();
1763                                        }
1764                                    }
1765                                })))
1766                            }),
1767                        ))
1768                    })
1769            });
1770
1771        let styled_message = match message.role {
1772            Role::User => v_flex()
1773                .id(("message-container", ix))
1774                .map(|this| {
1775                    if is_first_message {
1776                        this.pt_2()
1777                    } else {
1778                        this.pt_4()
1779                    }
1780                })
1781                .pl_2()
1782                .pr_2p5()
1783                .pb_4()
1784                .child(
1785                    v_flex()
1786                        .bg(colors.editor_background)
1787                        .rounded_lg()
1788                        .border_1()
1789                        .border_color(colors.border)
1790                        .shadow_md()
1791                        .child(
1792                            h_flex()
1793                                .py_1()
1794                                .pl_2()
1795                                .pr_1()
1796                                .bg(bg_user_message_header)
1797                                .border_b_1()
1798                                .border_color(colors.border)
1799                                .justify_between()
1800                                .rounded_t_md()
1801                                .child(
1802                                    h_flex()
1803                                        .gap_1p5()
1804                                        .child(
1805                                            Icon::new(IconName::PersonCircle)
1806                                                .size(IconSize::XSmall)
1807                                                .color(Color::Muted),
1808                                        )
1809                                        .child(
1810                                            Label::new("You")
1811                                                .size(LabelSize::Small)
1812                                                .color(Color::Muted),
1813                                        ),
1814                                )
1815                                .child(
1816                                    h_flex()
1817                                        .gap_1()
1818                                        .when_some(
1819                                            edit_message_editor.clone(),
1820                                            |this, edit_message_editor| {
1821                                                let focus_handle =
1822                                                    edit_message_editor.focus_handle(cx);
1823                                                this.child(
1824                                                    Button::new("cancel-edit-message", "Cancel")
1825                                                        .label_size(LabelSize::Small)
1826                                                        .key_binding(
1827                                                            KeyBinding::for_action_in(
1828                                                                &menu::Cancel,
1829                                                                &focus_handle,
1830                                                                window,
1831                                                                cx,
1832                                                            )
1833                                                            .map(|kb| kb.size(rems_from_px(12.))),
1834                                                        )
1835                                                        .on_click(
1836                                                            cx.listener(Self::handle_cancel_click),
1837                                                        ),
1838                                                )
1839                                                .child(
1840                                                    Button::new(
1841                                                        "confirm-edit-message",
1842                                                        "Regenerate",
1843                                                    )
1844                                                    .disabled(
1845                                                        edit_message_editor.read(cx).is_empty(cx),
1846                                                    )
1847                                                    .label_size(LabelSize::Small)
1848                                                    .key_binding(
1849                                                        KeyBinding::for_action_in(
1850                                                            &menu::Confirm,
1851                                                            &focus_handle,
1852                                                            window,
1853                                                            cx,
1854                                                        )
1855                                                        .map(|kb| kb.size(rems_from_px(12.))),
1856                                                    )
1857                                                    .on_click(
1858                                                        cx.listener(Self::handle_regenerate_click),
1859                                                    ),
1860                                                )
1861                                            },
1862                                        )
1863                                        .when(
1864                                            edit_message_editor.is_none() && allow_editing_message,
1865                                            |this| {
1866                                                this.child(
1867                                                    Button::new("edit-message", "Edit")
1868                                                        .label_size(LabelSize::Small)
1869                                                        .on_click(cx.listener({
1870                                                            let message_segments =
1871                                                                message.segments.clone();
1872                                                            move |this, _, window, cx| {
1873                                                                this.start_editing_message(
1874                                                                    message_id,
1875                                                                    &message_segments,
1876                                                                    window,
1877                                                                    cx,
1878                                                                );
1879                                                            }
1880                                                        })),
1881                                                )
1882                                            },
1883                                        ),
1884                                ),
1885                        )
1886                        .child(div().p_2().children(message_content)),
1887                ),
1888            Role::Assistant => v_flex()
1889                .id(("message-container", ix))
1890                .px(RESPONSE_PADDING_X)
1891                .gap_2()
1892                .children(message_content)
1893                .when(has_tool_uses, |parent| {
1894                    parent.children(
1895                        tool_uses
1896                            .into_iter()
1897                            .map(|tool_use| self.render_tool_use(tool_use, window, cx)),
1898                    )
1899                }),
1900            Role::System => div().id(("message-container", ix)).py_1().px_2().child(
1901                v_flex()
1902                    .bg(colors.editor_background)
1903                    .rounded_sm()
1904                    .child(div().p_4().children(message_content)),
1905            ),
1906        };
1907
1908        let after_editing_message = self
1909            .editing_message
1910            .as_ref()
1911            .map_or(false, |(editing_message_id, _)| {
1912                message_id > *editing_message_id
1913            });
1914
1915        let panel_background = cx.theme().colors().panel_background;
1916
1917        v_flex()
1918            .w_full()
1919            .when_some(checkpoint, |parent, checkpoint| {
1920                let mut is_pending = false;
1921                let mut error = None;
1922                if let Some(last_restore_checkpoint) =
1923                    self.thread.read(cx).last_restore_checkpoint()
1924                {
1925                    if last_restore_checkpoint.message_id() == message_id {
1926                        match last_restore_checkpoint {
1927                            LastRestoreCheckpoint::Pending { .. } => is_pending = true,
1928                            LastRestoreCheckpoint::Error { error: err, .. } => {
1929                                error = Some(err.clone());
1930                            }
1931                        }
1932                    }
1933                }
1934
1935                let restore_checkpoint_button =
1936                    Button::new(("restore-checkpoint", ix), "Restore Checkpoint")
1937                        .icon(if error.is_some() {
1938                            IconName::XCircle
1939                        } else {
1940                            IconName::Undo
1941                        })
1942                        .icon_size(IconSize::XSmall)
1943                        .icon_position(IconPosition::Start)
1944                        .icon_color(if error.is_some() {
1945                            Some(Color::Error)
1946                        } else {
1947                            None
1948                        })
1949                        .label_size(LabelSize::XSmall)
1950                        .disabled(is_pending)
1951                        .on_click(cx.listener(move |this, _, _window, cx| {
1952                            this.thread.update(cx, |thread, cx| {
1953                                thread
1954                                    .restore_checkpoint(checkpoint.clone(), cx)
1955                                    .detach_and_log_err(cx);
1956                            });
1957                        }));
1958
1959                let restore_checkpoint_button = if is_pending {
1960                    restore_checkpoint_button
1961                        .with_animation(
1962                            ("pulsating-restore-checkpoint-button", ix),
1963                            Animation::new(Duration::from_secs(2))
1964                                .repeat()
1965                                .with_easing(pulsating_between(0.6, 1.)),
1966                            |label, delta| label.alpha(delta),
1967                        )
1968                        .into_any_element()
1969                } else if let Some(error) = error {
1970                    restore_checkpoint_button
1971                        .tooltip(Tooltip::text(error.to_string()))
1972                        .into_any_element()
1973                } else {
1974                    restore_checkpoint_button.into_any_element()
1975                };
1976
1977                parent.child(
1978                    h_flex()
1979                        .pt_2p5()
1980                        .px_2p5()
1981                        .w_full()
1982                        .gap_1()
1983                        .child(ui::Divider::horizontal())
1984                        .child(restore_checkpoint_button)
1985                        .child(ui::Divider::horizontal()),
1986                )
1987            })
1988            .when(is_first_message, |parent| {
1989                parent.child(self.render_rules_item(cx))
1990            })
1991            .child(styled_message)
1992            .when(!needs_confirmation && generating_label.is_some(), |this| {
1993                this.child(
1994                    h_flex()
1995                        .h_8()
1996                        .mt_2()
1997                        .mb_4()
1998                        .ml_4()
1999                        .py_1p5()
2000                        .child(generating_label.unwrap()),
2001                )
2002            })
2003            .when(show_feedback, move |parent| {
2004                parent.child(feedback_items).when_some(
2005                    self.open_feedback_editors.get(&message_id),
2006                    move |parent, feedback_editor| {
2007                        let focus_handle = feedback_editor.focus_handle(cx);
2008                        parent.child(
2009                            v_flex()
2010                                .key_context("AgentFeedbackMessageEditor")
2011                                .on_action(cx.listener(move |this, _: &menu::Cancel, _, cx| {
2012                                    this.open_feedback_editors.remove(&message_id);
2013                                    cx.notify();
2014                                }))
2015                                .on_action(cx.listener(move |this, _: &menu::Confirm, _, cx| {
2016                                    this.submit_feedback_message(message_id, cx);
2017                                    cx.notify();
2018                                }))
2019                                .on_action(cx.listener(Self::confirm_editing_message))
2020                                .mb_2()
2021                                .mx_4()
2022                                .p_2()
2023                                .rounded_md()
2024                                .border_1()
2025                                .border_color(cx.theme().colors().border)
2026                                .bg(cx.theme().colors().editor_background)
2027                                .child(feedback_editor.clone())
2028                                .child(
2029                                    h_flex()
2030                                        .gap_1()
2031                                        .justify_end()
2032                                        .child(
2033                                            Button::new("dismiss-feedback-message", "Cancel")
2034                                                .label_size(LabelSize::Small)
2035                                                .key_binding(
2036                                                    KeyBinding::for_action_in(
2037                                                        &menu::Cancel,
2038                                                        &focus_handle,
2039                                                        window,
2040                                                        cx,
2041                                                    )
2042                                                    .map(|kb| kb.size(rems_from_px(10.))),
2043                                                )
2044                                                .on_click(cx.listener(
2045                                                    move |this, _, _window, cx| {
2046                                                        this.open_feedback_editors
2047                                                            .remove(&message_id);
2048                                                        cx.notify();
2049                                                    },
2050                                                )),
2051                                        )
2052                                        .child(
2053                                            Button::new(
2054                                                "submit-feedback-message",
2055                                                "Share Feedback",
2056                                            )
2057                                            .style(ButtonStyle::Tinted(ui::TintColor::Accent))
2058                                            .label_size(LabelSize::Small)
2059                                            .key_binding(
2060                                                KeyBinding::for_action_in(
2061                                                    &menu::Confirm,
2062                                                    &focus_handle,
2063                                                    window,
2064                                                    cx,
2065                                                )
2066                                                .map(|kb| kb.size(rems_from_px(10.))),
2067                                            )
2068                                            .on_click(
2069                                                cx.listener(move |this, _, _window, cx| {
2070                                                    this.submit_feedback_message(message_id, cx);
2071                                                    cx.notify()
2072                                                }),
2073                                            ),
2074                                        ),
2075                                ),
2076                        )
2077                    },
2078                )
2079            })
2080            .when(after_editing_message, |parent| {
2081                // Backdrop to dim out the whole thread below the editing user message
2082                parent.relative().child(
2083                    div()
2084                        .occlude()
2085                        .absolute()
2086                        .inset_0()
2087                        .size_full()
2088                        .bg(panel_background)
2089                        .opacity(0.8),
2090                )
2091            })
2092            .into_any()
2093    }
2094
2095    fn render_message_content(
2096        &self,
2097        message_id: MessageId,
2098        rendered_message: &RenderedMessage,
2099        has_tool_uses: bool,
2100        workspace: WeakEntity<Workspace>,
2101        window: &Window,
2102        cx: &Context<Self>,
2103    ) -> impl IntoElement {
2104        let is_last_message = self.messages.last() == Some(&message_id);
2105        let is_generating = self.thread.read(cx).is_generating();
2106        let pending_thinking_segment_index = if is_generating && is_last_message && !has_tool_uses {
2107            rendered_message
2108                .segments
2109                .iter()
2110                .enumerate()
2111                .next_back()
2112                .filter(|(_, segment)| matches!(segment, RenderedMessageSegment::Thinking { .. }))
2113                .map(|(index, _)| index)
2114        } else {
2115            None
2116        };
2117
2118        let message_role = self
2119            .thread
2120            .read(cx)
2121            .message(message_id)
2122            .map(|m| m.role)
2123            .unwrap_or(Role::User);
2124
2125        let is_assistant = message_role == Role::Assistant;
2126
2127        v_flex()
2128            .text_ui(cx)
2129            .gap_2()
2130            .children(
2131                rendered_message.segments.iter().enumerate().map(
2132                    |(index, segment)| match segment {
2133                        RenderedMessageSegment::Thinking {
2134                            content,
2135                            scroll_handle,
2136                        } => self
2137                            .render_message_thinking_segment(
2138                                message_id,
2139                                index,
2140                                content.clone(),
2141                                &scroll_handle,
2142                                Some(index) == pending_thinking_segment_index,
2143                                window,
2144                                cx,
2145                            )
2146                            .into_any_element(),
2147                        RenderedMessageSegment::Text(markdown) => {
2148                            let markdown_element = MarkdownElement::new(
2149                                markdown.clone(),
2150                                default_markdown_style(window, cx),
2151                            );
2152
2153                            let markdown_element = if is_assistant {
2154                                markdown_element.code_block_renderer(
2155                                    markdown::CodeBlockRenderer::Custom {
2156                                        render: Arc::new({
2157                                            let workspace = workspace.clone();
2158                                            let active_thread = cx.entity();
2159                                            move |kind,
2160                                                  parsed_markdown,
2161                                                  range,
2162                                                  metadata,
2163                                                  window,
2164                                                  cx| {
2165                                                render_markdown_code_block(
2166                                                    message_id,
2167                                                    range.start,
2168                                                    kind,
2169                                                    parsed_markdown,
2170                                                    metadata,
2171                                                    active_thread.clone(),
2172                                                    workspace.clone(),
2173                                                    window,
2174                                                    cx,
2175                                                )
2176                                            }
2177                                        }),
2178                                        transform: Some(Arc::new({
2179                                            let active_thread = cx.entity();
2180                                            move |el, range, metadata, _, cx| {
2181                                                let is_expanded = active_thread
2182                                                    .read(cx)
2183                                                    .expanded_code_blocks
2184                                                    .get(&(message_id, range.start))
2185                                                    .copied()
2186                                                    .unwrap_or(false);
2187
2188                                                if is_expanded
2189                                                    || metadata.line_count
2190                                                        <= MAX_UNCOLLAPSED_LINES_IN_CODE_BLOCK
2191                                                {
2192                                                    return el;
2193                                                }
2194                                                el.child(
2195                                                    div()
2196                                                        .absolute()
2197                                                        .bottom_0()
2198                                                        .left_0()
2199                                                        .w_full()
2200                                                        .h_1_4()
2201                                                        .rounded_b_lg()
2202                                                        .bg(gpui::linear_gradient(
2203                                                            0.,
2204                                                            gpui::linear_color_stop(
2205                                                                cx.theme()
2206                                                                    .colors()
2207                                                                    .editor_background,
2208                                                                0.,
2209                                                            ),
2210                                                            gpui::linear_color_stop(
2211                                                                cx.theme()
2212                                                                    .colors()
2213                                                                    .editor_background
2214                                                                    .opacity(0.),
2215                                                                1.,
2216                                                            ),
2217                                                        )),
2218                                                )
2219                                            }
2220                                        })),
2221                                    },
2222                                )
2223                            } else {
2224                                markdown_element.code_block_renderer(
2225                                    markdown::CodeBlockRenderer::Default {
2226                                        copy_button: false,
2227                                        border: true,
2228                                    },
2229                                )
2230                            };
2231
2232                            div()
2233                                .child(markdown_element.on_url_click({
2234                                    let workspace = self.workspace.clone();
2235                                    move |text, window, cx| {
2236                                        open_markdown_link(text, workspace.clone(), window, cx);
2237                                    }
2238                                }))
2239                                .into_any_element()
2240                        }
2241                    },
2242                ),
2243            )
2244    }
2245
2246    fn tool_card_border_color(&self, cx: &Context<Self>) -> Hsla {
2247        cx.theme().colors().border.opacity(0.5)
2248    }
2249
2250    fn tool_card_header_bg(&self, cx: &Context<Self>) -> Hsla {
2251        cx.theme()
2252            .colors()
2253            .element_background
2254            .blend(cx.theme().colors().editor_foreground.opacity(0.025))
2255    }
2256
2257    fn render_message_thinking_segment(
2258        &self,
2259        message_id: MessageId,
2260        ix: usize,
2261        markdown: Entity<Markdown>,
2262        scroll_handle: &ScrollHandle,
2263        pending: bool,
2264        window: &Window,
2265        cx: &Context<Self>,
2266    ) -> impl IntoElement {
2267        let is_open = self
2268            .expanded_thinking_segments
2269            .get(&(message_id, ix))
2270            .copied()
2271            .unwrap_or_default();
2272
2273        let editor_bg = cx.theme().colors().panel_background;
2274
2275        div().map(|this| {
2276            if pending {
2277                this.v_flex()
2278                    .mt_neg_2()
2279                    .mb_1p5()
2280                    .child(
2281                        h_flex()
2282                            .group("disclosure-header")
2283                            .justify_between()
2284                            .child(
2285                                h_flex()
2286                                    .gap_1p5()
2287                                    .child(
2288                                        Icon::new(IconName::LightBulb)
2289                                            .size(IconSize::XSmall)
2290                                            .color(Color::Muted),
2291                                    )
2292                                    .child({
2293                                        Label::new("Thinking")
2294                                            .color(Color::Muted)
2295                                            .size(LabelSize::Small)
2296                                            .with_animation(
2297                                                "generating-label",
2298                                                Animation::new(Duration::from_secs(1)).repeat(),
2299                                                |mut label, delta| {
2300                                                    let text = match delta {
2301                                                        d if d < 0.25 => "Thinking",
2302                                                        d if d < 0.5 => "Thinking.",
2303                                                        d if d < 0.75 => "Thinking..",
2304                                                        _ => "Thinking...",
2305                                                    };
2306                                                    label.set_text(text);
2307                                                    label
2308                                                },
2309                                            )
2310                                            .with_animation(
2311                                                "pulsating-label",
2312                                                Animation::new(Duration::from_secs(2))
2313                                                    .repeat()
2314                                                    .with_easing(pulsating_between(0.6, 1.)),
2315                                                |label, delta| {
2316                                                    label.map_element(|label| label.alpha(delta))
2317                                                },
2318                                            )
2319                                    }),
2320                            )
2321                            .child(
2322                                h_flex()
2323                                    .gap_1()
2324                                    .child(
2325                                        div().visible_on_hover("disclosure-header").child(
2326                                            Disclosure::new("thinking-disclosure", is_open)
2327                                                .opened_icon(IconName::ChevronUp)
2328                                                .closed_icon(IconName::ChevronDown)
2329                                                .on_click(cx.listener({
2330                                                    move |this, _event, _window, _cx| {
2331                                                        let is_open = this
2332                                                            .expanded_thinking_segments
2333                                                            .entry((message_id, ix))
2334                                                            .or_insert(false);
2335
2336                                                        *is_open = !*is_open;
2337                                                    }
2338                                                })),
2339                                        ),
2340                                    )
2341                                    .child({
2342                                        Icon::new(IconName::ArrowCircle)
2343                                            .color(Color::Accent)
2344                                            .size(IconSize::Small)
2345                                            .with_animation(
2346                                                "arrow-circle",
2347                                                Animation::new(Duration::from_secs(2)).repeat(),
2348                                                |icon, delta| {
2349                                                    icon.transform(Transformation::rotate(
2350                                                        percentage(delta),
2351                                                    ))
2352                                                },
2353                                            )
2354                                    }),
2355                            ),
2356                    )
2357                    .when(!is_open, |this| {
2358                        let gradient_overlay = div()
2359                            .rounded_b_lg()
2360                            .h_full()
2361                            .absolute()
2362                            .w_full()
2363                            .bottom_0()
2364                            .left_0()
2365                            .bg(linear_gradient(
2366                                180.,
2367                                linear_color_stop(editor_bg, 1.),
2368                                linear_color_stop(editor_bg.opacity(0.2), 0.),
2369                            ));
2370
2371                        this.child(
2372                            div()
2373                                .relative()
2374                                .bg(editor_bg)
2375                                .rounded_b_lg()
2376                                .mt_2()
2377                                .pl_4()
2378                                .child(
2379                                    div()
2380                                        .id(("thinking-content", ix))
2381                                        .max_h_20()
2382                                        .track_scroll(scroll_handle)
2383                                        .text_ui_sm(cx)
2384                                        .overflow_hidden()
2385                                        .child(
2386                                            MarkdownElement::new(
2387                                                markdown.clone(),
2388                                                default_markdown_style(window, cx),
2389                                            )
2390                                            .on_url_click({
2391                                                let workspace = self.workspace.clone();
2392                                                move |text, window, cx| {
2393                                                    open_markdown_link(
2394                                                        text,
2395                                                        workspace.clone(),
2396                                                        window,
2397                                                        cx,
2398                                                    );
2399                                                }
2400                                            }),
2401                                        ),
2402                                )
2403                                .child(gradient_overlay),
2404                        )
2405                    })
2406                    .when(is_open, |this| {
2407                        this.child(
2408                            div()
2409                                .id(("thinking-content", ix))
2410                                .h_full()
2411                                .bg(editor_bg)
2412                                .text_ui_sm(cx)
2413                                .child(
2414                                    MarkdownElement::new(
2415                                        markdown.clone(),
2416                                        default_markdown_style(window, cx),
2417                                    )
2418                                    .on_url_click({
2419                                        let workspace = self.workspace.clone();
2420                                        move |text, window, cx| {
2421                                            open_markdown_link(text, workspace.clone(), window, cx);
2422                                        }
2423                                    }),
2424                                ),
2425                        )
2426                    })
2427            } else {
2428                this.v_flex()
2429                    .mt_neg_2()
2430                    .child(
2431                        h_flex()
2432                            .group("disclosure-header")
2433                            .pr_1()
2434                            .justify_between()
2435                            .opacity(0.8)
2436                            .hover(|style| style.opacity(1.))
2437                            .child(
2438                                h_flex()
2439                                    .gap_1p5()
2440                                    .child(
2441                                        Icon::new(IconName::LightBulb)
2442                                            .size(IconSize::XSmall)
2443                                            .color(Color::Muted),
2444                                    )
2445                                    .child(Label::new("Thought Process").size(LabelSize::Small)),
2446                            )
2447                            .child(
2448                                div().visible_on_hover("disclosure-header").child(
2449                                    Disclosure::new("thinking-disclosure", is_open)
2450                                        .opened_icon(IconName::ChevronUp)
2451                                        .closed_icon(IconName::ChevronDown)
2452                                        .on_click(cx.listener({
2453                                            move |this, _event, _window, _cx| {
2454                                                let is_open = this
2455                                                    .expanded_thinking_segments
2456                                                    .entry((message_id, ix))
2457                                                    .or_insert(false);
2458
2459                                                *is_open = !*is_open;
2460                                            }
2461                                        })),
2462                                ),
2463                            ),
2464                    )
2465                    .child(
2466                        div()
2467                            .id(("thinking-content", ix))
2468                            .relative()
2469                            .mt_1p5()
2470                            .ml_1p5()
2471                            .pl_2p5()
2472                            .border_l_1()
2473                            .border_color(cx.theme().colors().border_variant)
2474                            .text_ui_sm(cx)
2475                            .when(is_open, |this| {
2476                                this.child(
2477                                    MarkdownElement::new(
2478                                        markdown.clone(),
2479                                        default_markdown_style(window, cx),
2480                                    )
2481                                    .on_url_click({
2482                                        let workspace = self.workspace.clone();
2483                                        move |text, window, cx| {
2484                                            open_markdown_link(text, workspace.clone(), window, cx);
2485                                        }
2486                                    }),
2487                                )
2488                            }),
2489                    )
2490            }
2491        })
2492    }
2493
2494    fn render_tool_use(
2495        &self,
2496        tool_use: ToolUse,
2497        window: &mut Window,
2498        cx: &mut Context<Self>,
2499    ) -> impl IntoElement + use<> {
2500        if let Some(card) = self.thread.read(cx).card_for_tool(&tool_use.id) {
2501            return card.render(&tool_use.status, window, cx);
2502        }
2503
2504        let is_open = self
2505            .expanded_tool_uses
2506            .get(&tool_use.id)
2507            .copied()
2508            .unwrap_or_default();
2509
2510        let is_status_finished = matches!(&tool_use.status, ToolUseStatus::Finished(_));
2511
2512        let fs = self
2513            .workspace
2514            .upgrade()
2515            .map(|workspace| workspace.read(cx).app_state().fs.clone());
2516        let needs_confirmation = matches!(&tool_use.status, ToolUseStatus::NeedsConfirmation);
2517        let edit_tools = tool_use.needs_confirmation;
2518
2519        let status_icons = div().child(match &tool_use.status {
2520            ToolUseStatus::NeedsConfirmation => {
2521                let icon = Icon::new(IconName::Warning)
2522                    .color(Color::Warning)
2523                    .size(IconSize::Small);
2524                icon.into_any_element()
2525            }
2526            ToolUseStatus::Pending
2527            | ToolUseStatus::InputStillStreaming
2528            | ToolUseStatus::Running => {
2529                let icon = Icon::new(IconName::ArrowCircle)
2530                    .color(Color::Accent)
2531                    .size(IconSize::Small);
2532                icon.with_animation(
2533                    "arrow-circle",
2534                    Animation::new(Duration::from_secs(2)).repeat(),
2535                    |icon, delta| icon.transform(Transformation::rotate(percentage(delta))),
2536                )
2537                .into_any_element()
2538            }
2539            ToolUseStatus::Finished(_) => div().w_0().into_any_element(),
2540            ToolUseStatus::Error(_) => {
2541                let icon = Icon::new(IconName::Close)
2542                    .color(Color::Error)
2543                    .size(IconSize::Small);
2544                icon.into_any_element()
2545            }
2546        });
2547
2548        let rendered_tool_use = self.rendered_tool_uses.get(&tool_use.id).cloned();
2549        let results_content_container = || v_flex().p_2().gap_0p5();
2550
2551        let results_content = v_flex()
2552            .gap_1()
2553            .child(
2554                results_content_container()
2555                    .child(
2556                        Label::new("Input")
2557                            .size(LabelSize::XSmall)
2558                            .color(Color::Muted)
2559                            .buffer_font(cx),
2560                    )
2561                    .child(
2562                        div()
2563                            .w_full()
2564                            .text_ui_sm(cx)
2565                            .children(rendered_tool_use.as_ref().map(|rendered| {
2566                                MarkdownElement::new(
2567                                    rendered.input.clone(),
2568                                    tool_use_markdown_style(window, cx),
2569                                )
2570                                .code_block_renderer(markdown::CodeBlockRenderer::Default {
2571                                    copy_button: false,
2572                                    border: false,
2573                                })
2574                                .on_url_click({
2575                                    let workspace = self.workspace.clone();
2576                                    move |text, window, cx| {
2577                                        open_markdown_link(text, workspace.clone(), window, cx);
2578                                    }
2579                                })
2580                            })),
2581                    ),
2582            )
2583            .map(|container| match tool_use.status {
2584                ToolUseStatus::Finished(_) => container.child(
2585                    results_content_container()
2586                        .border_t_1()
2587                        .border_color(self.tool_card_border_color(cx))
2588                        .child(
2589                            Label::new("Result")
2590                                .size(LabelSize::XSmall)
2591                                .color(Color::Muted)
2592                                .buffer_font(cx),
2593                        )
2594                        .child(div().w_full().text_ui_sm(cx).children(
2595                            rendered_tool_use.as_ref().map(|rendered| {
2596                                MarkdownElement::new(
2597                                    rendered.output.clone(),
2598                                    tool_use_markdown_style(window, cx),
2599                                )
2600                                .code_block_renderer(markdown::CodeBlockRenderer::Default {
2601                                    copy_button: false,
2602                                    border: false,
2603                                })
2604                                .on_url_click({
2605                                    let workspace = self.workspace.clone();
2606                                    move |text, window, cx| {
2607                                        open_markdown_link(text, workspace.clone(), window, cx);
2608                                    }
2609                                })
2610                                .into_any_element()
2611                            }),
2612                        )),
2613                ),
2614                ToolUseStatus::InputStillStreaming | ToolUseStatus::Running => container.child(
2615                    results_content_container().child(
2616                        h_flex()
2617                            .gap_1()
2618                            .pb_1()
2619                            .border_t_1()
2620                            .border_color(self.tool_card_border_color(cx))
2621                            .child(
2622                                Icon::new(IconName::ArrowCircle)
2623                                    .size(IconSize::Small)
2624                                    .color(Color::Accent)
2625                                    .with_animation(
2626                                        "arrow-circle",
2627                                        Animation::new(Duration::from_secs(2)).repeat(),
2628                                        |icon, delta| {
2629                                            icon.transform(Transformation::rotate(percentage(
2630                                                delta,
2631                                            )))
2632                                        },
2633                                    ),
2634                            )
2635                            .child(
2636                                Label::new("Running…")
2637                                    .size(LabelSize::XSmall)
2638                                    .color(Color::Muted)
2639                                    .buffer_font(cx),
2640                            ),
2641                    ),
2642                ),
2643                ToolUseStatus::Error(_) => container.child(
2644                    results_content_container()
2645                        .border_t_1()
2646                        .border_color(self.tool_card_border_color(cx))
2647                        .child(
2648                            Label::new("Error")
2649                                .size(LabelSize::XSmall)
2650                                .color(Color::Muted)
2651                                .buffer_font(cx),
2652                        )
2653                        .child(
2654                            div()
2655                                .text_ui_sm(cx)
2656                                .children(rendered_tool_use.as_ref().map(|rendered| {
2657                                    MarkdownElement::new(
2658                                        rendered.output.clone(),
2659                                        tool_use_markdown_style(window, cx),
2660                                    )
2661                                    .on_url_click({
2662                                        let workspace = self.workspace.clone();
2663                                        move |text, window, cx| {
2664                                            open_markdown_link(text, workspace.clone(), window, cx);
2665                                        }
2666                                    })
2667                                    .into_any_element()
2668                                })),
2669                        ),
2670                ),
2671                ToolUseStatus::Pending => container,
2672                ToolUseStatus::NeedsConfirmation => container.child(
2673                    results_content_container()
2674                        .border_t_1()
2675                        .border_color(self.tool_card_border_color(cx))
2676                        .child(
2677                            Label::new("Asking Permission")
2678                                .size(LabelSize::Small)
2679                                .color(Color::Muted)
2680                                .buffer_font(cx),
2681                        ),
2682                ),
2683            });
2684
2685        let gradient_overlay = |color: Hsla| {
2686            div()
2687                .h_full()
2688                .absolute()
2689                .w_12()
2690                .bottom_0()
2691                .map(|element| {
2692                    if is_status_finished {
2693                        element.right_6()
2694                    } else {
2695                        element.right(px(44.))
2696                    }
2697                })
2698                .bg(linear_gradient(
2699                    90.,
2700                    linear_color_stop(color, 1.),
2701                    linear_color_stop(color.opacity(0.2), 0.),
2702                ))
2703        };
2704
2705        v_flex().gap_1().mb_3().map(|element| {
2706            if !edit_tools {
2707                element.child(
2708                    v_flex()
2709                        .child(
2710                            h_flex()
2711                                .group("disclosure-header")
2712                                .relative()
2713                                .gap_1p5()
2714                                .justify_between()
2715                                .opacity(0.8)
2716                                .hover(|style| style.opacity(1.))
2717                                .when(!is_status_finished, |this| this.pr_2())
2718                                .child(
2719                                    h_flex()
2720                                        .id("tool-label-container")
2721                                        .gap_1p5()
2722                                        .max_w_full()
2723                                        .overflow_x_scroll()
2724                                        .child(
2725                                            Icon::new(tool_use.icon)
2726                                                .size(IconSize::XSmall)
2727                                                .color(Color::Muted),
2728                                        )
2729                                        .child(
2730                                            h_flex().pr_8().text_size(rems(0.8125)).children(
2731                                                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| {
2732                                                    open_markdown_link(text, workspace.clone(), window, cx);
2733                                                }}))
2734                                            ),
2735                                        ),
2736                                )
2737                                .child(
2738                                    h_flex()
2739                                        .gap_1()
2740                                        .child(
2741                                            div().visible_on_hover("disclosure-header").child(
2742                                                Disclosure::new("tool-use-disclosure", is_open)
2743                                                    .opened_icon(IconName::ChevronUp)
2744                                                    .closed_icon(IconName::ChevronDown)
2745                                                    .on_click(cx.listener({
2746                                                        let tool_use_id = tool_use.id.clone();
2747                                                        move |this, _event, _window, _cx| {
2748                                                            let is_open = this
2749                                                                .expanded_tool_uses
2750                                                                .entry(tool_use_id.clone())
2751                                                                .or_insert(false);
2752
2753                                                            *is_open = !*is_open;
2754                                                        }
2755                                                    })),
2756                                            ),
2757                                        )
2758                                        .child(status_icons),
2759                                )
2760                                .child(gradient_overlay(cx.theme().colors().panel_background)),
2761                        )
2762                        .map(|parent| {
2763                            if !is_open {
2764                                return parent;
2765                            }
2766
2767                            parent.child(
2768                                v_flex()
2769                                    .mt_1()
2770                                    .border_1()
2771                                    .border_color(self.tool_card_border_color(cx))
2772                                    .bg(cx.theme().colors().editor_background)
2773                                    .rounded_lg()
2774                                    .child(results_content),
2775                            )
2776                        }),
2777                )
2778            } else {
2779                v_flex()
2780                    .mb_2()
2781                    .rounded_lg()
2782                    .border_1()
2783                    .border_color(self.tool_card_border_color(cx))
2784                    .overflow_hidden()
2785                    .child(
2786                        h_flex()
2787                            .group("disclosure-header")
2788                            .relative()
2789                            .justify_between()
2790                            .py_1()
2791                            .map(|element| {
2792                                if is_status_finished {
2793                                    element.pl_2().pr_0p5()
2794                                } else {
2795                                    element.px_2()
2796                                }
2797                            })
2798                            .bg(self.tool_card_header_bg(cx))
2799                            .map(|element| {
2800                                if is_open {
2801                                    element.border_b_1().rounded_t_md()
2802                                } else if needs_confirmation {
2803                                    element.rounded_t_md()
2804                                } else {
2805                                    element.rounded_md()
2806                                }
2807                            })
2808                            .border_color(self.tool_card_border_color(cx))
2809                            .child(
2810                                h_flex()
2811                                    .id("tool-label-container")
2812                                    .gap_1p5()
2813                                    .max_w_full()
2814                                    .overflow_x_scroll()
2815                                    .child(
2816                                        Icon::new(tool_use.icon)
2817                                            .size(IconSize::XSmall)
2818                                            .color(Color::Muted),
2819                                    )
2820                                    .child(
2821                                        h_flex().pr_8().text_ui_sm(cx).children(
2822                                            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| {
2823                                                open_markdown_link(text, workspace.clone(), window, cx);
2824                                            }}))
2825                                        ),
2826                                    ),
2827                            )
2828                            .child(
2829                                h_flex()
2830                                    .gap_1()
2831                                    .child(
2832                                        div().visible_on_hover("disclosure-header").child(
2833                                            Disclosure::new("tool-use-disclosure", is_open)
2834                                                .opened_icon(IconName::ChevronUp)
2835                                                .closed_icon(IconName::ChevronDown)
2836                                                .on_click(cx.listener({
2837                                                    let tool_use_id = tool_use.id.clone();
2838                                                    move |this, _event, _window, _cx| {
2839                                                        let is_open = this
2840                                                            .expanded_tool_uses
2841                                                            .entry(tool_use_id.clone())
2842                                                            .or_insert(false);
2843
2844                                                        *is_open = !*is_open;
2845                                                    }
2846                                                })),
2847                                        ),
2848                                    )
2849                                    .child(status_icons),
2850                            )
2851                            .child(gradient_overlay(self.tool_card_header_bg(cx))),
2852                    )
2853                    .map(|parent| {
2854                        if !is_open {
2855                            return parent;
2856                        }
2857
2858                        parent.child(
2859                            v_flex()
2860                                .bg(cx.theme().colors().editor_background)
2861                                .map(|element| {
2862                                    if  needs_confirmation {
2863                                        element.rounded_none()
2864                                    } else {
2865                                        element.rounded_b_lg()
2866                                    }
2867                                })
2868                                .child(results_content),
2869                        )
2870                    })
2871                    .when(needs_confirmation, |this| {
2872                        this.child(
2873                            h_flex()
2874                                .py_1()
2875                                .pl_2()
2876                                .pr_1()
2877                                .gap_1()
2878                                .justify_between()
2879                                .bg(cx.theme().colors().editor_background)
2880                                .border_t_1()
2881                                .border_color(self.tool_card_border_color(cx))
2882                                .rounded_b_lg()
2883                                .child(
2884                                    Label::new("Waiting for Confirmation…")
2885                                        .color(Color::Muted)
2886                                        .size(LabelSize::Small)
2887                                        .with_animation(
2888                                            "generating-label",
2889                                            Animation::new(Duration::from_secs(1)).repeat(),
2890                                            |mut label, delta| {
2891                                                let text = match delta {
2892                                                    d if d < 0.25 => "Waiting for Confirmation",
2893                                                    d if d < 0.5 => "Waiting for Confirmation.",
2894                                                    d if d < 0.75 => "Waiting for Confirmation..",
2895                                                    _ => "Waiting for Confirmation...",
2896                                                };
2897                                                label.set_text(text);
2898                                                label
2899                                            },
2900                                        )
2901                                        .with_animation(
2902                                            "pulsating-label",
2903                                            Animation::new(Duration::from_secs(2))
2904                                                .repeat()
2905                                                .with_easing(pulsating_between(0.6, 1.)),
2906                                            |label, delta| label.map_element(|label| label.alpha(delta)),
2907                                        ),
2908                                )
2909                                .child(
2910                                    h_flex()
2911                                        .gap_0p5()
2912                                        .child({
2913                                            let tool_id = tool_use.id.clone();
2914                                            Button::new(
2915                                                "always-allow-tool-action",
2916                                                "Always Allow",
2917                                            )
2918                                            .label_size(LabelSize::Small)
2919                                            .icon(IconName::CheckDouble)
2920                                            .icon_position(IconPosition::Start)
2921                                            .icon_size(IconSize::Small)
2922                                            .icon_color(Color::Success)
2923                                            .tooltip(move |window, cx|  {
2924                                                Tooltip::with_meta(
2925                                                    "Never ask for permission",
2926                                                    None,
2927                                                    "Restore the original behavior in your Agent Panel settings",
2928                                                    window,
2929                                                    cx,
2930                                                )
2931                                            })
2932                                            .on_click(cx.listener(
2933                                                move |this, event, window, cx| {
2934                                                    if let Some(fs) = fs.clone() {
2935                                                        update_settings_file::<AssistantSettings>(
2936                                                            fs.clone(),
2937                                                            cx,
2938                                                            |settings, _| {
2939                                                                settings.set_always_allow_tool_actions(true);
2940                                                            },
2941                                                        );
2942                                                    }
2943                                                    this.handle_allow_tool(
2944                                                        tool_id.clone(),
2945                                                        event,
2946                                                        window,
2947                                                        cx,
2948                                                    )
2949                                                },
2950                                            ))
2951                                        })
2952                                        .child(ui::Divider::vertical())
2953                                        .child({
2954                                            let tool_id = tool_use.id.clone();
2955                                            Button::new("allow-tool-action", "Allow")
2956                                                .label_size(LabelSize::Small)
2957                                                .icon(IconName::Check)
2958                                                .icon_position(IconPosition::Start)
2959                                                .icon_size(IconSize::Small)
2960                                                .icon_color(Color::Success)
2961                                                .on_click(cx.listener(
2962                                                    move |this, event, window, cx| {
2963                                                        this.handle_allow_tool(
2964                                                            tool_id.clone(),
2965                                                            event,
2966                                                            window,
2967                                                            cx,
2968                                                        )
2969                                                    },
2970                                                ))
2971                                        })
2972                                        .child({
2973                                            let tool_id = tool_use.id.clone();
2974                                            let tool_name: Arc<str> = tool_use.name.into();
2975                                            Button::new("deny-tool", "Deny")
2976                                                .label_size(LabelSize::Small)
2977                                                .icon(IconName::Close)
2978                                                .icon_position(IconPosition::Start)
2979                                                .icon_size(IconSize::Small)
2980                                                .icon_color(Color::Error)
2981                                                .on_click(cx.listener(
2982                                                    move |this, event, window, cx| {
2983                                                        this.handle_deny_tool(
2984                                                            tool_id.clone(),
2985                                                            tool_name.clone(),
2986                                                            event,
2987                                                            window,
2988                                                            cx,
2989                                                        )
2990                                                    },
2991                                                ))
2992                                        }),
2993                                ),
2994                        )
2995                    })
2996            }
2997        }).into_any_element()
2998    }
2999
3000    fn render_rules_item(&self, cx: &Context<Self>) -> AnyElement {
3001        let project_context = self.thread.read(cx).project_context();
3002        let project_context = project_context.borrow();
3003        let Some(project_context) = project_context.as_ref() else {
3004            return div().into_any();
3005        };
3006
3007        let user_rules_text = if project_context.user_rules.is_empty() {
3008            None
3009        } else if project_context.user_rules.len() == 1 {
3010            let user_rules = &project_context.user_rules[0];
3011
3012            match user_rules.title.as_ref() {
3013                Some(title) => Some(format!("Using \"{title}\" user rule")),
3014                None => Some("Using user rule".into()),
3015            }
3016        } else {
3017            Some(format!(
3018                "Using {} user rules",
3019                project_context.user_rules.len()
3020            ))
3021        };
3022
3023        let first_user_rules_id = project_context
3024            .user_rules
3025            .first()
3026            .map(|user_rules| user_rules.uuid.0);
3027
3028        let rules_files = project_context
3029            .worktrees
3030            .iter()
3031            .filter_map(|worktree| worktree.rules_file.as_ref())
3032            .collect::<Vec<_>>();
3033
3034        let rules_file_text = match rules_files.as_slice() {
3035            &[] => None,
3036            &[rules_file] => Some(format!(
3037                "Using project {:?} file",
3038                rules_file.path_in_worktree
3039            )),
3040            rules_files => Some(format!("Using {} project rules files", rules_files.len())),
3041        };
3042
3043        if user_rules_text.is_none() && rules_file_text.is_none() {
3044            return div().into_any();
3045        }
3046
3047        v_flex()
3048            .pt_2()
3049            .px_2p5()
3050            .gap_1()
3051            .when_some(user_rules_text, |parent, user_rules_text| {
3052                parent.child(
3053                    h_flex()
3054                        .w_full()
3055                        .child(
3056                            Icon::new(RULES_ICON)
3057                                .size(IconSize::XSmall)
3058                                .color(Color::Disabled),
3059                        )
3060                        .child(
3061                            Label::new(user_rules_text)
3062                                .size(LabelSize::XSmall)
3063                                .color(Color::Muted)
3064                                .truncate()
3065                                .buffer_font(cx)
3066                                .ml_1p5()
3067                                .mr_0p5(),
3068                        )
3069                        .child(
3070                            IconButton::new("open-prompt-library", IconName::ArrowUpRightAlt)
3071                                .shape(ui::IconButtonShape::Square)
3072                                .icon_size(IconSize::XSmall)
3073                                .icon_color(Color::Ignored)
3074                                // TODO: Figure out a way to pass focus handle here so we can display the `OpenPromptLibrary`  keybinding
3075                                .tooltip(Tooltip::text("View User Rules"))
3076                                .on_click(move |_event, window, cx| {
3077                                    window.dispatch_action(
3078                                        Box::new(OpenPromptLibrary {
3079                                            prompt_to_select: first_user_rules_id,
3080                                        }),
3081                                        cx,
3082                                    )
3083                                }),
3084                        ),
3085                )
3086            })
3087            .when_some(rules_file_text, |parent, rules_file_text| {
3088                parent.child(
3089                    h_flex()
3090                        .w_full()
3091                        .child(
3092                            Icon::new(IconName::File)
3093                                .size(IconSize::XSmall)
3094                                .color(Color::Disabled),
3095                        )
3096                        .child(
3097                            Label::new(rules_file_text)
3098                                .size(LabelSize::XSmall)
3099                                .color(Color::Muted)
3100                                .buffer_font(cx)
3101                                .ml_1p5()
3102                                .mr_0p5(),
3103                        )
3104                        .child(
3105                            IconButton::new("open-rule", IconName::ArrowUpRightAlt)
3106                                .shape(ui::IconButtonShape::Square)
3107                                .icon_size(IconSize::XSmall)
3108                                .icon_color(Color::Ignored)
3109                                .on_click(cx.listener(Self::handle_open_rules))
3110                                .tooltip(Tooltip::text("View Rules")),
3111                        ),
3112                )
3113            })
3114            .into_any()
3115    }
3116
3117    fn handle_allow_tool(
3118        &mut self,
3119        tool_use_id: LanguageModelToolUseId,
3120        _: &ClickEvent,
3121        _window: &mut Window,
3122        cx: &mut Context<Self>,
3123    ) {
3124        if let Some(PendingToolUseStatus::NeedsConfirmation(c)) = self
3125            .thread
3126            .read(cx)
3127            .pending_tool(&tool_use_id)
3128            .map(|tool_use| tool_use.status.clone())
3129        {
3130            self.thread.update(cx, |thread, cx| {
3131                thread.run_tool(
3132                    c.tool_use_id.clone(),
3133                    c.ui_text.clone(),
3134                    c.input.clone(),
3135                    &c.messages,
3136                    c.tool.clone(),
3137                    cx,
3138                );
3139            });
3140        }
3141    }
3142
3143    fn handle_deny_tool(
3144        &mut self,
3145        tool_use_id: LanguageModelToolUseId,
3146        tool_name: Arc<str>,
3147        _: &ClickEvent,
3148        _window: &mut Window,
3149        cx: &mut Context<Self>,
3150    ) {
3151        self.thread.update(cx, |thread, cx| {
3152            thread.deny_tool_use(tool_use_id, tool_name, cx);
3153        });
3154    }
3155
3156    fn handle_open_rules(&mut self, _: &ClickEvent, window: &mut Window, cx: &mut Context<Self>) {
3157        let project_context = self.thread.read(cx).project_context();
3158        let project_context = project_context.borrow();
3159        let Some(project_context) = project_context.as_ref() else {
3160            return;
3161        };
3162
3163        let abs_paths = project_context
3164            .worktrees
3165            .iter()
3166            .flat_map(|worktree| worktree.rules_file.as_ref())
3167            .map(|rules_file| rules_file.abs_path.to_path_buf())
3168            .collect::<Vec<_>>();
3169
3170        if let Ok(task) = self.workspace.update(cx, move |workspace, cx| {
3171            // TODO: Open a multibuffer instead? In some cases this doesn't make the set of rules
3172            // files clear. For example, if rules file 1 is already open but rules file 2 is not,
3173            // this would open and focus rules file 2 in a tab that is not next to rules file 1.
3174            workspace.open_paths(abs_paths, OpenOptions::default(), None, window, cx)
3175        }) {
3176            task.detach();
3177        }
3178    }
3179
3180    fn dismiss_notifications(&mut self, cx: &mut Context<ActiveThread>) {
3181        for window in self.notifications.drain(..) {
3182            window
3183                .update(cx, |_, window, _| {
3184                    window.remove_window();
3185                })
3186                .ok();
3187
3188            self.notification_subscriptions.remove(&window);
3189        }
3190    }
3191
3192    fn render_vertical_scrollbar(&self, cx: &mut Context<Self>) -> Option<Stateful<Div>> {
3193        if !self.show_scrollbar && !self.scrollbar_state.is_dragging() {
3194            return None;
3195        }
3196
3197        Some(
3198            div()
3199                .occlude()
3200                .id("active-thread-scrollbar")
3201                .on_mouse_move(cx.listener(|_, _, _, cx| {
3202                    cx.notify();
3203                    cx.stop_propagation()
3204                }))
3205                .on_hover(|_, _, cx| {
3206                    cx.stop_propagation();
3207                })
3208                .on_any_mouse_down(|_, _, cx| {
3209                    cx.stop_propagation();
3210                })
3211                .on_mouse_up(
3212                    MouseButton::Left,
3213                    cx.listener(|_, _, _, cx| {
3214                        cx.stop_propagation();
3215                    }),
3216                )
3217                .on_scroll_wheel(cx.listener(|_, _, _, cx| {
3218                    cx.notify();
3219                }))
3220                .h_full()
3221                .absolute()
3222                .right_1()
3223                .top_1()
3224                .bottom_0()
3225                .w(px(12.))
3226                .cursor_default()
3227                .children(Scrollbar::vertical(self.scrollbar_state.clone())),
3228        )
3229    }
3230
3231    fn hide_scrollbar_later(&mut self, cx: &mut Context<Self>) {
3232        const SCROLLBAR_SHOW_INTERVAL: Duration = Duration::from_secs(1);
3233        self.hide_scrollbar_task = Some(cx.spawn(async move |thread, cx| {
3234            cx.background_executor()
3235                .timer(SCROLLBAR_SHOW_INTERVAL)
3236                .await;
3237            thread
3238                .update(cx, |thread, cx| {
3239                    if !thread.scrollbar_state.is_dragging() {
3240                        thread.show_scrollbar = false;
3241                        cx.notify();
3242                    }
3243                })
3244                .log_err();
3245        }))
3246    }
3247}
3248
3249pub enum ActiveThreadEvent {
3250    EditingMessageTokenCountChanged,
3251}
3252
3253impl EventEmitter<ActiveThreadEvent> for ActiveThread {}
3254
3255impl Render for ActiveThread {
3256    fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
3257        v_flex()
3258            .size_full()
3259            .relative()
3260            .on_mouse_move(cx.listener(|this, _, _, cx| {
3261                this.show_scrollbar = true;
3262                this.hide_scrollbar_later(cx);
3263                cx.notify();
3264            }))
3265            .on_scroll_wheel(cx.listener(|this, _, _, cx| {
3266                this.show_scrollbar = true;
3267                this.hide_scrollbar_later(cx);
3268                cx.notify();
3269            }))
3270            .on_mouse_up(
3271                MouseButton::Left,
3272                cx.listener(|this, _, _, cx| {
3273                    this.hide_scrollbar_later(cx);
3274                }),
3275            )
3276            .child(list(self.list_state.clone()).flex_grow())
3277            .when_some(self.render_vertical_scrollbar(cx), |this, scrollbar| {
3278                this.child(scrollbar)
3279            })
3280    }
3281}
3282
3283pub(crate) fn open_context(
3284    id: ContextId,
3285    context_store: Entity<ContextStore>,
3286    workspace: Entity<Workspace>,
3287    window: &mut Window,
3288    cx: &mut App,
3289) {
3290    let Some(context) = context_store.read(cx).context_for_id(id) else {
3291        return;
3292    };
3293
3294    match context {
3295        AssistantContext::File(file_context) => {
3296            if let Some(project_path) = file_context.context_buffer.buffer.read(cx).project_path(cx)
3297            {
3298                workspace.update(cx, |workspace, cx| {
3299                    workspace
3300                        .open_path(project_path, None, true, window, cx)
3301                        .detach_and_log_err(cx);
3302                });
3303            }
3304        }
3305        AssistantContext::Directory(directory_context) => {
3306            let entry_id = directory_context.entry_id;
3307            workspace.update(cx, |workspace, cx| {
3308                workspace.project().update(cx, |_project, cx| {
3309                    cx.emit(project::Event::RevealInProjectPanel(entry_id));
3310                })
3311            })
3312        }
3313        AssistantContext::Symbol(symbol_context) => {
3314            if let Some(project_path) = symbol_context
3315                .context_symbol
3316                .buffer
3317                .read(cx)
3318                .project_path(cx)
3319            {
3320                let snapshot = symbol_context.context_symbol.buffer.read(cx).snapshot();
3321                let target_position = symbol_context
3322                    .context_symbol
3323                    .id
3324                    .range
3325                    .start
3326                    .to_point(&snapshot);
3327
3328                open_editor_at_position(project_path, target_position, &workspace, window, cx)
3329                    .detach();
3330            }
3331        }
3332        AssistantContext::Selection(selection_context) => {
3333            if let Some(project_path) = selection_context
3334                .context_buffer
3335                .buffer
3336                .read(cx)
3337                .project_path(cx)
3338            {
3339                let snapshot = selection_context.context_buffer.buffer.read(cx).snapshot();
3340                let target_position = selection_context.range.start.to_point(&snapshot);
3341
3342                open_editor_at_position(project_path, target_position, &workspace, window, cx)
3343                    .detach();
3344            }
3345        }
3346        AssistantContext::FetchedUrl(fetched_url_context) => {
3347            cx.open_url(&fetched_url_context.url);
3348        }
3349        AssistantContext::Thread(thread_context) => {
3350            let thread_id = thread_context.thread.read(cx).id().clone();
3351            workspace.update(cx, |workspace, cx| {
3352                if let Some(panel) = workspace.panel::<AssistantPanel>(cx) {
3353                    panel.update(cx, |panel, cx| {
3354                        panel
3355                            .open_thread(&thread_id, window, cx)
3356                            .detach_and_log_err(cx)
3357                    });
3358                }
3359            })
3360        }
3361        AssistantContext::Rules(rules_context) => window.dispatch_action(
3362            Box::new(OpenPromptLibrary {
3363                prompt_to_select: Some(rules_context.prompt_id.0),
3364            }),
3365            cx,
3366        ),
3367        AssistantContext::Image(_) => {}
3368    }
3369}
3370
3371fn open_editor_at_position(
3372    project_path: project::ProjectPath,
3373    target_position: Point,
3374    workspace: &Entity<Workspace>,
3375    window: &mut Window,
3376    cx: &mut App,
3377) -> Task<()> {
3378    let open_task = workspace.update(cx, |workspace, cx| {
3379        workspace.open_path(project_path, None, true, window, cx)
3380    });
3381    window.spawn(cx, async move |cx| {
3382        if let Some(active_editor) = open_task
3383            .await
3384            .log_err()
3385            .and_then(|item| item.downcast::<Editor>())
3386        {
3387            active_editor
3388                .downgrade()
3389                .update_in(cx, |editor, window, cx| {
3390                    editor.go_to_singleton_buffer_point(target_position, window, cx);
3391                })
3392                .log_err();
3393        }
3394    })
3395}