active_thread.rs

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