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