active_thread.rs

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