active_thread.rs

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