agent_panel.rs

   1use std::{
   2    ops::Range,
   3    path::{Path, PathBuf},
   4    rc::Rc,
   5    sync::{
   6        Arc,
   7        atomic::{AtomicBool, Ordering},
   8    },
   9    time::Duration,
  10};
  11
  12use acp_thread::{AcpThread, MentionUri, ThreadStatus};
  13use agent::{ContextServerRegistry, SharedThread, ThreadStore};
  14use agent_client_protocol as acp;
  15use agent_servers::AgentServer;
  16use collections::HashSet;
  17use db::kvp::{Dismissable, KeyValueStore};
  18use itertools::Itertools;
  19use project::AgentId;
  20use serde::{Deserialize, Serialize};
  21use settings::{LanguageModelProviderSetting, LanguageModelSelection};
  22
  23use feature_flags::{AgentV2FeatureFlag, FeatureFlagAppExt as _};
  24use zed_actions::agent::{
  25    ConflictContent, OpenClaudeAgentOnboardingModal, ReauthenticateAgent,
  26    ResolveConflictedFilesWithAgent, ResolveConflictsWithAgent, ReviewBranchDiff,
  27};
  28
  29use crate::{
  30    AddContextServer, AgentDiffPane, ConversationView, CopyThreadToClipboard, CycleStartThreadIn,
  31    Follow, InlineAssistant, LoadThreadFromClipboard, NewTextThread, NewThread,
  32    OpenActiveThreadAsMarkdown, OpenAgentDiff, OpenHistory, ResetTrialEndUpsell, ResetTrialUpsell,
  33    StartThreadIn, ToggleNavigationMenu, ToggleNewThreadMenu, ToggleOptionsMenu,
  34    agent_configuration::{AgentConfiguration, AssistantConfigurationEvent},
  35    conversation_view::{AcpThreadViewEvent, ThreadView},
  36    slash_command::SlashCommandCompletionProvider,
  37    text_thread_editor::{AgentPanelDelegate, TextThreadEditor, make_lsp_adapter_delegate},
  38    ui::EndTrialUpsell,
  39};
  40use crate::{
  41    Agent, AgentInitialContent, ExternalSourcePrompt, NewExternalAgentThread,
  42    NewNativeAgentThreadFromSummary,
  43};
  44use crate::{
  45    DEFAULT_THREAD_TITLE,
  46    ui::{AcpOnboardingModal, ClaudeCodeOnboardingModal, HoldForDefault},
  47};
  48use crate::{
  49    ExpandMessageEditor, ThreadHistoryView,
  50    text_thread_history::{TextThreadHistory, TextThreadHistoryEvent},
  51};
  52use crate::{ManageProfiles, ThreadHistoryViewEvent};
  53use crate::{ThreadHistory, agent_connection_store::AgentConnectionStore};
  54use agent_settings::AgentSettings;
  55use ai_onboarding::AgentPanelOnboarding;
  56use anyhow::{Context as _, Result, anyhow};
  57use assistant_slash_command::SlashCommandWorkingSet;
  58use assistant_text_thread::{TextThread, TextThreadEvent, TextThreadSummary};
  59use client::UserStore;
  60use cloud_api_types::Plan;
  61use collections::HashMap;
  62use editor::{Anchor, AnchorRangeExt as _, Editor, EditorEvent, MultiBuffer};
  63use extension::ExtensionEvents;
  64use extension_host::ExtensionStore;
  65use fs::Fs;
  66use gpui::{
  67    Action, Animation, AnimationExt, AnyElement, App, AsyncWindowContext, ClipboardItem, Corner,
  68    DismissEvent, Entity, EventEmitter, ExternalPaths, FocusHandle, Focusable, KeyContext, Pixels,
  69    Subscription, Task, UpdateGlobal, WeakEntity, prelude::*, pulsating_between,
  70};
  71use language::LanguageRegistry;
  72use language_model::{ConfigurationError, LanguageModelRegistry};
  73use project::project_settings::ProjectSettings;
  74use project::{Project, ProjectPath, Worktree};
  75use prompt_store::{PromptBuilder, PromptStore, UserPromptId};
  76use rules_library::{RulesLibrary, open_rules_library};
  77use search::{BufferSearchBar, buffer_search};
  78use settings::{Settings, update_settings_file};
  79use theme_settings::ThemeSettings;
  80use ui::{
  81    Button, Callout, CommonAnimationExt, ContextMenu, ContextMenuEntry, DocumentationSide,
  82    KeyBinding, PopoverMenu, PopoverMenuHandle, Tab, Tooltip, prelude::*, utils::WithRemSize,
  83};
  84use util::{ResultExt as _, debug_panic};
  85use workspace::{
  86    CollaboratorId, DraggedSelection, DraggedTab, OpenMode, OpenResult, PathList,
  87    SerializedPathList, ToggleWorkspaceSidebar, ToggleZoom, ToolbarItemView, Workspace,
  88    WorkspaceId,
  89    dock::{DockPosition, Panel, PanelEvent},
  90};
  91use zed_actions::{
  92    DecreaseBufferFontSize, IncreaseBufferFontSize, ResetBufferFontSize,
  93    agent::{OpenAcpOnboardingModal, OpenSettings, ResetAgentZoom, ResetOnboarding},
  94    assistant::{OpenRulesLibrary, Toggle, ToggleFocus},
  95};
  96
  97const AGENT_PANEL_KEY: &str = "agent_panel";
  98const RECENTLY_UPDATED_MENU_LIMIT: usize = 6;
  99
 100fn read_serialized_panel(
 101    workspace_id: workspace::WorkspaceId,
 102    kvp: &KeyValueStore,
 103) -> Option<SerializedAgentPanel> {
 104    let scope = kvp.scoped(AGENT_PANEL_KEY);
 105    let key = i64::from(workspace_id).to_string();
 106    scope
 107        .read(&key)
 108        .log_err()
 109        .flatten()
 110        .and_then(|json| serde_json::from_str::<SerializedAgentPanel>(&json).log_err())
 111}
 112
 113async fn save_serialized_panel(
 114    workspace_id: workspace::WorkspaceId,
 115    panel: SerializedAgentPanel,
 116    kvp: KeyValueStore,
 117) -> Result<()> {
 118    let scope = kvp.scoped(AGENT_PANEL_KEY);
 119    let key = i64::from(workspace_id).to_string();
 120    scope.write(key, serde_json::to_string(&panel)?).await?;
 121    Ok(())
 122}
 123
 124/// Migration: reads the original single-panel format stored under the
 125/// `"agent_panel"` KVP key before per-workspace keying was introduced.
 126fn read_legacy_serialized_panel(kvp: &KeyValueStore) -> Option<SerializedAgentPanel> {
 127    kvp.read_kvp(AGENT_PANEL_KEY)
 128        .log_err()
 129        .flatten()
 130        .and_then(|json| serde_json::from_str::<SerializedAgentPanel>(&json).log_err())
 131}
 132
 133#[derive(Serialize, Deserialize, Debug)]
 134struct SerializedAgentPanel {
 135    selected_agent: Option<AgentType>,
 136    #[serde(default)]
 137    last_active_thread: Option<SerializedActiveThread>,
 138    #[serde(default)]
 139    start_thread_in: Option<StartThreadIn>,
 140}
 141
 142#[derive(Serialize, Deserialize, Debug)]
 143struct SerializedActiveThread {
 144    session_id: String,
 145    agent_type: AgentType,
 146    title: Option<String>,
 147    work_dirs: Option<SerializedPathList>,
 148}
 149
 150pub fn init(cx: &mut App) {
 151    cx.observe_new(
 152        |workspace: &mut Workspace, _window, _cx: &mut Context<Workspace>| {
 153            workspace
 154                .register_action(|workspace, action: &NewThread, window, cx| {
 155                    if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
 156                        panel.update(cx, |panel, cx| panel.new_thread(action, window, cx));
 157                        workspace.focus_panel::<AgentPanel>(window, cx);
 158                    }
 159                })
 160                .register_action(
 161                    |workspace, action: &NewNativeAgentThreadFromSummary, window, cx| {
 162                        if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
 163                            panel.update(cx, |panel, cx| {
 164                                panel.new_native_agent_thread_from_summary(action, window, cx)
 165                            });
 166                            workspace.focus_panel::<AgentPanel>(window, cx);
 167                        }
 168                    },
 169                )
 170                .register_action(|workspace, _: &ExpandMessageEditor, window, cx| {
 171                    if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
 172                        workspace.focus_panel::<AgentPanel>(window, cx);
 173                        panel.update(cx, |panel, cx| panel.expand_message_editor(window, cx));
 174                    }
 175                })
 176                .register_action(|workspace, _: &OpenHistory, window, cx| {
 177                    if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
 178                        workspace.focus_panel::<AgentPanel>(window, cx);
 179                        panel.update(cx, |panel, cx| panel.open_history(window, cx));
 180                    }
 181                })
 182                .register_action(|workspace, _: &OpenSettings, window, cx| {
 183                    if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
 184                        workspace.focus_panel::<AgentPanel>(window, cx);
 185                        panel.update(cx, |panel, cx| panel.open_configuration(window, cx));
 186                    }
 187                })
 188                .register_action(|workspace, _: &NewTextThread, window, cx| {
 189                    if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
 190                        workspace.focus_panel::<AgentPanel>(window, cx);
 191                        panel.update(cx, |panel, cx| {
 192                            panel.new_text_thread(window, cx);
 193                        });
 194                    }
 195                })
 196                .register_action(|workspace, action: &NewExternalAgentThread, window, cx| {
 197                    if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
 198                        workspace.focus_panel::<AgentPanel>(window, cx);
 199                        panel.update(cx, |panel, cx| {
 200                            panel.external_thread(
 201                                action.agent.clone(),
 202                                None,
 203                                None,
 204                                None,
 205                                None,
 206                                true,
 207                                window,
 208                                cx,
 209                            )
 210                        });
 211                    }
 212                })
 213                .register_action(|workspace, action: &OpenRulesLibrary, window, cx| {
 214                    if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
 215                        workspace.focus_panel::<AgentPanel>(window, cx);
 216                        panel.update(cx, |panel, cx| {
 217                            panel.deploy_rules_library(action, window, cx)
 218                        });
 219                    }
 220                })
 221                .register_action(|workspace, _: &Follow, window, cx| {
 222                    workspace.follow(CollaboratorId::Agent, window, cx);
 223                })
 224                .register_action(|workspace, _: &OpenAgentDiff, window, cx| {
 225                    let thread = workspace
 226                        .panel::<AgentPanel>(cx)
 227                        .and_then(|panel| panel.read(cx).active_conversation_view().cloned())
 228                        .and_then(|conversation| {
 229                            conversation
 230                                .read(cx)
 231                                .active_thread()
 232                                .map(|r| r.read(cx).thread.clone())
 233                        });
 234
 235                    if let Some(thread) = thread {
 236                        AgentDiffPane::deploy_in_workspace(thread, workspace, window, cx);
 237                    }
 238                })
 239                .register_action(|workspace, _: &ToggleNavigationMenu, window, cx| {
 240                    if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
 241                        workspace.focus_panel::<AgentPanel>(window, cx);
 242                        panel.update(cx, |panel, cx| {
 243                            panel.toggle_navigation_menu(&ToggleNavigationMenu, window, cx);
 244                        });
 245                    }
 246                })
 247                .register_action(|workspace, _: &ToggleOptionsMenu, window, cx| {
 248                    if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
 249                        workspace.focus_panel::<AgentPanel>(window, cx);
 250                        panel.update(cx, |panel, cx| {
 251                            panel.toggle_options_menu(&ToggleOptionsMenu, window, cx);
 252                        });
 253                    }
 254                })
 255                .register_action(|workspace, _: &ToggleNewThreadMenu, window, cx| {
 256                    if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
 257                        workspace.focus_panel::<AgentPanel>(window, cx);
 258                        panel.update(cx, |panel, cx| {
 259                            panel.toggle_new_thread_menu(&ToggleNewThreadMenu, window, cx);
 260                        });
 261                    }
 262                })
 263                .register_action(|workspace, _: &OpenAcpOnboardingModal, window, cx| {
 264                    AcpOnboardingModal::toggle(workspace, window, cx)
 265                })
 266                .register_action(
 267                    |workspace, _: &OpenClaudeAgentOnboardingModal, window, cx| {
 268                        ClaudeCodeOnboardingModal::toggle(workspace, window, cx)
 269                    },
 270                )
 271                .register_action(|_workspace, _: &ResetOnboarding, window, cx| {
 272                    window.dispatch_action(workspace::RestoreBanner.boxed_clone(), cx);
 273                    window.refresh();
 274                })
 275                .register_action(|workspace, _: &ResetTrialUpsell, _window, cx| {
 276                    if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
 277                        panel.update(cx, |panel, _| {
 278                            panel
 279                                .on_boarding_upsell_dismissed
 280                                .store(false, Ordering::Release);
 281                        });
 282                    }
 283                    OnboardingUpsell::set_dismissed(false, cx);
 284                })
 285                .register_action(|_workspace, _: &ResetTrialEndUpsell, _window, cx| {
 286                    TrialEndUpsell::set_dismissed(false, cx);
 287                })
 288                .register_action(|workspace, _: &ResetAgentZoom, window, cx| {
 289                    if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
 290                        panel.update(cx, |panel, cx| {
 291                            panel.reset_agent_zoom(window, cx);
 292                        });
 293                    }
 294                })
 295                .register_action(|workspace, _: &CopyThreadToClipboard, window, cx| {
 296                    if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
 297                        panel.update(cx, |panel, cx| {
 298                            panel.copy_thread_to_clipboard(window, cx);
 299                        });
 300                    }
 301                })
 302                .register_action(|workspace, _: &LoadThreadFromClipboard, window, cx| {
 303                    if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
 304                        workspace.focus_panel::<AgentPanel>(window, cx);
 305                        panel.update(cx, |panel, cx| {
 306                            panel.load_thread_from_clipboard(window, cx);
 307                        });
 308                    }
 309                })
 310                .register_action(|workspace, action: &ReviewBranchDiff, window, cx| {
 311                    let Some(panel) = workspace.panel::<AgentPanel>(cx) else {
 312                        return;
 313                    };
 314
 315                    let mention_uri = MentionUri::GitDiff {
 316                        base_ref: action.base_ref.to_string(),
 317                    };
 318                    let diff_uri = mention_uri.to_uri().to_string();
 319
 320                    let content_blocks = vec![
 321                        acp::ContentBlock::Text(acp::TextContent::new(
 322                            "Please review this branch diff carefully. Point out any issues, \
 323                             potential bugs, or improvement opportunities you find.\n\n"
 324                                .to_string(),
 325                        )),
 326                        acp::ContentBlock::Resource(acp::EmbeddedResource::new(
 327                            acp::EmbeddedResourceResource::TextResourceContents(
 328                                acp::TextResourceContents::new(
 329                                    action.diff_text.to_string(),
 330                                    diff_uri,
 331                                ),
 332                            ),
 333                        )),
 334                    ];
 335
 336                    workspace.focus_panel::<AgentPanel>(window, cx);
 337
 338                    panel.update(cx, |panel, cx| {
 339                        panel.external_thread(
 340                            None,
 341                            None,
 342                            None,
 343                            None,
 344                            Some(AgentInitialContent::ContentBlock {
 345                                blocks: content_blocks,
 346                                auto_submit: true,
 347                            }),
 348                            true,
 349                            window,
 350                            cx,
 351                        );
 352                    });
 353                })
 354                .register_action(
 355                    |workspace, action: &ResolveConflictsWithAgent, window, cx| {
 356                        let Some(panel) = workspace.panel::<AgentPanel>(cx) else {
 357                            return;
 358                        };
 359
 360                        let content_blocks = build_conflict_resolution_prompt(&action.conflicts);
 361
 362                        workspace.focus_panel::<AgentPanel>(window, cx);
 363
 364                        panel.update(cx, |panel, cx| {
 365                            panel.external_thread(
 366                                None,
 367                                None,
 368                                None,
 369                                None,
 370                                Some(AgentInitialContent::ContentBlock {
 371                                    blocks: content_blocks,
 372                                    auto_submit: true,
 373                                }),
 374                                true,
 375                                window,
 376                                cx,
 377                            );
 378                        });
 379                    },
 380                )
 381                .register_action(
 382                    |workspace, action: &ResolveConflictedFilesWithAgent, window, cx| {
 383                        let Some(panel) = workspace.panel::<AgentPanel>(cx) else {
 384                            return;
 385                        };
 386
 387                        let content_blocks =
 388                            build_conflicted_files_resolution_prompt(&action.conflicted_file_paths);
 389
 390                        workspace.focus_panel::<AgentPanel>(window, cx);
 391
 392                        panel.update(cx, |panel, cx| {
 393                            panel.external_thread(
 394                                None,
 395                                None,
 396                                None,
 397                                None,
 398                                Some(AgentInitialContent::ContentBlock {
 399                                    blocks: content_blocks,
 400                                    auto_submit: true,
 401                                }),
 402                                true,
 403                                window,
 404                                cx,
 405                            );
 406                        });
 407                    },
 408                )
 409                .register_action(|workspace, action: &StartThreadIn, window, cx| {
 410                    if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
 411                        panel.update(cx, |panel, cx| {
 412                            panel.set_start_thread_in(action, window, cx);
 413                        });
 414                    }
 415                })
 416                .register_action(|workspace, _: &CycleStartThreadIn, window, cx| {
 417                    if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
 418                        panel.update(cx, |panel, cx| {
 419                            panel.cycle_start_thread_in(window, cx);
 420                        });
 421                    }
 422                });
 423        },
 424    )
 425    .detach();
 426}
 427
 428fn conflict_resource_block(conflict: &ConflictContent) -> acp::ContentBlock {
 429    let mention_uri = MentionUri::MergeConflict {
 430        file_path: conflict.file_path.clone(),
 431    };
 432    acp::ContentBlock::Resource(acp::EmbeddedResource::new(
 433        acp::EmbeddedResourceResource::TextResourceContents(acp::TextResourceContents::new(
 434            conflict.conflict_text.clone(),
 435            mention_uri.to_uri().to_string(),
 436        )),
 437    ))
 438}
 439
 440fn build_conflict_resolution_prompt(conflicts: &[ConflictContent]) -> Vec<acp::ContentBlock> {
 441    if conflicts.is_empty() {
 442        return Vec::new();
 443    }
 444
 445    let mut blocks = Vec::new();
 446
 447    if conflicts.len() == 1 {
 448        let conflict = &conflicts[0];
 449
 450        blocks.push(acp::ContentBlock::Text(acp::TextContent::new(
 451            "Please resolve the following merge conflict in ",
 452        )));
 453        let mention = MentionUri::File {
 454            abs_path: PathBuf::from(conflict.file_path.clone()),
 455        };
 456        blocks.push(acp::ContentBlock::ResourceLink(acp::ResourceLink::new(
 457            mention.name(),
 458            mention.to_uri(),
 459        )));
 460
 461        blocks.push(acp::ContentBlock::Text(acp::TextContent::new(
 462            indoc::formatdoc!(
 463                "\nThe conflict is between branch `{ours}` (ours) and `{theirs}` (theirs).
 464
 465                Analyze both versions carefully and resolve the conflict by editing \
 466                the file directly. Choose the resolution that best preserves the intent \
 467                of both changes, or combine them if appropriate.
 468
 469                ",
 470                ours = conflict.ours_branch_name,
 471                theirs = conflict.theirs_branch_name,
 472            ),
 473        )));
 474    } else {
 475        let n = conflicts.len();
 476        let unique_files: HashSet<&str> = conflicts.iter().map(|c| c.file_path.as_str()).collect();
 477        let ours = &conflicts[0].ours_branch_name;
 478        let theirs = &conflicts[0].theirs_branch_name;
 479        blocks.push(acp::ContentBlock::Text(acp::TextContent::new(
 480            indoc::formatdoc!(
 481                "Please resolve all {n} merge conflicts below.
 482
 483                The conflicts are between branch `{ours}` (ours) and `{theirs}` (theirs).
 484
 485                For each conflict, analyze both versions carefully and resolve them \
 486                by editing the file{suffix} directly. Choose resolutions that best preserve \
 487                the intent of both changes, or combine them if appropriate.
 488
 489                ",
 490                suffix = if unique_files.len() > 1 { "s" } else { "" },
 491            ),
 492        )));
 493    }
 494
 495    for conflict in conflicts {
 496        blocks.push(conflict_resource_block(conflict));
 497    }
 498
 499    blocks
 500}
 501
 502fn build_conflicted_files_resolution_prompt(
 503    conflicted_file_paths: &[String],
 504) -> Vec<acp::ContentBlock> {
 505    if conflicted_file_paths.is_empty() {
 506        return Vec::new();
 507    }
 508
 509    let instruction = indoc::indoc!(
 510        "The following files have unresolved merge conflicts. Please open each \
 511         file, find the conflict markers (`<<<<<<<` / `=======` / `>>>>>>>`), \
 512         and resolve every conflict by editing the files directly.
 513
 514         Choose resolutions that best preserve the intent of both changes, \
 515         or combine them if appropriate.
 516
 517         Files with conflicts:
 518         ",
 519    );
 520
 521    let mut content = vec![acp::ContentBlock::Text(acp::TextContent::new(instruction))];
 522    for path in conflicted_file_paths {
 523        let mention = MentionUri::File {
 524            abs_path: PathBuf::from(path),
 525        };
 526        content.push(acp::ContentBlock::ResourceLink(acp::ResourceLink::new(
 527            mention.name(),
 528            mention.to_uri(),
 529        )));
 530        content.push(acp::ContentBlock::Text(acp::TextContent::new("\n")));
 531    }
 532    content
 533}
 534
 535#[derive(Clone, Debug, PartialEq, Eq)]
 536enum History {
 537    AgentThreads { view: Entity<ThreadHistoryView> },
 538    TextThreads,
 539}
 540
 541enum ActiveView {
 542    Uninitialized,
 543    AgentThread {
 544        conversation_view: Entity<ConversationView>,
 545    },
 546    TextThread {
 547        text_thread_editor: Entity<TextThreadEditor>,
 548        title_editor: Entity<Editor>,
 549        buffer_search_bar: Entity<BufferSearchBar>,
 550        _subscriptions: Vec<gpui::Subscription>,
 551    },
 552    History {
 553        history: History,
 554    },
 555    Configuration,
 556}
 557
 558enum WhichFontSize {
 559    AgentFont,
 560    BufferFont,
 561    None,
 562}
 563
 564// TODO unify this with ExternalAgent
 565#[derive(Debug, Default, Clone, PartialEq, Serialize, Deserialize)]
 566pub enum AgentType {
 567    #[default]
 568    NativeAgent,
 569    TextThread,
 570    Custom {
 571        #[serde(rename = "name")]
 572        id: AgentId,
 573    },
 574}
 575
 576impl AgentType {
 577    pub fn is_native(&self) -> bool {
 578        matches!(self, Self::NativeAgent)
 579    }
 580
 581    fn label(&self) -> SharedString {
 582        match self {
 583            Self::NativeAgent | Self::TextThread => "Zed Agent".into(),
 584            Self::Custom { id, .. } => id.0.clone(),
 585        }
 586    }
 587
 588    fn icon(&self) -> Option<IconName> {
 589        match self {
 590            Self::NativeAgent | Self::TextThread => None,
 591            Self::Custom { .. } => Some(IconName::Sparkle),
 592        }
 593    }
 594}
 595
 596impl From<Agent> for AgentType {
 597    fn from(value: Agent) -> Self {
 598        match value {
 599            Agent::Custom { id } => Self::Custom { id },
 600            Agent::NativeAgent => Self::NativeAgent,
 601        }
 602    }
 603}
 604
 605impl StartThreadIn {
 606    fn label(&self) -> SharedString {
 607        match self {
 608            Self::LocalProject => "Current Worktree".into(),
 609            Self::NewWorktree => "New Git Worktree".into(),
 610        }
 611    }
 612}
 613
 614#[derive(Clone, Debug)]
 615#[allow(dead_code)]
 616pub enum WorktreeCreationStatus {
 617    Creating,
 618    Error(SharedString),
 619}
 620
 621impl ActiveView {
 622    pub fn which_font_size_used(&self) -> WhichFontSize {
 623        match self {
 624            ActiveView::Uninitialized
 625            | ActiveView::AgentThread { .. }
 626            | ActiveView::History { .. } => WhichFontSize::AgentFont,
 627            ActiveView::TextThread { .. } => WhichFontSize::BufferFont,
 628            ActiveView::Configuration => WhichFontSize::None,
 629        }
 630    }
 631
 632    pub fn text_thread(
 633        text_thread_editor: Entity<TextThreadEditor>,
 634        language_registry: Arc<LanguageRegistry>,
 635        window: &mut Window,
 636        cx: &mut App,
 637    ) -> Self {
 638        let title = text_thread_editor.read(cx).title(cx).to_string();
 639
 640        let editor = cx.new(|cx| {
 641            let mut editor = Editor::single_line(window, cx);
 642            editor.set_text(title, window, cx);
 643            editor
 644        });
 645
 646        // This is a workaround for `editor.set_text` emitting a `BufferEdited` event, which would
 647        // cause a custom summary to be set. The presence of this custom summary would cause
 648        // summarization to not happen.
 649        let mut suppress_first_edit = true;
 650
 651        let subscriptions = vec![
 652            window.subscribe(&editor, cx, {
 653                {
 654                    let text_thread_editor = text_thread_editor.clone();
 655                    move |editor, event, window, cx| match event {
 656                        EditorEvent::BufferEdited => {
 657                            if suppress_first_edit {
 658                                suppress_first_edit = false;
 659                                return;
 660                            }
 661                            let new_summary = editor.read(cx).text(cx);
 662
 663                            text_thread_editor.update(cx, |text_thread_editor, cx| {
 664                                text_thread_editor
 665                                    .text_thread()
 666                                    .update(cx, |text_thread, cx| {
 667                                        text_thread.set_custom_summary(new_summary, cx);
 668                                    })
 669                            })
 670                        }
 671                        EditorEvent::Blurred => {
 672                            if editor.read(cx).text(cx).is_empty() {
 673                                let summary = text_thread_editor
 674                                    .read(cx)
 675                                    .text_thread()
 676                                    .read(cx)
 677                                    .summary()
 678                                    .or_default();
 679
 680                                editor.update(cx, |editor, cx| {
 681                                    editor.set_text(summary, window, cx);
 682                                });
 683                            }
 684                        }
 685                        _ => {}
 686                    }
 687                }
 688            }),
 689            window.subscribe(&text_thread_editor.read(cx).text_thread().clone(), cx, {
 690                let editor = editor.clone();
 691                move |text_thread, event, window, cx| match event {
 692                    TextThreadEvent::SummaryGenerated => {
 693                        let summary = text_thread.read(cx).summary().or_default();
 694
 695                        editor.update(cx, |editor, cx| {
 696                            editor.set_text(summary, window, cx);
 697                        })
 698                    }
 699                    TextThreadEvent::PathChanged { .. } => {}
 700                    _ => {}
 701                }
 702            }),
 703        ];
 704
 705        let buffer_search_bar =
 706            cx.new(|cx| BufferSearchBar::new(Some(language_registry), window, cx));
 707        buffer_search_bar.update(cx, |buffer_search_bar, cx| {
 708            buffer_search_bar.set_active_pane_item(Some(&text_thread_editor), window, cx)
 709        });
 710
 711        Self::TextThread {
 712            text_thread_editor,
 713            title_editor: editor,
 714            buffer_search_bar,
 715            _subscriptions: subscriptions,
 716        }
 717    }
 718}
 719
 720pub struct AgentPanel {
 721    workspace: WeakEntity<Workspace>,
 722    /// Workspace id is used as a database key
 723    workspace_id: Option<WorkspaceId>,
 724    user_store: Entity<UserStore>,
 725    project: Entity<Project>,
 726    fs: Arc<dyn Fs>,
 727    language_registry: Arc<LanguageRegistry>,
 728    text_thread_history: Entity<TextThreadHistory>,
 729    thread_store: Entity<ThreadStore>,
 730    text_thread_store: Entity<assistant_text_thread::TextThreadStore>,
 731    prompt_store: Option<Entity<PromptStore>>,
 732    connection_store: Entity<AgentConnectionStore>,
 733    context_server_registry: Entity<ContextServerRegistry>,
 734    configuration: Option<Entity<AgentConfiguration>>,
 735    configuration_subscription: Option<Subscription>,
 736    focus_handle: FocusHandle,
 737    active_view: ActiveView,
 738    previous_view: Option<ActiveView>,
 739    background_threads: HashMap<acp::SessionId, Entity<ConversationView>>,
 740    new_thread_menu_handle: PopoverMenuHandle<ContextMenu>,
 741    start_thread_in_menu_handle: PopoverMenuHandle<ContextMenu>,
 742    agent_panel_menu_handle: PopoverMenuHandle<ContextMenu>,
 743    agent_navigation_menu_handle: PopoverMenuHandle<ContextMenu>,
 744    agent_navigation_menu: Option<Entity<ContextMenu>>,
 745    _extension_subscription: Option<Subscription>,
 746    _project_subscription: Subscription,
 747    zoomed: bool,
 748    pending_serialization: Option<Task<Result<()>>>,
 749    onboarding: Entity<AgentPanelOnboarding>,
 750    selected_agent_type: AgentType,
 751    start_thread_in: StartThreadIn,
 752    worktree_creation_status: Option<WorktreeCreationStatus>,
 753    _thread_view_subscription: Option<Subscription>,
 754    _active_thread_focus_subscription: Option<Subscription>,
 755    _worktree_creation_task: Option<Task<()>>,
 756    show_trust_workspace_message: bool,
 757    last_configuration_error_telemetry: Option<String>,
 758    on_boarding_upsell_dismissed: AtomicBool,
 759    _active_view_observation: Option<Subscription>,
 760}
 761
 762impl AgentPanel {
 763    fn serialize(&mut self, cx: &mut App) {
 764        let Some(workspace_id) = self.workspace_id else {
 765            return;
 766        };
 767
 768        let selected_agent_type = self.selected_agent_type.clone();
 769        let start_thread_in = Some(self.start_thread_in);
 770
 771        let last_active_thread = self.active_agent_thread(cx).map(|thread| {
 772            let thread = thread.read(cx);
 773            let title = thread.title();
 774            let work_dirs = thread.work_dirs().cloned();
 775            SerializedActiveThread {
 776                session_id: thread.session_id().0.to_string(),
 777                agent_type: self.selected_agent_type.clone(),
 778                title: title.map(|t| t.to_string()),
 779                work_dirs: work_dirs.map(|dirs| dirs.serialize()),
 780            }
 781        });
 782
 783        let kvp = KeyValueStore::global(cx);
 784        self.pending_serialization = Some(cx.background_spawn(async move {
 785            save_serialized_panel(
 786                workspace_id,
 787                SerializedAgentPanel {
 788                    selected_agent: Some(selected_agent_type),
 789                    last_active_thread,
 790                    start_thread_in,
 791                },
 792                kvp,
 793            )
 794            .await?;
 795            anyhow::Ok(())
 796        }));
 797    }
 798
 799    pub fn load(
 800        workspace: WeakEntity<Workspace>,
 801        prompt_builder: Arc<PromptBuilder>,
 802        mut cx: AsyncWindowContext,
 803    ) -> Task<Result<Entity<Self>>> {
 804        let prompt_store = cx.update(|_window, cx| PromptStore::global(cx));
 805        let kvp = cx.update(|_window, cx| KeyValueStore::global(cx)).ok();
 806        cx.spawn(async move |cx| {
 807            let prompt_store = match prompt_store {
 808                Ok(prompt_store) => prompt_store.await.ok(),
 809                Err(_) => None,
 810            };
 811            let workspace_id = workspace
 812                .read_with(cx, |workspace, _| workspace.database_id())
 813                .ok()
 814                .flatten();
 815
 816            let serialized_panel = cx
 817                .background_spawn(async move {
 818                    kvp.and_then(|kvp| {
 819                        workspace_id
 820                            .and_then(|id| read_serialized_panel(id, &kvp))
 821                            .or_else(|| read_legacy_serialized_panel(&kvp))
 822                    })
 823                })
 824                .await;
 825
 826            let slash_commands = Arc::new(SlashCommandWorkingSet::default());
 827            let text_thread_store = workspace
 828                .update(cx, |workspace, cx| {
 829                    let project = workspace.project().clone();
 830                    assistant_text_thread::TextThreadStore::new(
 831                        project,
 832                        prompt_builder,
 833                        slash_commands,
 834                        cx,
 835                    )
 836                })?
 837                .await?;
 838
 839            let last_active_thread = if let Some(thread_info) = serialized_panel
 840                .as_ref()
 841                .and_then(|p| p.last_active_thread.as_ref())
 842            {
 843                if thread_info.agent_type.is_native() {
 844                    let session_id = acp::SessionId::new(thread_info.session_id.clone());
 845                    let load_result = cx.update(|_window, cx| {
 846                        let thread_store = ThreadStore::global(cx);
 847                        thread_store.update(cx, |store, cx| store.load_thread(session_id, cx))
 848                    });
 849                    let thread_exists = if let Ok(task) = load_result {
 850                        task.await.ok().flatten().is_some()
 851                    } else {
 852                        false
 853                    };
 854                    if thread_exists {
 855                        Some(thread_info)
 856                    } else {
 857                        log::warn!(
 858                            "last active thread {} not found in database, skipping restoration",
 859                            thread_info.session_id
 860                        );
 861                        None
 862                    }
 863                } else {
 864                    Some(thread_info)
 865                }
 866            } else {
 867                None
 868            };
 869
 870            let panel = workspace.update_in(cx, |workspace, window, cx| {
 871                let panel =
 872                    cx.new(|cx| Self::new(workspace, text_thread_store, prompt_store, window, cx));
 873
 874                if let Some(serialized_panel) = &serialized_panel {
 875                    panel.update(cx, |panel, cx| {
 876                        if let Some(selected_agent) = serialized_panel.selected_agent.clone() {
 877                            panel.selected_agent_type = selected_agent;
 878                        }
 879                        if let Some(start_thread_in) = serialized_panel.start_thread_in {
 880                            let is_worktree_flag_enabled =
 881                                cx.has_flag::<AgentV2FeatureFlag>();
 882                            let is_valid = match &start_thread_in {
 883                                StartThreadIn::LocalProject => true,
 884                                StartThreadIn::NewWorktree => {
 885                                    let project = panel.project.read(cx);
 886                                    is_worktree_flag_enabled && !project.is_via_collab()
 887                                }
 888                            };
 889                            if is_valid {
 890                                panel.start_thread_in = start_thread_in;
 891                            } else {
 892                                log::info!(
 893                                    "deserialized start_thread_in {:?} is no longer valid, falling back to LocalProject",
 894                                    start_thread_in,
 895                                );
 896                            }
 897                        }
 898                        cx.notify();
 899                    });
 900                }
 901
 902                if let Some(thread_info) = last_active_thread {
 903                    let agent_type = thread_info.agent_type.clone();
 904                    panel.update(cx, |panel, cx| {
 905                        panel.selected_agent_type = agent_type;
 906                        if let Some(agent) = panel.selected_agent() {
 907                            panel.load_agent_thread(
 908                                agent,
 909                                thread_info.session_id.clone().into(),
 910                                thread_info.work_dirs.as_ref().map(|dirs| PathList::deserialize(dirs)),
 911                                thread_info.title.as_ref().map(|t| t.clone().into()),
 912                                false,
 913                                window,
 914                                cx,
 915                            );
 916                        }
 917                    });
 918                }
 919                panel
 920            })?;
 921
 922            Ok(panel)
 923        })
 924    }
 925
 926    pub(crate) fn new(
 927        workspace: &Workspace,
 928        text_thread_store: Entity<assistant_text_thread::TextThreadStore>,
 929        prompt_store: Option<Entity<PromptStore>>,
 930        window: &mut Window,
 931        cx: &mut Context<Self>,
 932    ) -> Self {
 933        let fs = workspace.app_state().fs.clone();
 934        let user_store = workspace.app_state().user_store.clone();
 935        let project = workspace.project();
 936        let language_registry = project.read(cx).languages().clone();
 937        let client = workspace.client().clone();
 938        let workspace_id = workspace.database_id();
 939        let workspace = workspace.weak_handle();
 940
 941        let context_server_registry =
 942            cx.new(|cx| ContextServerRegistry::new(project.read(cx).context_server_store(), cx));
 943
 944        let thread_store = ThreadStore::global(cx);
 945        let text_thread_history =
 946            cx.new(|cx| TextThreadHistory::new(text_thread_store.clone(), window, cx));
 947
 948        cx.subscribe_in(
 949            &text_thread_history,
 950            window,
 951            |this, _, event, window, cx| match event {
 952                TextThreadHistoryEvent::Open(thread) => {
 953                    this.open_saved_text_thread(thread.path.clone(), window, cx)
 954                        .detach_and_log_err(cx);
 955                }
 956            },
 957        )
 958        .detach();
 959
 960        let active_view = ActiveView::Uninitialized;
 961
 962        let weak_panel = cx.entity().downgrade();
 963
 964        window.defer(cx, move |window, cx| {
 965            let panel = weak_panel.clone();
 966            let agent_navigation_menu =
 967                ContextMenu::build_persistent(window, cx, move |mut menu, window, cx| {
 968                    if let Some(panel) = panel.upgrade() {
 969                        if let Some(history) = panel
 970                            .update(cx, |panel, cx| panel.history_for_selected_agent(window, cx))
 971                        {
 972                            let view_all_label = match history {
 973                                History::AgentThreads { .. } => "View All",
 974                                History::TextThreads => "View All Text Threads",
 975                            };
 976                            menu = Self::populate_recently_updated_menu_section(
 977                                menu, panel, history, cx,
 978                            );
 979                            menu = menu.action(view_all_label, Box::new(OpenHistory));
 980                        }
 981                    }
 982
 983                    menu = menu
 984                        .fixed_width(px(320.).into())
 985                        .keep_open_on_confirm(false)
 986                        .key_context("NavigationMenu");
 987
 988                    menu
 989                });
 990            weak_panel
 991                .update(cx, |panel, cx| {
 992                    cx.subscribe_in(
 993                        &agent_navigation_menu,
 994                        window,
 995                        |_, menu, _: &DismissEvent, window, cx| {
 996                            menu.update(cx, |menu, _| {
 997                                menu.clear_selected();
 998                            });
 999                            cx.focus_self(window);
1000                        },
1001                    )
1002                    .detach();
1003                    panel.agent_navigation_menu = Some(agent_navigation_menu);
1004                })
1005                .ok();
1006        });
1007
1008        let weak_panel = cx.entity().downgrade();
1009        let onboarding = cx.new(|cx| {
1010            AgentPanelOnboarding::new(
1011                user_store.clone(),
1012                client,
1013                move |_window, cx| {
1014                    weak_panel
1015                        .update(cx, |panel, _| {
1016                            panel
1017                                .on_boarding_upsell_dismissed
1018                                .store(true, Ordering::Release);
1019                        })
1020                        .ok();
1021                    OnboardingUpsell::set_dismissed(true, cx);
1022                },
1023                cx,
1024            )
1025        });
1026
1027        // Subscribe to extension events to sync agent servers when extensions change
1028        let extension_subscription = if let Some(extension_events) = ExtensionEvents::try_global(cx)
1029        {
1030            Some(
1031                cx.subscribe(&extension_events, |this, _source, event, cx| match event {
1032                    extension::Event::ExtensionInstalled(_)
1033                    | extension::Event::ExtensionUninstalled(_)
1034                    | extension::Event::ExtensionsInstalledChanged => {
1035                        this.sync_agent_servers_from_extensions(cx);
1036                    }
1037                    _ => {}
1038                }),
1039            )
1040        } else {
1041            None
1042        };
1043
1044        let connection_store = cx.new(|cx| {
1045            let mut store = AgentConnectionStore::new(project.clone(), cx);
1046            // Register the native agent right away, so that it is available for
1047            // the inline assistant etc.
1048            store.request_connection(
1049                Agent::NativeAgent,
1050                Agent::NativeAgent.server(fs.clone(), thread_store.clone()),
1051                cx,
1052            );
1053            store
1054        });
1055        let _project_subscription =
1056            cx.subscribe(&project, |this, _project, event, cx| match event {
1057                project::Event::WorktreeAdded(_)
1058                | project::Event::WorktreeRemoved(_)
1059                | project::Event::WorktreeOrderChanged => {
1060                    this.update_thread_work_dirs(cx);
1061                }
1062                _ => {}
1063            });
1064
1065        let mut panel = Self {
1066            workspace_id,
1067            active_view,
1068            workspace,
1069            user_store,
1070            project: project.clone(),
1071            fs: fs.clone(),
1072            language_registry,
1073            text_thread_store,
1074            prompt_store,
1075            connection_store,
1076            configuration: None,
1077            configuration_subscription: None,
1078            focus_handle: cx.focus_handle(),
1079            context_server_registry,
1080            previous_view: None,
1081            background_threads: HashMap::default(),
1082            new_thread_menu_handle: PopoverMenuHandle::default(),
1083            start_thread_in_menu_handle: PopoverMenuHandle::default(),
1084            agent_panel_menu_handle: PopoverMenuHandle::default(),
1085            agent_navigation_menu_handle: PopoverMenuHandle::default(),
1086            agent_navigation_menu: None,
1087            _extension_subscription: extension_subscription,
1088            _project_subscription,
1089            zoomed: false,
1090            pending_serialization: None,
1091            onboarding,
1092            text_thread_history,
1093            thread_store,
1094            selected_agent_type: AgentType::default(),
1095            start_thread_in: StartThreadIn::default(),
1096            worktree_creation_status: None,
1097            _thread_view_subscription: None,
1098            _active_thread_focus_subscription: None,
1099            _worktree_creation_task: None,
1100            show_trust_workspace_message: false,
1101            last_configuration_error_telemetry: None,
1102            on_boarding_upsell_dismissed: AtomicBool::new(OnboardingUpsell::dismissed(cx)),
1103            _active_view_observation: None,
1104        };
1105
1106        // Initial sync of agent servers from extensions
1107        panel.sync_agent_servers_from_extensions(cx);
1108        panel
1109    }
1110
1111    pub fn toggle_focus(
1112        workspace: &mut Workspace,
1113        _: &ToggleFocus,
1114        window: &mut Window,
1115        cx: &mut Context<Workspace>,
1116    ) {
1117        if workspace
1118            .panel::<Self>(cx)
1119            .is_some_and(|panel| panel.read(cx).enabled(cx))
1120        {
1121            workspace.toggle_panel_focus::<Self>(window, cx);
1122        }
1123    }
1124
1125    pub fn toggle(
1126        workspace: &mut Workspace,
1127        _: &Toggle,
1128        window: &mut Window,
1129        cx: &mut Context<Workspace>,
1130    ) {
1131        if workspace
1132            .panel::<Self>(cx)
1133            .is_some_and(|panel| panel.read(cx).enabled(cx))
1134        {
1135            if !workspace.toggle_panel_focus::<Self>(window, cx) {
1136                workspace.close_panel::<Self>(window, cx);
1137            }
1138        }
1139    }
1140
1141    pub(crate) fn prompt_store(&self) -> &Option<Entity<PromptStore>> {
1142        &self.prompt_store
1143    }
1144
1145    pub fn thread_store(&self) -> &Entity<ThreadStore> {
1146        &self.thread_store
1147    }
1148
1149    pub fn connection_store(&self) -> &Entity<AgentConnectionStore> {
1150        &self.connection_store
1151    }
1152
1153    pub fn open_thread(
1154        &mut self,
1155        session_id: acp::SessionId,
1156        work_dirs: Option<PathList>,
1157        title: Option<SharedString>,
1158        window: &mut Window,
1159        cx: &mut Context<Self>,
1160    ) {
1161        self.external_thread(
1162            Some(crate::Agent::NativeAgent),
1163            Some(session_id),
1164            work_dirs,
1165            title,
1166            None,
1167            true,
1168            window,
1169            cx,
1170        );
1171    }
1172
1173    pub(crate) fn context_server_registry(&self) -> &Entity<ContextServerRegistry> {
1174        &self.context_server_registry
1175    }
1176
1177    pub fn is_visible(workspace: &Entity<Workspace>, cx: &App) -> bool {
1178        let workspace_read = workspace.read(cx);
1179
1180        workspace_read
1181            .panel::<AgentPanel>(cx)
1182            .map(|panel| {
1183                let panel_id = Entity::entity_id(&panel);
1184
1185                workspace_read.all_docks().iter().any(|dock| {
1186                    dock.read(cx)
1187                        .visible_panel()
1188                        .is_some_and(|visible_panel| visible_panel.panel_id() == panel_id)
1189                })
1190            })
1191            .unwrap_or(false)
1192    }
1193
1194    pub fn new_thread(&mut self, _action: &NewThread, window: &mut Window, cx: &mut Context<Self>) {
1195        self.reset_start_thread_in_to_default(cx);
1196        self.external_thread(None, None, None, None, None, true, window, cx);
1197    }
1198
1199    fn new_native_agent_thread_from_summary(
1200        &mut self,
1201        action: &NewNativeAgentThreadFromSummary,
1202        window: &mut Window,
1203        cx: &mut Context<Self>,
1204    ) {
1205        let session_id = action.from_session_id.clone();
1206
1207        let Some(history) = self
1208            .connection_store
1209            .read(cx)
1210            .entry(&Agent::NativeAgent)
1211            .and_then(|e| e.read(cx).history().cloned())
1212        else {
1213            debug_panic!("Native agent is not registered");
1214            return;
1215        };
1216
1217        cx.spawn_in(window, async move |this, cx| {
1218            this.update_in(cx, |this, window, cx| {
1219                let thread = history
1220                    .read(cx)
1221                    .session_for_id(&session_id)
1222                    .context("Session not found")?;
1223
1224                this.external_thread(
1225                    Some(Agent::NativeAgent),
1226                    None,
1227                    None,
1228                    None,
1229                    Some(AgentInitialContent::ThreadSummary {
1230                        session_id: thread.session_id,
1231                        title: thread.title,
1232                    }),
1233                    true,
1234                    window,
1235                    cx,
1236                );
1237                anyhow::Ok(())
1238            })
1239        })
1240        .detach_and_log_err(cx);
1241    }
1242
1243    fn new_text_thread(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1244        telemetry::event!("Agent Thread Started", agent = "zed-text");
1245
1246        let context = self
1247            .text_thread_store
1248            .update(cx, |context_store, cx| context_store.create(cx));
1249        let lsp_adapter_delegate = make_lsp_adapter_delegate(&self.project, cx)
1250            .log_err()
1251            .flatten();
1252
1253        let text_thread_editor = cx.new(|cx| {
1254            let mut editor = TextThreadEditor::for_text_thread(
1255                context,
1256                self.fs.clone(),
1257                self.workspace.clone(),
1258                self.project.clone(),
1259                lsp_adapter_delegate,
1260                window,
1261                cx,
1262            );
1263            editor.insert_default_prompt(window, cx);
1264            editor
1265        });
1266
1267        if self.selected_agent_type != AgentType::TextThread {
1268            self.selected_agent_type = AgentType::TextThread;
1269            self.serialize(cx);
1270        }
1271
1272        self.set_active_view(
1273            ActiveView::text_thread(
1274                text_thread_editor.clone(),
1275                self.language_registry.clone(),
1276                window,
1277                cx,
1278            ),
1279            true,
1280            window,
1281            cx,
1282        );
1283        text_thread_editor.focus_handle(cx).focus(window, cx);
1284    }
1285
1286    fn external_thread(
1287        &mut self,
1288        agent_choice: Option<crate::Agent>,
1289        resume_session_id: Option<acp::SessionId>,
1290        work_dirs: Option<PathList>,
1291        title: Option<SharedString>,
1292        initial_content: Option<AgentInitialContent>,
1293        focus: bool,
1294        window: &mut Window,
1295        cx: &mut Context<Self>,
1296    ) {
1297        let workspace = self.workspace.clone();
1298        let project = self.project.clone();
1299        let fs = self.fs.clone();
1300        let is_via_collab = self.project.read(cx).is_via_collab();
1301
1302        const LAST_USED_EXTERNAL_AGENT_KEY: &str = "agent_panel__last_used_external_agent";
1303
1304        #[derive(Serialize, Deserialize)]
1305        struct LastUsedExternalAgent {
1306            agent: crate::Agent,
1307        }
1308
1309        let thread_store = self.thread_store.clone();
1310        let kvp = KeyValueStore::global(cx);
1311
1312        if let Some(agent) = agent_choice {
1313            cx.background_spawn({
1314                let agent = agent.clone();
1315                let kvp = kvp;
1316                async move {
1317                    if let Some(serialized) =
1318                        serde_json::to_string(&LastUsedExternalAgent { agent }).log_err()
1319                    {
1320                        kvp.write_kvp(LAST_USED_EXTERNAL_AGENT_KEY.to_string(), serialized)
1321                            .await
1322                            .log_err();
1323                    }
1324                }
1325            })
1326            .detach();
1327
1328            let server = agent.server(fs, thread_store);
1329            self.create_agent_thread(
1330                server,
1331                resume_session_id,
1332                work_dirs,
1333                title,
1334                initial_content,
1335                workspace,
1336                project,
1337                agent,
1338                focus,
1339                window,
1340                cx,
1341            );
1342        } else {
1343            cx.spawn_in(window, async move |this, cx| {
1344                let ext_agent = if is_via_collab {
1345                    Agent::NativeAgent
1346                } else {
1347                    cx.background_spawn(async move { kvp.read_kvp(LAST_USED_EXTERNAL_AGENT_KEY) })
1348                        .await
1349                        .log_err()
1350                        .flatten()
1351                        .and_then(|value| {
1352                            serde_json::from_str::<LastUsedExternalAgent>(&value).log_err()
1353                        })
1354                        .map(|agent| agent.agent)
1355                        .unwrap_or(Agent::NativeAgent)
1356                };
1357
1358                let server = ext_agent.server(fs, thread_store);
1359                this.update_in(cx, |agent_panel, window, cx| {
1360                    agent_panel.create_agent_thread(
1361                        server,
1362                        resume_session_id,
1363                        work_dirs,
1364                        title,
1365                        initial_content,
1366                        workspace,
1367                        project,
1368                        ext_agent,
1369                        focus,
1370                        window,
1371                        cx,
1372                    );
1373                })?;
1374
1375                anyhow::Ok(())
1376            })
1377            .detach_and_log_err(cx);
1378        }
1379    }
1380
1381    fn deploy_rules_library(
1382        &mut self,
1383        action: &OpenRulesLibrary,
1384        _window: &mut Window,
1385        cx: &mut Context<Self>,
1386    ) {
1387        open_rules_library(
1388            self.language_registry.clone(),
1389            Box::new(PromptLibraryInlineAssist::new(self.workspace.clone())),
1390            Rc::new(|| {
1391                Rc::new(SlashCommandCompletionProvider::new(
1392                    Arc::new(SlashCommandWorkingSet::default()),
1393                    None,
1394                    None,
1395                ))
1396            }),
1397            action
1398                .prompt_to_select
1399                .map(|uuid| UserPromptId(uuid).into()),
1400            cx,
1401        )
1402        .detach_and_log_err(cx);
1403    }
1404
1405    fn expand_message_editor(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1406        let Some(conversation_view) = self.active_conversation_view() else {
1407            return;
1408        };
1409
1410        let Some(active_thread) = conversation_view.read(cx).active_thread().cloned() else {
1411            return;
1412        };
1413
1414        active_thread.update(cx, |active_thread, cx| {
1415            active_thread.expand_message_editor(&ExpandMessageEditor, window, cx);
1416            active_thread.focus_handle(cx).focus(window, cx);
1417        })
1418    }
1419
1420    fn has_history_for_selected_agent(&self, cx: &App) -> bool {
1421        match &self.selected_agent_type {
1422            AgentType::TextThread | AgentType::NativeAgent => true,
1423            AgentType::Custom { id } => {
1424                let agent = Agent::Custom { id: id.clone() };
1425                self.connection_store
1426                    .read(cx)
1427                    .entry(&agent)
1428                    .map_or(false, |entry| entry.read(cx).history().is_some())
1429            }
1430        }
1431    }
1432
1433    fn history_for_selected_agent(
1434        &self,
1435        window: &mut Window,
1436        cx: &mut Context<Self>,
1437    ) -> Option<History> {
1438        match &self.selected_agent_type {
1439            AgentType::TextThread => Some(History::TextThreads),
1440            AgentType::NativeAgent => {
1441                let history = self
1442                    .connection_store
1443                    .read(cx)
1444                    .entry(&Agent::NativeAgent)?
1445                    .read(cx)
1446                    .history()?
1447                    .clone();
1448
1449                Some(History::AgentThreads {
1450                    view: self.create_thread_history_view(Agent::NativeAgent, history, window, cx),
1451                })
1452            }
1453            AgentType::Custom { id, .. } => {
1454                let agent = Agent::Custom { id: id.clone() };
1455                let history = self
1456                    .connection_store
1457                    .read(cx)
1458                    .entry(&agent)?
1459                    .read(cx)
1460                    .history()?
1461                    .clone();
1462                Some(History::AgentThreads {
1463                    view: self.create_thread_history_view(agent, history, window, cx),
1464                })
1465            }
1466        }
1467    }
1468
1469    fn create_thread_history_view(
1470        &self,
1471        agent: Agent,
1472        history: Entity<ThreadHistory>,
1473        window: &mut Window,
1474        cx: &mut Context<Self>,
1475    ) -> Entity<ThreadHistoryView> {
1476        let view = cx.new(|cx| ThreadHistoryView::new(history.clone(), window, cx));
1477        cx.subscribe_in(
1478            &view,
1479            window,
1480            move |this, _, event, window, cx| match event {
1481                ThreadHistoryViewEvent::Open(thread) => {
1482                    this.load_agent_thread(
1483                        agent.clone(),
1484                        thread.session_id.clone(),
1485                        thread.work_dirs.clone(),
1486                        thread.title.clone(),
1487                        true,
1488                        window,
1489                        cx,
1490                    );
1491                }
1492            },
1493        )
1494        .detach();
1495        view
1496    }
1497
1498    fn open_history(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1499        let Some(history) = self.history_for_selected_agent(window, cx) else {
1500            return;
1501        };
1502
1503        if let ActiveView::History {
1504            history: active_history,
1505        } = &self.active_view
1506        {
1507            if active_history == &history {
1508                if let Some(previous_view) = self.previous_view.take() {
1509                    self.set_active_view(previous_view, true, window, cx);
1510                }
1511                return;
1512            }
1513        }
1514
1515        self.set_active_view(ActiveView::History { history }, true, window, cx);
1516        cx.notify();
1517    }
1518
1519    pub(crate) fn open_saved_text_thread(
1520        &mut self,
1521        path: Arc<Path>,
1522        window: &mut Window,
1523        cx: &mut Context<Self>,
1524    ) -> Task<Result<()>> {
1525        let text_thread_task = self
1526            .text_thread_store
1527            .update(cx, |store, cx| store.open_local(path, cx));
1528        cx.spawn_in(window, async move |this, cx| {
1529            let text_thread = text_thread_task.await?;
1530            this.update_in(cx, |this, window, cx| {
1531                this.open_text_thread(text_thread, window, cx);
1532            })
1533        })
1534    }
1535
1536    pub(crate) fn open_text_thread(
1537        &mut self,
1538        text_thread: Entity<TextThread>,
1539        window: &mut Window,
1540        cx: &mut Context<Self>,
1541    ) {
1542        let lsp_adapter_delegate = make_lsp_adapter_delegate(&self.project.clone(), cx)
1543            .log_err()
1544            .flatten();
1545        let editor = cx.new(|cx| {
1546            TextThreadEditor::for_text_thread(
1547                text_thread,
1548                self.fs.clone(),
1549                self.workspace.clone(),
1550                self.project.clone(),
1551                lsp_adapter_delegate,
1552                window,
1553                cx,
1554            )
1555        });
1556
1557        if self.selected_agent_type != AgentType::TextThread {
1558            self.selected_agent_type = AgentType::TextThread;
1559            self.serialize(cx);
1560        }
1561
1562        self.set_active_view(
1563            ActiveView::text_thread(editor, self.language_registry.clone(), window, cx),
1564            true,
1565            window,
1566            cx,
1567        );
1568    }
1569
1570    pub fn go_back(&mut self, _: &workspace::GoBack, window: &mut Window, cx: &mut Context<Self>) {
1571        match self.active_view {
1572            ActiveView::Configuration | ActiveView::History { .. } => {
1573                if let Some(previous_view) = self.previous_view.take() {
1574                    self.set_active_view(previous_view, true, window, cx);
1575                }
1576                cx.notify();
1577            }
1578            _ => {}
1579        }
1580    }
1581
1582    pub fn toggle_navigation_menu(
1583        &mut self,
1584        _: &ToggleNavigationMenu,
1585        window: &mut Window,
1586        cx: &mut Context<Self>,
1587    ) {
1588        if !self.has_history_for_selected_agent(cx) {
1589            return;
1590        }
1591        self.agent_navigation_menu_handle.toggle(window, cx);
1592    }
1593
1594    pub fn toggle_options_menu(
1595        &mut self,
1596        _: &ToggleOptionsMenu,
1597        window: &mut Window,
1598        cx: &mut Context<Self>,
1599    ) {
1600        self.agent_panel_menu_handle.toggle(window, cx);
1601    }
1602
1603    pub fn toggle_new_thread_menu(
1604        &mut self,
1605        _: &ToggleNewThreadMenu,
1606        window: &mut Window,
1607        cx: &mut Context<Self>,
1608    ) {
1609        self.new_thread_menu_handle.toggle(window, cx);
1610    }
1611
1612    pub fn increase_font_size(
1613        &mut self,
1614        action: &IncreaseBufferFontSize,
1615        _: &mut Window,
1616        cx: &mut Context<Self>,
1617    ) {
1618        self.handle_font_size_action(action.persist, px(1.0), cx);
1619    }
1620
1621    pub fn decrease_font_size(
1622        &mut self,
1623        action: &DecreaseBufferFontSize,
1624        _: &mut Window,
1625        cx: &mut Context<Self>,
1626    ) {
1627        self.handle_font_size_action(action.persist, px(-1.0), cx);
1628    }
1629
1630    fn handle_font_size_action(&mut self, persist: bool, delta: Pixels, cx: &mut Context<Self>) {
1631        match self.active_view.which_font_size_used() {
1632            WhichFontSize::AgentFont => {
1633                if persist {
1634                    update_settings_file(self.fs.clone(), cx, move |settings, cx| {
1635                        let agent_ui_font_size =
1636                            ThemeSettings::get_global(cx).agent_ui_font_size(cx) + delta;
1637                        let agent_buffer_font_size =
1638                            ThemeSettings::get_global(cx).agent_buffer_font_size(cx) + delta;
1639
1640                        let _ = settings.theme.agent_ui_font_size.insert(
1641                            f32::from(theme_settings::clamp_font_size(agent_ui_font_size)).into(),
1642                        );
1643                        let _ = settings.theme.agent_buffer_font_size.insert(
1644                            f32::from(theme_settings::clamp_font_size(agent_buffer_font_size))
1645                                .into(),
1646                        );
1647                    });
1648                } else {
1649                    theme_settings::adjust_agent_ui_font_size(cx, |size| size + delta);
1650                    theme_settings::adjust_agent_buffer_font_size(cx, |size| size + delta);
1651                }
1652            }
1653            WhichFontSize::BufferFont => {
1654                // Prompt editor uses the buffer font size, so allow the action to propagate to the
1655                // default handler that changes that font size.
1656                cx.propagate();
1657            }
1658            WhichFontSize::None => {}
1659        }
1660    }
1661
1662    pub fn reset_font_size(
1663        &mut self,
1664        action: &ResetBufferFontSize,
1665        _: &mut Window,
1666        cx: &mut Context<Self>,
1667    ) {
1668        if action.persist {
1669            update_settings_file(self.fs.clone(), cx, move |settings, _| {
1670                settings.theme.agent_ui_font_size = None;
1671                settings.theme.agent_buffer_font_size = None;
1672            });
1673        } else {
1674            theme_settings::reset_agent_ui_font_size(cx);
1675            theme_settings::reset_agent_buffer_font_size(cx);
1676        }
1677    }
1678
1679    pub fn reset_agent_zoom(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
1680        theme_settings::reset_agent_ui_font_size(cx);
1681        theme_settings::reset_agent_buffer_font_size(cx);
1682    }
1683
1684    pub fn toggle_zoom(&mut self, _: &ToggleZoom, window: &mut Window, cx: &mut Context<Self>) {
1685        if self.zoomed {
1686            cx.emit(PanelEvent::ZoomOut);
1687        } else {
1688            if !self.focus_handle(cx).contains_focused(window, cx) {
1689                cx.focus_self(window);
1690            }
1691            cx.emit(PanelEvent::ZoomIn);
1692        }
1693    }
1694
1695    pub(crate) fn open_configuration(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1696        let agent_server_store = self.project.read(cx).agent_server_store().clone();
1697        let context_server_store = self.project.read(cx).context_server_store();
1698        let fs = self.fs.clone();
1699
1700        self.set_active_view(ActiveView::Configuration, true, window, cx);
1701        self.configuration = Some(cx.new(|cx| {
1702            AgentConfiguration::new(
1703                fs,
1704                agent_server_store,
1705                self.connection_store.clone(),
1706                context_server_store,
1707                self.context_server_registry.clone(),
1708                self.language_registry.clone(),
1709                self.workspace.clone(),
1710                window,
1711                cx,
1712            )
1713        }));
1714
1715        if let Some(configuration) = self.configuration.as_ref() {
1716            self.configuration_subscription = Some(cx.subscribe_in(
1717                configuration,
1718                window,
1719                Self::handle_agent_configuration_event,
1720            ));
1721
1722            configuration.focus_handle(cx).focus(window, cx);
1723        }
1724    }
1725
1726    pub(crate) fn open_active_thread_as_markdown(
1727        &mut self,
1728        _: &OpenActiveThreadAsMarkdown,
1729        window: &mut Window,
1730        cx: &mut Context<Self>,
1731    ) {
1732        if let Some(workspace) = self.workspace.upgrade()
1733            && let Some(conversation_view) = self.active_conversation_view()
1734            && let Some(active_thread) = conversation_view.read(cx).active_thread().cloned()
1735        {
1736            active_thread.update(cx, |thread, cx| {
1737                thread
1738                    .open_thread_as_markdown(workspace, window, cx)
1739                    .detach_and_log_err(cx);
1740            });
1741        }
1742    }
1743
1744    fn copy_thread_to_clipboard(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1745        let Some(thread) = self.active_native_agent_thread(cx) else {
1746            Self::show_deferred_toast(&self.workspace, "No active native thread to copy", cx);
1747            return;
1748        };
1749
1750        let workspace = self.workspace.clone();
1751        let load_task = thread.read(cx).to_db(cx);
1752
1753        cx.spawn_in(window, async move |_this, cx| {
1754            let db_thread = load_task.await;
1755            let shared_thread = SharedThread::from_db_thread(&db_thread);
1756            let thread_data = shared_thread.to_bytes()?;
1757            let encoded = base64::Engine::encode(&base64::prelude::BASE64_STANDARD, &thread_data);
1758
1759            cx.update(|_window, cx| {
1760                cx.write_to_clipboard(ClipboardItem::new_string(encoded));
1761                if let Some(workspace) = workspace.upgrade() {
1762                    workspace.update(cx, |workspace, cx| {
1763                        struct ThreadCopiedToast;
1764                        workspace.show_toast(
1765                            workspace::Toast::new(
1766                                workspace::notifications::NotificationId::unique::<ThreadCopiedToast>(),
1767                                "Thread copied to clipboard (base64 encoded)",
1768                            )
1769                            .autohide(),
1770                            cx,
1771                        );
1772                    });
1773                }
1774            })?;
1775
1776            anyhow::Ok(())
1777        })
1778        .detach_and_log_err(cx);
1779    }
1780
1781    fn show_deferred_toast(
1782        workspace: &WeakEntity<workspace::Workspace>,
1783        message: &'static str,
1784        cx: &mut App,
1785    ) {
1786        let workspace = workspace.clone();
1787        cx.defer(move |cx| {
1788            if let Some(workspace) = workspace.upgrade() {
1789                workspace.update(cx, |workspace, cx| {
1790                    struct ClipboardToast;
1791                    workspace.show_toast(
1792                        workspace::Toast::new(
1793                            workspace::notifications::NotificationId::unique::<ClipboardToast>(),
1794                            message,
1795                        )
1796                        .autohide(),
1797                        cx,
1798                    );
1799                });
1800            }
1801        });
1802    }
1803
1804    fn load_thread_from_clipboard(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1805        let Some(clipboard) = cx.read_from_clipboard() else {
1806            Self::show_deferred_toast(&self.workspace, "No clipboard content available", cx);
1807            return;
1808        };
1809
1810        let Some(encoded) = clipboard.text() else {
1811            Self::show_deferred_toast(&self.workspace, "Clipboard does not contain text", cx);
1812            return;
1813        };
1814
1815        let thread_data = match base64::Engine::decode(&base64::prelude::BASE64_STANDARD, &encoded)
1816        {
1817            Ok(data) => data,
1818            Err(_) => {
1819                Self::show_deferred_toast(
1820                    &self.workspace,
1821                    "Failed to decode clipboard content (expected base64)",
1822                    cx,
1823                );
1824                return;
1825            }
1826        };
1827
1828        let shared_thread = match SharedThread::from_bytes(&thread_data) {
1829            Ok(thread) => thread,
1830            Err(_) => {
1831                Self::show_deferred_toast(
1832                    &self.workspace,
1833                    "Failed to parse thread data from clipboard",
1834                    cx,
1835                );
1836                return;
1837            }
1838        };
1839
1840        let db_thread = shared_thread.to_db_thread();
1841        let session_id = acp::SessionId::new(uuid::Uuid::new_v4().to_string());
1842        let thread_store = self.thread_store.clone();
1843        let title = db_thread.title.clone();
1844        let workspace = self.workspace.clone();
1845
1846        cx.spawn_in(window, async move |this, cx| {
1847            thread_store
1848                .update(&mut cx.clone(), |store, cx| {
1849                    store.save_thread(session_id.clone(), db_thread, Default::default(), cx)
1850                })
1851                .await?;
1852
1853            this.update_in(cx, |this, window, cx| {
1854                this.open_thread(session_id, None, Some(title), window, cx);
1855            })?;
1856
1857            this.update_in(cx, |_, _window, cx| {
1858                if let Some(workspace) = workspace.upgrade() {
1859                    workspace.update(cx, |workspace, cx| {
1860                        struct ThreadLoadedToast;
1861                        workspace.show_toast(
1862                            workspace::Toast::new(
1863                                workspace::notifications::NotificationId::unique::<ThreadLoadedToast>(),
1864                                "Thread loaded from clipboard",
1865                            )
1866                            .autohide(),
1867                            cx,
1868                        );
1869                    });
1870                }
1871            })?;
1872
1873            anyhow::Ok(())
1874        })
1875        .detach_and_log_err(cx);
1876    }
1877
1878    fn handle_agent_configuration_event(
1879        &mut self,
1880        _entity: &Entity<AgentConfiguration>,
1881        event: &AssistantConfigurationEvent,
1882        window: &mut Window,
1883        cx: &mut Context<Self>,
1884    ) {
1885        match event {
1886            AssistantConfigurationEvent::NewThread(provider) => {
1887                if LanguageModelRegistry::read_global(cx)
1888                    .default_model()
1889                    .is_none_or(|model| model.provider.id() != provider.id())
1890                    && let Some(model) = provider.default_model(cx)
1891                {
1892                    update_settings_file(self.fs.clone(), cx, move |settings, _| {
1893                        let provider = model.provider_id().0.to_string();
1894                        let enable_thinking = model.supports_thinking();
1895                        let effort = model
1896                            .default_effort_level()
1897                            .map(|effort| effort.value.to_string());
1898                        let model = model.id().0.to_string();
1899                        settings
1900                            .agent
1901                            .get_or_insert_default()
1902                            .set_model(LanguageModelSelection {
1903                                provider: LanguageModelProviderSetting(provider),
1904                                model,
1905                                enable_thinking,
1906                                effort,
1907                            })
1908                    });
1909                }
1910
1911                self.new_thread(&NewThread, window, cx);
1912                if let Some((thread, model)) = self
1913                    .active_native_agent_thread(cx)
1914                    .zip(provider.default_model(cx))
1915                {
1916                    thread.update(cx, |thread, cx| {
1917                        thread.set_model(model, cx);
1918                    });
1919                }
1920            }
1921        }
1922    }
1923
1924    pub fn workspace_id(&self) -> Option<WorkspaceId> {
1925        self.workspace_id
1926    }
1927
1928    pub fn background_threads(&self) -> &HashMap<acp::SessionId, Entity<ConversationView>> {
1929        &self.background_threads
1930    }
1931
1932    pub fn active_conversation_view(&self) -> Option<&Entity<ConversationView>> {
1933        match &self.active_view {
1934            ActiveView::AgentThread { conversation_view } => Some(conversation_view),
1935            _ => None,
1936        }
1937    }
1938
1939    pub fn active_thread_view(&self, cx: &App) -> Option<Entity<ThreadView>> {
1940        let server_view = self.active_conversation_view()?;
1941        server_view.read(cx).active_thread().cloned()
1942    }
1943
1944    pub fn active_agent_thread(&self, cx: &App) -> Option<Entity<AcpThread>> {
1945        match &self.active_view {
1946            ActiveView::AgentThread {
1947                conversation_view, ..
1948            } => conversation_view
1949                .read(cx)
1950                .active_thread()
1951                .map(|r| r.read(cx).thread.clone()),
1952            _ => None,
1953        }
1954    }
1955
1956    /// Returns the primary thread views for all retained connections: the
1957    pub fn is_background_thread(&self, session_id: &acp::SessionId) -> bool {
1958        self.background_threads.contains_key(session_id)
1959    }
1960
1961    pub fn cancel_thread(&self, session_id: &acp::SessionId, cx: &mut Context<Self>) -> bool {
1962        let conversation_views = self
1963            .active_conversation_view()
1964            .into_iter()
1965            .chain(self.background_threads.values());
1966
1967        for conversation_view in conversation_views {
1968            if let Some(thread_view) = conversation_view.read(cx).thread_view(session_id) {
1969                thread_view.update(cx, |view, cx| view.cancel_generation(cx));
1970                return true;
1971            }
1972        }
1973        false
1974    }
1975
1976    /// active thread plus any background threads that are still running or
1977    /// completed but unseen.
1978    pub fn parent_threads(&self, cx: &App) -> Vec<Entity<ThreadView>> {
1979        let mut views = Vec::new();
1980
1981        if let Some(server_view) = self.active_conversation_view() {
1982            if let Some(thread_view) = server_view.read(cx).root_thread(cx) {
1983                views.push(thread_view);
1984            }
1985        }
1986
1987        for server_view in self.background_threads.values() {
1988            if let Some(thread_view) = server_view.read(cx).root_thread(cx) {
1989                views.push(thread_view);
1990            }
1991        }
1992
1993        views
1994    }
1995
1996    fn update_thread_work_dirs(&self, cx: &mut Context<Self>) {
1997        let new_work_dirs = self.project.read(cx).default_path_list(cx);
1998
1999        // Only update the active thread and still-running background threads.
2000        // Idle background threads have finished their work against the old
2001        // worktree set and shouldn't have their metadata rewritten.
2002        let mut root_threads: Vec<Entity<AcpThread>> = Vec::new();
2003
2004        if let Some(conversation_view) = self.active_conversation_view() {
2005            if let Some(connected) = conversation_view.read(cx).as_connected() {
2006                for thread_view in connected.threads.values() {
2007                    let thread = &thread_view.read(cx).thread;
2008                    if thread.read(cx).parent_session_id().is_none() {
2009                        root_threads.push(thread.clone());
2010                    }
2011                }
2012            }
2013        }
2014
2015        for conversation_view in self.background_threads.values() {
2016            let Some(connected) = conversation_view.read(cx).as_connected() else {
2017                continue;
2018            };
2019            for thread_view in connected.threads.values() {
2020                let thread = &thread_view.read(cx).thread;
2021                let thread_ref = thread.read(cx);
2022                if thread_ref.parent_session_id().is_some() {
2023                    continue;
2024                }
2025                if thread_ref.status() != acp_thread::ThreadStatus::Generating {
2026                    continue;
2027                }
2028                root_threads.push(thread.clone());
2029            }
2030        }
2031
2032        for thread in &root_threads {
2033            thread.update(cx, |thread, _cx| {
2034                thread.set_work_dirs(new_work_dirs.clone());
2035            });
2036        }
2037
2038        if let Some(metadata_store) =
2039            crate::thread_metadata_store::ThreadMetadataStore::try_global(cx)
2040        {
2041            metadata_store.update(cx, |store, cx| {
2042                for thread in &root_threads {
2043                    let is_archived = store
2044                        .entry(thread.read(cx).session_id())
2045                        .map(|t| t.archived)
2046                        .unwrap_or(false);
2047                    let metadata = crate::thread_metadata_store::ThreadMetadata::from_thread(
2048                        is_archived,
2049                        thread,
2050                        cx,
2051                    );
2052                    store.save(metadata, cx);
2053                }
2054            });
2055        }
2056    }
2057
2058    fn retain_running_thread(&mut self, old_view: ActiveView, cx: &mut Context<Self>) {
2059        let ActiveView::AgentThread { conversation_view } = old_view else {
2060            return;
2061        };
2062
2063        let Some(thread_view) = conversation_view.read(cx).root_thread(cx) else {
2064            return;
2065        };
2066
2067        self.background_threads
2068            .insert(thread_view.read(cx).id.clone(), conversation_view);
2069        self.cleanup_background_threads(cx);
2070    }
2071
2072    /// We keep threads that are:
2073    /// - Still running
2074    /// - Do not support reloading the full session
2075    /// - Have had the most recent events (up to 5 idle threads)
2076    fn cleanup_background_threads(&mut self, cx: &App) {
2077        let mut potential_removals = self
2078            .background_threads
2079            .iter()
2080            .filter(|(_id, view)| {
2081                let Some(thread_view) = view.read(cx).root_thread(cx) else {
2082                    return true;
2083                };
2084                let thread = thread_view.read(cx).thread.read(cx);
2085                thread.connection().supports_load_session() && thread.status() == ThreadStatus::Idle
2086            })
2087            .collect::<Vec<_>>();
2088
2089        const MAX_IDLE_BACKGROUND_THREADS: usize = 5;
2090
2091        potential_removals.sort_unstable_by_key(|(_, view)| view.read(cx).updated_at(cx));
2092        let n = potential_removals
2093            .len()
2094            .saturating_sub(MAX_IDLE_BACKGROUND_THREADS);
2095        let to_remove = potential_removals
2096            .into_iter()
2097            .map(|(id, _)| id.clone())
2098            .take(n)
2099            .collect::<Vec<_>>();
2100        for id in to_remove {
2101            self.background_threads.remove(&id);
2102        }
2103    }
2104
2105    pub(crate) fn active_native_agent_thread(&self, cx: &App) -> Option<Entity<agent::Thread>> {
2106        match &self.active_view {
2107            ActiveView::AgentThread {
2108                conversation_view, ..
2109            } => conversation_view.read(cx).as_native_thread(cx),
2110            _ => None,
2111        }
2112    }
2113
2114    pub(crate) fn active_text_thread_editor(&self) -> Option<Entity<TextThreadEditor>> {
2115        match &self.active_view {
2116            ActiveView::TextThread {
2117                text_thread_editor, ..
2118            } => Some(text_thread_editor.clone()),
2119            _ => None,
2120        }
2121    }
2122
2123    fn set_active_view(
2124        &mut self,
2125        new_view: ActiveView,
2126        focus: bool,
2127        window: &mut Window,
2128        cx: &mut Context<Self>,
2129    ) {
2130        let was_in_agent_history = matches!(
2131            self.active_view,
2132            ActiveView::History {
2133                history: History::AgentThreads { .. }
2134            }
2135        );
2136        let current_is_uninitialized = matches!(self.active_view, ActiveView::Uninitialized);
2137        let current_is_history = matches!(self.active_view, ActiveView::History { .. });
2138        let new_is_history = matches!(new_view, ActiveView::History { .. });
2139
2140        let current_is_config = matches!(self.active_view, ActiveView::Configuration);
2141        let new_is_config = matches!(new_view, ActiveView::Configuration);
2142
2143        let current_is_overlay = current_is_history || current_is_config;
2144        let new_is_overlay = new_is_history || new_is_config;
2145
2146        if current_is_uninitialized || (current_is_overlay && !new_is_overlay) {
2147            self.active_view = new_view;
2148        } else if !current_is_overlay && new_is_overlay {
2149            self.previous_view = Some(std::mem::replace(&mut self.active_view, new_view));
2150        } else {
2151            let old_view = std::mem::replace(&mut self.active_view, new_view);
2152            if !new_is_overlay {
2153                if let Some(previous) = self.previous_view.take() {
2154                    self.retain_running_thread(previous, cx);
2155                }
2156            }
2157            self.retain_running_thread(old_view, cx);
2158        }
2159
2160        // Subscribe to the active ThreadView's events (e.g. FirstSendRequested)
2161        // so the panel can intercept the first send for worktree creation.
2162        // Re-subscribe whenever the ConnectionView changes, since the inner
2163        // ThreadView may have been replaced (e.g. navigating between threads).
2164        self._active_view_observation = match &self.active_view {
2165            ActiveView::AgentThread { conversation_view } => {
2166                self._thread_view_subscription =
2167                    Self::subscribe_to_active_thread_view(conversation_view, window, cx);
2168                let focus_handle = conversation_view.focus_handle(cx);
2169                self._active_thread_focus_subscription =
2170                    Some(cx.on_focus_in(&focus_handle, window, |_this, _window, cx| {
2171                        cx.emit(AgentPanelEvent::ThreadFocused);
2172                        cx.notify();
2173                    }));
2174                Some(cx.observe_in(
2175                    conversation_view,
2176                    window,
2177                    |this, server_view, window, cx| {
2178                        this._thread_view_subscription =
2179                            Self::subscribe_to_active_thread_view(&server_view, window, cx);
2180                        cx.emit(AgentPanelEvent::ActiveViewChanged);
2181                        this.serialize(cx);
2182                        cx.notify();
2183                    },
2184                ))
2185            }
2186            _ => {
2187                self._thread_view_subscription = None;
2188                self._active_thread_focus_subscription = None;
2189                None
2190            }
2191        };
2192
2193        if let ActiveView::History { history } = &self.active_view {
2194            if !was_in_agent_history && let History::AgentThreads { view } = history {
2195                view.update(cx, |view, cx| {
2196                    view.history()
2197                        .update(cx, |history, cx| history.refresh_full_history(cx))
2198                });
2199            }
2200        }
2201
2202        if focus {
2203            self.focus_handle(cx).focus(window, cx);
2204        }
2205        cx.emit(AgentPanelEvent::ActiveViewChanged);
2206    }
2207
2208    fn populate_recently_updated_menu_section(
2209        mut menu: ContextMenu,
2210        panel: Entity<Self>,
2211        history: History,
2212        cx: &mut Context<ContextMenu>,
2213    ) -> ContextMenu {
2214        match history {
2215            History::AgentThreads { view } => {
2216                let entries = view
2217                    .read(cx)
2218                    .history()
2219                    .read(cx)
2220                    .sessions()
2221                    .iter()
2222                    .take(RECENTLY_UPDATED_MENU_LIMIT)
2223                    .cloned()
2224                    .collect::<Vec<_>>();
2225
2226                if entries.is_empty() {
2227                    return menu;
2228                }
2229
2230                menu = menu.header("Recently Updated");
2231
2232                for entry in entries {
2233                    let title = entry
2234                        .title
2235                        .as_ref()
2236                        .filter(|title| !title.is_empty())
2237                        .cloned()
2238                        .unwrap_or_else(|| SharedString::new_static(DEFAULT_THREAD_TITLE));
2239
2240                    menu = menu.entry(title, None, {
2241                        let panel = panel.downgrade();
2242                        let entry = entry.clone();
2243                        move |window, cx| {
2244                            let entry = entry.clone();
2245                            panel
2246                                .update(cx, move |this, cx| {
2247                                    if let Some(agent) = this.selected_agent() {
2248                                        this.load_agent_thread(
2249                                            agent,
2250                                            entry.session_id.clone(),
2251                                            entry.work_dirs.clone(),
2252                                            entry.title.clone(),
2253                                            true,
2254                                            window,
2255                                            cx,
2256                                        );
2257                                    }
2258                                })
2259                                .ok();
2260                        }
2261                    });
2262                }
2263            }
2264            History::TextThreads => {
2265                let entries = panel
2266                    .read(cx)
2267                    .text_thread_store
2268                    .read(cx)
2269                    .ordered_text_threads()
2270                    .take(RECENTLY_UPDATED_MENU_LIMIT)
2271                    .cloned()
2272                    .collect::<Vec<_>>();
2273
2274                if entries.is_empty() {
2275                    return menu;
2276                }
2277
2278                menu = menu.header("Recent Text Threads");
2279
2280                for entry in entries {
2281                    let title = if entry.title.is_empty() {
2282                        SharedString::new_static(DEFAULT_THREAD_TITLE)
2283                    } else {
2284                        entry.title.clone()
2285                    };
2286
2287                    menu = menu.entry(title, None, {
2288                        let panel = panel.downgrade();
2289                        let entry = entry.clone();
2290                        move |window, cx| {
2291                            let path = entry.path.clone();
2292                            panel
2293                                .update(cx, move |this, cx| {
2294                                    this.open_saved_text_thread(path.clone(), window, cx)
2295                                        .detach_and_log_err(cx);
2296                                })
2297                                .ok();
2298                        }
2299                    });
2300                }
2301            }
2302        }
2303
2304        menu.separator()
2305    }
2306
2307    fn subscribe_to_active_thread_view(
2308        server_view: &Entity<ConversationView>,
2309        window: &mut Window,
2310        cx: &mut Context<Self>,
2311    ) -> Option<Subscription> {
2312        server_view.read(cx).active_thread().cloned().map(|tv| {
2313            cx.subscribe_in(
2314                &tv,
2315                window,
2316                |this, view, event: &AcpThreadViewEvent, window, cx| match event {
2317                    AcpThreadViewEvent::FirstSendRequested { content } => {
2318                        this.handle_first_send_requested(view.clone(), content.clone(), window, cx);
2319                    }
2320                    AcpThreadViewEvent::MessageSentOrQueued => {
2321                        let session_id = view.read(cx).thread.read(cx).session_id().clone();
2322                        cx.emit(AgentPanelEvent::MessageSentOrQueued { session_id });
2323                    }
2324                },
2325            )
2326        })
2327    }
2328
2329    pub fn start_thread_in(&self) -> &StartThreadIn {
2330        &self.start_thread_in
2331    }
2332
2333    fn set_start_thread_in(
2334        &mut self,
2335        action: &StartThreadIn,
2336        window: &mut Window,
2337        cx: &mut Context<Self>,
2338    ) {
2339        if matches!(action, StartThreadIn::NewWorktree) && !cx.has_flag::<AgentV2FeatureFlag>() {
2340            return;
2341        }
2342
2343        let new_target = match *action {
2344            StartThreadIn::LocalProject => StartThreadIn::LocalProject,
2345            StartThreadIn::NewWorktree => {
2346                if !self.project_has_git_repository(cx) {
2347                    log::error!(
2348                        "set_start_thread_in: cannot use NewWorktree without a git repository"
2349                    );
2350                    return;
2351                }
2352                if self.project.read(cx).is_via_collab() {
2353                    log::error!("set_start_thread_in: cannot use NewWorktree in a collab project");
2354                    return;
2355                }
2356                StartThreadIn::NewWorktree
2357            }
2358        };
2359        self.start_thread_in = new_target;
2360        if let Some(thread) = self.active_thread_view(cx) {
2361            thread.update(cx, |thread, cx| thread.focus_handle(cx).focus(window, cx));
2362        }
2363        self.serialize(cx);
2364        cx.notify();
2365    }
2366
2367    fn cycle_start_thread_in(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2368        let next = match self.start_thread_in {
2369            StartThreadIn::LocalProject => StartThreadIn::NewWorktree,
2370            StartThreadIn::NewWorktree => StartThreadIn::LocalProject,
2371        };
2372        self.set_start_thread_in(&next, window, cx);
2373    }
2374
2375    fn reset_start_thread_in_to_default(&mut self, cx: &mut Context<Self>) {
2376        use settings::{NewThreadLocation, Settings};
2377        let default = AgentSettings::get_global(cx).new_thread_location;
2378        let start_thread_in = match default {
2379            NewThreadLocation::LocalProject => StartThreadIn::LocalProject,
2380            NewThreadLocation::NewWorktree => {
2381                if self.project_has_git_repository(cx) {
2382                    StartThreadIn::NewWorktree
2383                } else {
2384                    StartThreadIn::LocalProject
2385                }
2386            }
2387        };
2388        if self.start_thread_in != start_thread_in {
2389            self.start_thread_in = start_thread_in;
2390            self.serialize(cx);
2391            cx.notify();
2392        }
2393    }
2394
2395    pub(crate) fn selected_agent(&self) -> Option<Agent> {
2396        match &self.selected_agent_type {
2397            AgentType::NativeAgent => Some(Agent::NativeAgent),
2398            AgentType::Custom { id } => Some(Agent::Custom { id: id.clone() }),
2399            AgentType::TextThread => None,
2400        }
2401    }
2402
2403    fn sync_agent_servers_from_extensions(&mut self, cx: &mut Context<Self>) {
2404        if let Some(extension_store) = ExtensionStore::try_global(cx) {
2405            let (manifests, extensions_dir) = {
2406                let store = extension_store.read(cx);
2407                let installed = store.installed_extensions();
2408                let manifests: Vec<_> = installed
2409                    .iter()
2410                    .map(|(id, entry)| (id.clone(), entry.manifest.clone()))
2411                    .collect();
2412                let extensions_dir = paths::extensions_dir().join("installed");
2413                (manifests, extensions_dir)
2414            };
2415
2416            self.project.update(cx, |project, cx| {
2417                project.agent_server_store().update(cx, |store, cx| {
2418                    let manifest_refs: Vec<_> = manifests
2419                        .iter()
2420                        .map(|(id, manifest)| (id.as_ref(), manifest.as_ref()))
2421                        .collect();
2422                    store.sync_extension_agents(manifest_refs, extensions_dir, cx);
2423                });
2424            });
2425        }
2426    }
2427
2428    pub fn new_agent_thread_with_external_source_prompt(
2429        &mut self,
2430        external_source_prompt: Option<ExternalSourcePrompt>,
2431        window: &mut Window,
2432        cx: &mut Context<Self>,
2433    ) {
2434        self.external_thread(
2435            None,
2436            None,
2437            None,
2438            None,
2439            external_source_prompt.map(AgentInitialContent::from),
2440            true,
2441            window,
2442            cx,
2443        );
2444    }
2445
2446    pub fn new_agent_thread(
2447        &mut self,
2448        agent: AgentType,
2449        window: &mut Window,
2450        cx: &mut Context<Self>,
2451    ) {
2452        self.reset_start_thread_in_to_default(cx);
2453        self.new_agent_thread_inner(agent, true, window, cx);
2454    }
2455
2456    fn new_agent_thread_inner(
2457        &mut self,
2458        agent: AgentType,
2459        focus: bool,
2460        window: &mut Window,
2461        cx: &mut Context<Self>,
2462    ) {
2463        match agent {
2464            AgentType::TextThread => {
2465                window.dispatch_action(NewTextThread.boxed_clone(), cx);
2466            }
2467            AgentType::NativeAgent => self.external_thread(
2468                Some(crate::Agent::NativeAgent),
2469                None,
2470                None,
2471                None,
2472                None,
2473                focus,
2474                window,
2475                cx,
2476            ),
2477            AgentType::Custom { id } => self.external_thread(
2478                Some(crate::Agent::Custom { id }),
2479                None,
2480                None,
2481                None,
2482                None,
2483                focus,
2484                window,
2485                cx,
2486            ),
2487        }
2488    }
2489
2490    pub fn load_agent_thread(
2491        &mut self,
2492        agent: Agent,
2493        session_id: acp::SessionId,
2494        work_dirs: Option<PathList>,
2495        title: Option<SharedString>,
2496        focus: bool,
2497        window: &mut Window,
2498        cx: &mut Context<Self>,
2499    ) {
2500        if let Some(conversation_view) = self.background_threads.remove(&session_id) {
2501            self.set_active_view(
2502                ActiveView::AgentThread { conversation_view },
2503                focus,
2504                window,
2505                cx,
2506            );
2507            return;
2508        }
2509
2510        if let ActiveView::AgentThread { conversation_view } = &self.active_view {
2511            if conversation_view
2512                .read(cx)
2513                .active_thread()
2514                .map(|t| t.read(cx).id.clone())
2515                == Some(session_id.clone())
2516            {
2517                cx.emit(AgentPanelEvent::ActiveViewChanged);
2518                return;
2519            }
2520        }
2521
2522        if let Some(ActiveView::AgentThread { conversation_view }) = &self.previous_view {
2523            if conversation_view
2524                .read(cx)
2525                .active_thread()
2526                .map(|t| t.read(cx).id.clone())
2527                == Some(session_id.clone())
2528            {
2529                let view = self.previous_view.take().unwrap();
2530                self.set_active_view(view, focus, window, cx);
2531                return;
2532            }
2533        }
2534
2535        self.external_thread(
2536            Some(agent),
2537            Some(session_id),
2538            work_dirs,
2539            title,
2540            None,
2541            focus,
2542            window,
2543            cx,
2544        );
2545    }
2546
2547    pub(crate) fn create_agent_thread(
2548        &mut self,
2549        server: Rc<dyn AgentServer>,
2550        resume_session_id: Option<acp::SessionId>,
2551        work_dirs: Option<PathList>,
2552        title: Option<SharedString>,
2553        initial_content: Option<AgentInitialContent>,
2554        workspace: WeakEntity<Workspace>,
2555        project: Entity<Project>,
2556        ext_agent: Agent,
2557        focus: bool,
2558        window: &mut Window,
2559        cx: &mut Context<Self>,
2560    ) {
2561        let selected_agent = AgentType::from(ext_agent.clone());
2562        if self.selected_agent_type != selected_agent {
2563            self.selected_agent_type = selected_agent;
2564            self.serialize(cx);
2565        }
2566        let thread_store = server
2567            .clone()
2568            .downcast::<agent::NativeAgentServer>()
2569            .is_some()
2570            .then(|| self.thread_store.clone());
2571
2572        let connection_store = self.connection_store.clone();
2573
2574        let conversation_view = cx.new(|cx| {
2575            crate::ConversationView::new(
2576                server,
2577                connection_store,
2578                ext_agent,
2579                resume_session_id,
2580                work_dirs,
2581                title,
2582                initial_content,
2583                workspace.clone(),
2584                project,
2585                thread_store,
2586                self.prompt_store.clone(),
2587                window,
2588                cx,
2589            )
2590        });
2591
2592        cx.observe(&conversation_view, |this, server_view, cx| {
2593            let is_active = this
2594                .active_conversation_view()
2595                .is_some_and(|active| active.entity_id() == server_view.entity_id());
2596            if is_active {
2597                cx.emit(AgentPanelEvent::ActiveViewChanged);
2598                this.serialize(cx);
2599            } else {
2600                cx.emit(AgentPanelEvent::BackgroundThreadChanged);
2601            }
2602            cx.notify();
2603        })
2604        .detach();
2605
2606        self.set_active_view(
2607            ActiveView::AgentThread { conversation_view },
2608            focus,
2609            window,
2610            cx,
2611        );
2612    }
2613
2614    fn active_thread_has_messages(&self, cx: &App) -> bool {
2615        self.active_agent_thread(cx)
2616            .is_some_and(|thread| !thread.read(cx).entries().is_empty())
2617    }
2618
2619    pub fn active_thread_is_draft(&self, cx: &App) -> bool {
2620        self.active_conversation_view().is_some() && !self.active_thread_has_messages(cx)
2621    }
2622
2623    fn handle_first_send_requested(
2624        &mut self,
2625        thread_view: Entity<ThreadView>,
2626        content: Vec<acp::ContentBlock>,
2627        window: &mut Window,
2628        cx: &mut Context<Self>,
2629    ) {
2630        if self.start_thread_in == StartThreadIn::NewWorktree {
2631            self.handle_worktree_creation_requested(content, window, cx);
2632        } else {
2633            cx.defer_in(window, move |_this, window, cx| {
2634                thread_view.update(cx, |thread_view, cx| {
2635                    let editor = thread_view.message_editor.clone();
2636                    thread_view.send_impl(editor, window, cx);
2637                });
2638            });
2639        }
2640    }
2641
2642    // TODO: The mapping from workspace root paths to git repositories needs a
2643    // unified approach across the codebase: this method, `sidebar::is_root_repo`,
2644    // thread persistence (which PathList is saved to the database), and thread
2645    // querying (which PathList is used to read threads back). All of these need
2646    // to agree on how repos are resolved for a given workspace, especially in
2647    // multi-root and nested-repo configurations.
2648    /// Partitions the project's visible worktrees into git-backed repositories
2649    /// and plain (non-git) paths. Git repos will have worktrees created for
2650    /// them; non-git paths are carried over to the new workspace as-is.
2651    ///
2652    /// When multiple worktrees map to the same repository, the most specific
2653    /// match wins (deepest work directory path), with a deterministic
2654    /// tie-break on entity id. Each repository appears at most once.
2655    fn classify_worktrees(
2656        &self,
2657        cx: &App,
2658    ) -> (Vec<Entity<project::git_store::Repository>>, Vec<PathBuf>) {
2659        let project = &self.project;
2660        let repositories = project.read(cx).repositories(cx).clone();
2661        let mut git_repos: Vec<Entity<project::git_store::Repository>> = Vec::new();
2662        let mut non_git_paths: Vec<PathBuf> = Vec::new();
2663        let mut seen_repo_ids = std::collections::HashSet::new();
2664
2665        for worktree in project.read(cx).visible_worktrees(cx) {
2666            let wt_path = worktree.read(cx).abs_path();
2667
2668            let matching_repo = repositories
2669                .iter()
2670                .filter_map(|(id, repo)| {
2671                    let work_dir = repo.read(cx).work_directory_abs_path.clone();
2672                    if wt_path.starts_with(work_dir.as_ref())
2673                        || work_dir.starts_with(wt_path.as_ref())
2674                    {
2675                        Some((*id, repo.clone(), work_dir.as_ref().components().count()))
2676                    } else {
2677                        None
2678                    }
2679                })
2680                .max_by(
2681                    |(left_id, _left_repo, left_depth), (right_id, _right_repo, right_depth)| {
2682                        left_depth
2683                            .cmp(right_depth)
2684                            .then_with(|| left_id.cmp(right_id))
2685                    },
2686                );
2687
2688            if let Some((id, repo, _)) = matching_repo {
2689                if seen_repo_ids.insert(id) {
2690                    git_repos.push(repo);
2691                }
2692            } else {
2693                non_git_paths.push(wt_path.to_path_buf());
2694            }
2695        }
2696
2697        (git_repos, non_git_paths)
2698    }
2699
2700    /// Kicks off an async git-worktree creation for each repository. Returns:
2701    ///
2702    /// - `creation_infos`: a vec of `(repo, new_path, receiver)` tuples—the
2703    ///   receiver resolves once the git worktree command finishes.
2704    /// - `path_remapping`: `(old_work_dir, new_worktree_path)` pairs used
2705    ///   later to remap open editor tabs into the new workspace.
2706    fn start_worktree_creations(
2707        git_repos: &[Entity<project::git_store::Repository>],
2708        branch_name: &str,
2709        worktree_directory_setting: &str,
2710        cx: &mut Context<Self>,
2711    ) -> Result<(
2712        Vec<(
2713            Entity<project::git_store::Repository>,
2714            PathBuf,
2715            futures::channel::oneshot::Receiver<Result<()>>,
2716        )>,
2717        Vec<(PathBuf, PathBuf)>,
2718    )> {
2719        let mut creation_infos = Vec::new();
2720        let mut path_remapping = Vec::new();
2721
2722        for repo in git_repos {
2723            let (work_dir, new_path, receiver) = repo.update(cx, |repo, _cx| {
2724                let new_path =
2725                    repo.path_for_new_linked_worktree(branch_name, worktree_directory_setting)?;
2726                let receiver =
2727                    repo.create_worktree(branch_name.to_string(), new_path.clone(), None);
2728                let work_dir = repo.work_directory_abs_path.clone();
2729                anyhow::Ok((work_dir, new_path, receiver))
2730            })?;
2731            path_remapping.push((work_dir.to_path_buf(), new_path.clone()));
2732            creation_infos.push((repo.clone(), new_path, receiver));
2733        }
2734
2735        Ok((creation_infos, path_remapping))
2736    }
2737
2738    /// Waits for every in-flight worktree creation to complete. If any
2739    /// creation fails, all successfully-created worktrees are rolled back
2740    /// (removed) so the project isn't left in a half-migrated state.
2741    async fn await_and_rollback_on_failure(
2742        creation_infos: Vec<(
2743            Entity<project::git_store::Repository>,
2744            PathBuf,
2745            futures::channel::oneshot::Receiver<Result<()>>,
2746        )>,
2747        cx: &mut AsyncWindowContext,
2748    ) -> Result<Vec<PathBuf>> {
2749        let mut created_paths: Vec<PathBuf> = Vec::new();
2750        let mut repos_and_paths: Vec<(Entity<project::git_store::Repository>, PathBuf)> =
2751            Vec::new();
2752        let mut first_error: Option<anyhow::Error> = None;
2753
2754        for (repo, new_path, receiver) in creation_infos {
2755            match receiver.await {
2756                Ok(Ok(())) => {
2757                    created_paths.push(new_path.clone());
2758                    repos_and_paths.push((repo, new_path));
2759                }
2760                Ok(Err(err)) => {
2761                    if first_error.is_none() {
2762                        first_error = Some(err);
2763                    }
2764                }
2765                Err(_canceled) => {
2766                    if first_error.is_none() {
2767                        first_error = Some(anyhow!("Worktree creation was canceled"));
2768                    }
2769                }
2770            }
2771        }
2772
2773        let Some(err) = first_error else {
2774            return Ok(created_paths);
2775        };
2776
2777        // Rollback all successfully created worktrees
2778        let mut rollback_receivers = Vec::new();
2779        for (rollback_repo, rollback_path) in &repos_and_paths {
2780            if let Ok(receiver) = cx.update(|_, cx| {
2781                rollback_repo.update(cx, |repo, _cx| {
2782                    repo.remove_worktree(rollback_path.clone(), true)
2783                })
2784            }) {
2785                rollback_receivers.push((rollback_path.clone(), receiver));
2786            }
2787        }
2788        let mut rollback_failures: Vec<String> = Vec::new();
2789        for (path, receiver) in rollback_receivers {
2790            match receiver.await {
2791                Ok(Ok(())) => {}
2792                Ok(Err(rollback_err)) => {
2793                    log::error!(
2794                        "failed to rollback worktree at {}: {rollback_err}",
2795                        path.display()
2796                    );
2797                    rollback_failures.push(format!("{}: {rollback_err}", path.display()));
2798                }
2799                Err(rollback_err) => {
2800                    log::error!(
2801                        "failed to rollback worktree at {}: {rollback_err}",
2802                        path.display()
2803                    );
2804                    rollback_failures.push(format!("{}: {rollback_err}", path.display()));
2805                }
2806            }
2807        }
2808        let mut error_message = format!("Failed to create worktree: {err}");
2809        if !rollback_failures.is_empty() {
2810            error_message.push_str("\n\nFailed to clean up: ");
2811            error_message.push_str(&rollback_failures.join(", "));
2812        }
2813        Err(anyhow!(error_message))
2814    }
2815
2816    fn set_worktree_creation_error(
2817        &mut self,
2818        message: SharedString,
2819        window: &mut Window,
2820        cx: &mut Context<Self>,
2821    ) {
2822        self.worktree_creation_status = Some(WorktreeCreationStatus::Error(message));
2823        if matches!(self.active_view, ActiveView::Uninitialized) {
2824            let selected_agent_type = self.selected_agent_type.clone();
2825            self.new_agent_thread(selected_agent_type, window, cx);
2826        }
2827        cx.notify();
2828    }
2829
2830    fn handle_worktree_creation_requested(
2831        &mut self,
2832        content: Vec<acp::ContentBlock>,
2833        window: &mut Window,
2834        cx: &mut Context<Self>,
2835    ) {
2836        if matches!(
2837            self.worktree_creation_status,
2838            Some(WorktreeCreationStatus::Creating)
2839        ) {
2840            return;
2841        }
2842
2843        self.worktree_creation_status = Some(WorktreeCreationStatus::Creating);
2844        cx.notify();
2845
2846        let (git_repos, non_git_paths) = self.classify_worktrees(cx);
2847
2848        if git_repos.is_empty() {
2849            self.set_worktree_creation_error(
2850                "No git repositories found in the project".into(),
2851                window,
2852                cx,
2853            );
2854            return;
2855        }
2856
2857        // Kick off branch listing as early as possible so it can run
2858        // concurrently with the remaining synchronous setup work.
2859        let branch_receivers: Vec<_> = git_repos
2860            .iter()
2861            .map(|repo| repo.update(cx, |repo, _cx| repo.branches()))
2862            .collect();
2863
2864        let worktree_directory_setting = ProjectSettings::get_global(cx)
2865            .git
2866            .worktree_directory
2867            .clone();
2868
2869        let active_file_path = self.workspace.upgrade().and_then(|workspace| {
2870            let workspace = workspace.read(cx);
2871            let active_item = workspace.active_item(cx)?;
2872            let project_path = active_item.project_path(cx)?;
2873            workspace
2874                .project()
2875                .read(cx)
2876                .absolute_path(&project_path, cx)
2877        });
2878
2879        let workspace = self.workspace.clone();
2880        let window_handle = window
2881            .window_handle()
2882            .downcast::<workspace::MultiWorkspace>();
2883
2884        let selected_agent = self.selected_agent();
2885
2886        let task = cx.spawn_in(window, async move |this, cx| {
2887            // Await the branch listings we kicked off earlier.
2888            let mut existing_branches = Vec::new();
2889            for result in futures::future::join_all(branch_receivers).await {
2890                match result {
2891                    Ok(Ok(branches)) => {
2892                        for branch in branches {
2893                            existing_branches.push(branch.name().to_string());
2894                        }
2895                    }
2896                    Ok(Err(err)) => {
2897                        Err::<(), _>(err).log_err();
2898                    }
2899                    Err(_) => {}
2900                }
2901            }
2902
2903            let existing_branch_refs: Vec<&str> =
2904                existing_branches.iter().map(|s| s.as_str()).collect();
2905            let mut rng = rand::rng();
2906            let branch_name =
2907                match crate::branch_names::generate_branch_name(&existing_branch_refs, &mut rng) {
2908                    Some(name) => name,
2909                    None => {
2910                        this.update_in(cx, |this, window, cx| {
2911                            this.set_worktree_creation_error(
2912                                "Failed to generate a unique branch name".into(),
2913                                window,
2914                                cx,
2915                            );
2916                        })?;
2917                        return anyhow::Ok(());
2918                    }
2919                };
2920
2921            let (creation_infos, path_remapping) = match this.update_in(cx, |_this, _window, cx| {
2922                Self::start_worktree_creations(
2923                    &git_repos,
2924                    &branch_name,
2925                    &worktree_directory_setting,
2926                    cx,
2927                )
2928            }) {
2929                Ok(Ok(result)) => result,
2930                Ok(Err(err)) | Err(err) => {
2931                    this.update_in(cx, |this, window, cx| {
2932                        this.set_worktree_creation_error(
2933                            format!("Failed to validate worktree directory: {err}").into(),
2934                            window,
2935                            cx,
2936                        );
2937                    })
2938                    .log_err();
2939                    return anyhow::Ok(());
2940                }
2941            };
2942
2943            let created_paths = match Self::await_and_rollback_on_failure(creation_infos, cx).await
2944            {
2945                Ok(paths) => paths,
2946                Err(err) => {
2947                    this.update_in(cx, |this, window, cx| {
2948                        this.set_worktree_creation_error(format!("{err}").into(), window, cx);
2949                    })?;
2950                    return anyhow::Ok(());
2951                }
2952            };
2953
2954            let mut all_paths = created_paths;
2955            let has_non_git = !non_git_paths.is_empty();
2956            all_paths.extend(non_git_paths.iter().cloned());
2957
2958            let app_state = match workspace.upgrade() {
2959                Some(workspace) => cx.update(|_, cx| workspace.read(cx).app_state().clone())?,
2960                None => {
2961                    this.update_in(cx, |this, window, cx| {
2962                        this.set_worktree_creation_error(
2963                            "Workspace no longer available".into(),
2964                            window,
2965                            cx,
2966                        );
2967                    })?;
2968                    return anyhow::Ok(());
2969                }
2970            };
2971
2972            let this_for_error = this.clone();
2973            if let Err(err) = Self::setup_new_workspace(
2974                this,
2975                all_paths,
2976                app_state,
2977                window_handle,
2978                active_file_path,
2979                path_remapping,
2980                non_git_paths,
2981                has_non_git,
2982                content,
2983                selected_agent,
2984                cx,
2985            )
2986            .await
2987            {
2988                this_for_error
2989                    .update_in(cx, |this, window, cx| {
2990                        this.set_worktree_creation_error(
2991                            format!("Failed to set up workspace: {err}").into(),
2992                            window,
2993                            cx,
2994                        );
2995                    })
2996                    .log_err();
2997            }
2998            anyhow::Ok(())
2999        });
3000
3001        self._worktree_creation_task = Some(cx.foreground_executor().spawn(async move {
3002            task.await.log_err();
3003        }));
3004    }
3005
3006    async fn setup_new_workspace(
3007        this: WeakEntity<Self>,
3008        all_paths: Vec<PathBuf>,
3009        app_state: Arc<workspace::AppState>,
3010        window_handle: Option<gpui::WindowHandle<workspace::MultiWorkspace>>,
3011        active_file_path: Option<PathBuf>,
3012        path_remapping: Vec<(PathBuf, PathBuf)>,
3013        non_git_paths: Vec<PathBuf>,
3014        has_non_git: bool,
3015        content: Vec<acp::ContentBlock>,
3016        selected_agent: Option<Agent>,
3017        cx: &mut AsyncWindowContext,
3018    ) -> Result<()> {
3019        let OpenResult {
3020            window: new_window_handle,
3021            workspace: new_workspace,
3022            ..
3023        } = cx
3024            .update(|_window, cx| {
3025                Workspace::new_local(
3026                    all_paths,
3027                    app_state,
3028                    window_handle,
3029                    None,
3030                    None,
3031                    OpenMode::Add,
3032                    cx,
3033                )
3034            })?
3035            .await?;
3036
3037        let panels_task = new_workspace.update(cx, |workspace, _cx| workspace.take_panels_task());
3038
3039        if let Some(task) = panels_task {
3040            task.await.log_err();
3041        }
3042
3043        new_workspace
3044            .update(cx, |workspace, cx| {
3045                workspace.project().read(cx).wait_for_initial_scan(cx)
3046            })
3047            .await;
3048
3049        new_workspace
3050            .update(cx, |workspace, cx| {
3051                let repos = workspace
3052                    .project()
3053                    .read(cx)
3054                    .repositories(cx)
3055                    .values()
3056                    .cloned()
3057                    .collect::<Vec<_>>();
3058
3059                let tasks = repos
3060                    .into_iter()
3061                    .map(|repo| repo.update(cx, |repo, _| repo.barrier()));
3062                futures::future::join_all(tasks)
3063            })
3064            .await;
3065
3066        let initial_content = AgentInitialContent::ContentBlock {
3067            blocks: content,
3068            auto_submit: true,
3069        };
3070
3071        new_window_handle.update(cx, |_multi_workspace, window, cx| {
3072            new_workspace.update(cx, |workspace, cx| {
3073                if has_non_git {
3074                    let toast_id = workspace::notifications::NotificationId::unique::<AgentPanel>();
3075                    workspace.show_toast(
3076                        workspace::Toast::new(
3077                            toast_id,
3078                            "Some project folders are not git repositories. \
3079                             They were included as-is without creating a worktree.",
3080                        ),
3081                        cx,
3082                    );
3083                }
3084
3085                // If we had an active buffer, remap its path and reopen it.
3086                let had_active_file = active_file_path.is_some();
3087                let remapped_active_path = active_file_path.and_then(|original_path| {
3088                    let best_match = path_remapping
3089                        .iter()
3090                        .filter_map(|(old_root, new_root)| {
3091                            original_path.strip_prefix(old_root).ok().map(|relative| {
3092                                (old_root.components().count(), new_root.join(relative))
3093                            })
3094                        })
3095                        .max_by_key(|(depth, _)| *depth);
3096
3097                    if let Some((_, remapped_path)) = best_match {
3098                        return Some(remapped_path);
3099                    }
3100
3101                    for non_git in &non_git_paths {
3102                        if original_path.starts_with(non_git) {
3103                            return Some(original_path);
3104                        }
3105                    }
3106                    None
3107                });
3108
3109                if had_active_file && remapped_active_path.is_none() {
3110                    log::warn!(
3111                        "Active file could not be remapped to the new worktree; it will not be reopened"
3112                    );
3113                }
3114
3115                if let Some(path) = remapped_active_path {
3116                    let open_task = workspace.open_paths(
3117                        vec![path],
3118                        workspace::OpenOptions::default(),
3119                        None,
3120                        window,
3121                        cx,
3122                    );
3123                    cx.spawn(async move |_, _| -> anyhow::Result<()> {
3124                        for item in open_task.await.into_iter().flatten() {
3125                            item?;
3126                        }
3127                        Ok(())
3128                    })
3129                    .detach_and_log_err(cx);
3130                }
3131
3132                workspace.focus_panel::<AgentPanel>(window, cx);
3133
3134                // If no active buffer was open, zoom the agent panel
3135                // (equivalent to cmd-esc fullscreen behavior).
3136                // This must happen after focus_panel, which activates
3137                // and opens the panel in the dock.
3138
3139                if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
3140                    panel.update(cx, |panel, cx| {
3141                        panel.external_thread(
3142                            selected_agent,
3143                            None,
3144                            None,
3145                            None,
3146                            Some(initial_content),
3147                            true,
3148                            window,
3149                            cx,
3150                        );
3151                    });
3152                }
3153            });
3154        })?;
3155
3156        new_window_handle.update(cx, |multi_workspace, window, cx| {
3157            multi_workspace.activate(new_workspace.clone(), window, cx);
3158        })?;
3159
3160        this.update_in(cx, |this, window, cx| {
3161            this.worktree_creation_status = None;
3162
3163            if let Some(thread_view) = this.active_thread_view(cx) {
3164                thread_view.update(cx, |thread_view, cx| {
3165                    thread_view
3166                        .message_editor
3167                        .update(cx, |editor, cx| editor.clear(window, cx));
3168                });
3169            }
3170
3171            cx.notify();
3172        })?;
3173
3174        anyhow::Ok(())
3175    }
3176}
3177
3178impl Focusable for AgentPanel {
3179    fn focus_handle(&self, cx: &App) -> FocusHandle {
3180        match &self.active_view {
3181            ActiveView::Uninitialized => self.focus_handle.clone(),
3182            ActiveView::AgentThread {
3183                conversation_view, ..
3184            } => conversation_view.focus_handle(cx),
3185            ActiveView::History { history: kind } => match kind {
3186                History::AgentThreads { view } => view.read(cx).focus_handle(cx),
3187                History::TextThreads => self.text_thread_history.focus_handle(cx),
3188            },
3189            ActiveView::TextThread {
3190                text_thread_editor, ..
3191            } => text_thread_editor.focus_handle(cx),
3192            ActiveView::Configuration => {
3193                if let Some(configuration) = self.configuration.as_ref() {
3194                    configuration.focus_handle(cx)
3195                } else {
3196                    self.focus_handle.clone()
3197                }
3198            }
3199        }
3200    }
3201}
3202
3203fn agent_panel_dock_position(cx: &App) -> DockPosition {
3204    AgentSettings::get_global(cx).dock.into()
3205}
3206
3207pub enum AgentPanelEvent {
3208    ActiveViewChanged,
3209    ThreadFocused,
3210    BackgroundThreadChanged,
3211    MessageSentOrQueued { session_id: acp::SessionId },
3212}
3213
3214impl EventEmitter<PanelEvent> for AgentPanel {}
3215impl EventEmitter<AgentPanelEvent> for AgentPanel {}
3216
3217impl Panel for AgentPanel {
3218    fn persistent_name() -> &'static str {
3219        "AgentPanel"
3220    }
3221
3222    fn panel_key() -> &'static str {
3223        AGENT_PANEL_KEY
3224    }
3225
3226    fn position(&self, _window: &Window, cx: &App) -> DockPosition {
3227        agent_panel_dock_position(cx)
3228    }
3229
3230    fn position_is_valid(&self, position: DockPosition) -> bool {
3231        position != DockPosition::Bottom
3232    }
3233
3234    fn set_position(&mut self, position: DockPosition, _: &mut Window, cx: &mut Context<Self>) {
3235        settings::update_settings_file(self.fs.clone(), cx, move |settings, _| {
3236            settings
3237                .agent
3238                .get_or_insert_default()
3239                .set_dock(position.into());
3240        });
3241    }
3242
3243    fn default_size(&self, window: &Window, cx: &App) -> Pixels {
3244        let settings = AgentSettings::get_global(cx);
3245        match self.position(window, cx) {
3246            DockPosition::Left | DockPosition::Right => settings.default_width,
3247            DockPosition::Bottom => settings.default_height,
3248        }
3249    }
3250
3251    fn supports_flexible_size(&self) -> bool {
3252        true
3253    }
3254
3255    fn has_flexible_size(&self, _window: &Window, cx: &App) -> bool {
3256        AgentSettings::get_global(cx).flexible
3257    }
3258
3259    fn set_flexible_size(&mut self, flexible: bool, _window: &mut Window, cx: &mut Context<Self>) {
3260        settings::update_settings_file(self.fs.clone(), cx, move |settings, _| {
3261            settings
3262                .agent
3263                .get_or_insert_default()
3264                .set_flexible_size(flexible);
3265        });
3266    }
3267
3268    fn set_active(&mut self, active: bool, window: &mut Window, cx: &mut Context<Self>) {
3269        if active
3270            && matches!(self.active_view, ActiveView::Uninitialized)
3271            && !matches!(
3272                self.worktree_creation_status,
3273                Some(WorktreeCreationStatus::Creating)
3274            )
3275        {
3276            let selected_agent_type = self.selected_agent_type.clone();
3277            self.new_agent_thread_inner(selected_agent_type, false, window, cx);
3278        }
3279    }
3280
3281    fn remote_id() -> Option<proto::PanelId> {
3282        Some(proto::PanelId::AssistantPanel)
3283    }
3284
3285    fn icon(&self, _window: &Window, cx: &App) -> Option<IconName> {
3286        (self.enabled(cx) && AgentSettings::get_global(cx).button).then_some(IconName::ZedAssistant)
3287    }
3288
3289    fn icon_tooltip(&self, _window: &Window, _cx: &App) -> Option<&'static str> {
3290        Some("Agent Panel")
3291    }
3292
3293    fn toggle_action(&self) -> Box<dyn Action> {
3294        Box::new(ToggleFocus)
3295    }
3296
3297    fn activation_priority(&self) -> u32 {
3298        0
3299    }
3300
3301    fn enabled(&self, cx: &App) -> bool {
3302        AgentSettings::get_global(cx).enabled(cx)
3303    }
3304
3305    fn is_agent_panel(&self) -> bool {
3306        true
3307    }
3308
3309    fn is_zoomed(&self, _window: &Window, _cx: &App) -> bool {
3310        self.zoomed
3311    }
3312
3313    fn set_zoomed(&mut self, zoomed: bool, _window: &mut Window, cx: &mut Context<Self>) {
3314        self.zoomed = zoomed;
3315        cx.notify();
3316    }
3317}
3318
3319impl AgentPanel {
3320    fn render_title_view(&self, _window: &mut Window, cx: &Context<Self>) -> AnyElement {
3321        const LOADING_SUMMARY_PLACEHOLDER: &str = "Loading Summary…";
3322
3323        let content = match &self.active_view {
3324            ActiveView::AgentThread { conversation_view } => {
3325                let server_view_ref = conversation_view.read(cx);
3326                let is_generating_title = server_view_ref.as_native_thread(cx).is_some()
3327                    && server_view_ref.root_thread(cx).map_or(false, |tv| {
3328                        tv.read(cx).thread.read(cx).has_provisional_title()
3329                    });
3330
3331                if let Some(title_editor) = server_view_ref
3332                    .root_thread(cx)
3333                    .map(|r| r.read(cx).title_editor.clone())
3334                {
3335                    if is_generating_title {
3336                        Label::new(DEFAULT_THREAD_TITLE)
3337                            .color(Color::Muted)
3338                            .truncate()
3339                            .with_animation(
3340                                "generating_title",
3341                                Animation::new(Duration::from_secs(2))
3342                                    .repeat()
3343                                    .with_easing(pulsating_between(0.4, 0.8)),
3344                                |label, delta| label.alpha(delta),
3345                            )
3346                            .into_any_element()
3347                    } else {
3348                        div()
3349                            .w_full()
3350                            .on_action({
3351                                let conversation_view = conversation_view.downgrade();
3352                                move |_: &menu::Confirm, window, cx| {
3353                                    if let Some(conversation_view) = conversation_view.upgrade() {
3354                                        conversation_view.focus_handle(cx).focus(window, cx);
3355                                    }
3356                                }
3357                            })
3358                            .on_action({
3359                                let conversation_view = conversation_view.downgrade();
3360                                move |_: &editor::actions::Cancel, window, cx| {
3361                                    if let Some(conversation_view) = conversation_view.upgrade() {
3362                                        conversation_view.focus_handle(cx).focus(window, cx);
3363                                    }
3364                                }
3365                            })
3366                            .child(title_editor)
3367                            .into_any_element()
3368                    }
3369                } else {
3370                    Label::new(conversation_view.read(cx).title(cx))
3371                        .color(Color::Muted)
3372                        .truncate()
3373                        .into_any_element()
3374                }
3375            }
3376            ActiveView::TextThread {
3377                title_editor,
3378                text_thread_editor,
3379                ..
3380            } => {
3381                let summary = text_thread_editor.read(cx).text_thread().read(cx).summary();
3382
3383                match summary {
3384                    TextThreadSummary::Pending => Label::new(TextThreadSummary::DEFAULT)
3385                        .color(Color::Muted)
3386                        .truncate()
3387                        .into_any_element(),
3388                    TextThreadSummary::Content(summary) => {
3389                        if summary.done {
3390                            div()
3391                                .w_full()
3392                                .child(title_editor.clone())
3393                                .into_any_element()
3394                        } else {
3395                            Label::new(LOADING_SUMMARY_PLACEHOLDER)
3396                                .truncate()
3397                                .color(Color::Muted)
3398                                .with_animation(
3399                                    "generating_title",
3400                                    Animation::new(Duration::from_secs(2))
3401                                        .repeat()
3402                                        .with_easing(pulsating_between(0.4, 0.8)),
3403                                    |label, delta| label.alpha(delta),
3404                                )
3405                                .into_any_element()
3406                        }
3407                    }
3408                    TextThreadSummary::Error => h_flex()
3409                        .w_full()
3410                        .child(title_editor.clone())
3411                        .child(
3412                            IconButton::new("retry-summary-generation", IconName::RotateCcw)
3413                                .icon_size(IconSize::Small)
3414                                .on_click({
3415                                    let text_thread_editor = text_thread_editor.clone();
3416                                    move |_, _window, cx| {
3417                                        text_thread_editor.update(cx, |text_thread_editor, cx| {
3418                                            text_thread_editor.regenerate_summary(cx);
3419                                        });
3420                                    }
3421                                })
3422                                .tooltip(move |_window, cx| {
3423                                    cx.new(|_| {
3424                                        Tooltip::new("Failed to generate title")
3425                                            .meta("Click to try again")
3426                                    })
3427                                    .into()
3428                                }),
3429                        )
3430                        .into_any_element(),
3431                }
3432            }
3433            ActiveView::History { history: kind } => {
3434                let title = match kind {
3435                    History::AgentThreads { .. } => "History",
3436                    History::TextThreads => "Text Thread History",
3437                };
3438                Label::new(title).truncate().into_any_element()
3439            }
3440            ActiveView::Configuration => Label::new("Settings").truncate().into_any_element(),
3441            ActiveView::Uninitialized => Label::new("Agent").truncate().into_any_element(),
3442        };
3443
3444        h_flex()
3445            .key_context("TitleEditor")
3446            .id("TitleEditor")
3447            .flex_grow()
3448            .w_full()
3449            .max_w_full()
3450            .overflow_x_scroll()
3451            .child(content)
3452            .into_any()
3453    }
3454
3455    fn handle_regenerate_thread_title(conversation_view: Entity<ConversationView>, cx: &mut App) {
3456        conversation_view.update(cx, |conversation_view, cx| {
3457            if let Some(thread) = conversation_view.as_native_thread(cx) {
3458                thread.update(cx, |thread, cx| {
3459                    thread.generate_title(cx);
3460                });
3461            }
3462        });
3463    }
3464
3465    fn handle_regenerate_text_thread_title(
3466        text_thread_editor: Entity<TextThreadEditor>,
3467        cx: &mut App,
3468    ) {
3469        text_thread_editor.update(cx, |text_thread_editor, cx| {
3470            text_thread_editor.regenerate_summary(cx);
3471        });
3472    }
3473
3474    fn render_panel_options_menu(
3475        &self,
3476        window: &mut Window,
3477        cx: &mut Context<Self>,
3478    ) -> impl IntoElement {
3479        let focus_handle = self.focus_handle(cx);
3480
3481        let full_screen_label = if self.is_zoomed(window, cx) {
3482            "Disable Full Screen"
3483        } else {
3484            "Enable Full Screen"
3485        };
3486
3487        let text_thread_view = match &self.active_view {
3488            ActiveView::TextThread {
3489                text_thread_editor, ..
3490            } => Some(text_thread_editor.clone()),
3491            _ => None,
3492        };
3493        let text_thread_with_messages = match &self.active_view {
3494            ActiveView::TextThread {
3495                text_thread_editor, ..
3496            } => text_thread_editor
3497                .read(cx)
3498                .text_thread()
3499                .read(cx)
3500                .messages(cx)
3501                .any(|message| message.role == language_model::Role::Assistant),
3502            _ => false,
3503        };
3504
3505        let conversation_view = match &self.active_view {
3506            ActiveView::AgentThread { conversation_view } => Some(conversation_view.clone()),
3507            _ => None,
3508        };
3509        let thread_with_messages = match &self.active_view {
3510            ActiveView::AgentThread { conversation_view } => {
3511                conversation_view.read(cx).has_user_submitted_prompt(cx)
3512            }
3513            _ => false,
3514        };
3515        let has_auth_methods = match &self.active_view {
3516            ActiveView::AgentThread { conversation_view } => {
3517                conversation_view.read(cx).has_auth_methods()
3518            }
3519            _ => false,
3520        };
3521
3522        PopoverMenu::new("agent-options-menu")
3523            .trigger_with_tooltip(
3524                IconButton::new("agent-options-menu", IconName::Ellipsis)
3525                    .icon_size(IconSize::Small),
3526                {
3527                    let focus_handle = focus_handle.clone();
3528                    move |_window, cx| {
3529                        Tooltip::for_action_in(
3530                            "Toggle Agent Menu",
3531                            &ToggleOptionsMenu,
3532                            &focus_handle,
3533                            cx,
3534                        )
3535                    }
3536                },
3537            )
3538            .anchor(Corner::TopRight)
3539            .with_handle(self.agent_panel_menu_handle.clone())
3540            .menu({
3541                move |window, cx| {
3542                    Some(ContextMenu::build(window, cx, |mut menu, _window, _| {
3543                        menu = menu.context(focus_handle.clone());
3544
3545                        if thread_with_messages | text_thread_with_messages {
3546                            menu = menu.header("Current Thread");
3547
3548                            if let Some(text_thread_view) = text_thread_view.as_ref() {
3549                                menu = menu
3550                                    .entry("Regenerate Thread Title", None, {
3551                                        let text_thread_view = text_thread_view.clone();
3552                                        move |_, cx| {
3553                                            Self::handle_regenerate_text_thread_title(
3554                                                text_thread_view.clone(),
3555                                                cx,
3556                                            );
3557                                        }
3558                                    })
3559                                    .separator();
3560                            }
3561
3562                            if let Some(conversation_view) = conversation_view.as_ref() {
3563                                menu = menu
3564                                    .entry("Regenerate Thread Title", None, {
3565                                        let conversation_view = conversation_view.clone();
3566                                        move |_, cx| {
3567                                            Self::handle_regenerate_thread_title(
3568                                                conversation_view.clone(),
3569                                                cx,
3570                                            );
3571                                        }
3572                                    })
3573                                    .separator();
3574                            }
3575                        }
3576
3577                        menu = menu
3578                            .header("MCP Servers")
3579                            .action(
3580                                "View Server Extensions",
3581                                Box::new(zed_actions::Extensions {
3582                                    category_filter: Some(
3583                                        zed_actions::ExtensionCategoryFilter::ContextServers,
3584                                    ),
3585                                    id: None,
3586                                }),
3587                            )
3588                            .action("Add Custom Server…", Box::new(AddContextServer))
3589                            .separator()
3590                            .action("Rules", Box::new(OpenRulesLibrary::default()))
3591                            .action("Profiles", Box::new(ManageProfiles::default()))
3592                            .action("Settings", Box::new(OpenSettings))
3593                            .separator()
3594                            .action("Toggle Threads Sidebar", Box::new(ToggleWorkspaceSidebar))
3595                            .action(full_screen_label, Box::new(ToggleZoom));
3596
3597                        if has_auth_methods {
3598                            menu = menu.action("Reauthenticate", Box::new(ReauthenticateAgent))
3599                        }
3600
3601                        menu
3602                    }))
3603                }
3604            })
3605    }
3606
3607    fn render_recent_entries_menu(
3608        &self,
3609        icon: IconName,
3610        corner: Corner,
3611        cx: &mut Context<Self>,
3612    ) -> impl IntoElement {
3613        let focus_handle = self.focus_handle(cx);
3614
3615        PopoverMenu::new("agent-nav-menu")
3616            .trigger_with_tooltip(
3617                IconButton::new("agent-nav-menu", icon).icon_size(IconSize::Small),
3618                {
3619                    move |_window, cx| {
3620                        Tooltip::for_action_in(
3621                            "Toggle Recently Updated Threads",
3622                            &ToggleNavigationMenu,
3623                            &focus_handle,
3624                            cx,
3625                        )
3626                    }
3627                },
3628            )
3629            .anchor(corner)
3630            .with_handle(self.agent_navigation_menu_handle.clone())
3631            .menu({
3632                let menu = self.agent_navigation_menu.clone();
3633                move |window, cx| {
3634                    telemetry::event!("View Thread History Clicked");
3635
3636                    if let Some(menu) = menu.as_ref() {
3637                        menu.update(cx, |_, cx| {
3638                            cx.defer_in(window, |menu, window, cx| {
3639                                menu.rebuild(window, cx);
3640                            });
3641                        })
3642                    }
3643                    menu.clone()
3644                }
3645            })
3646    }
3647
3648    fn render_toolbar_back_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
3649        let focus_handle = self.focus_handle(cx);
3650
3651        IconButton::new("go-back", IconName::ArrowLeft)
3652            .icon_size(IconSize::Small)
3653            .on_click(cx.listener(|this, _, window, cx| {
3654                this.go_back(&workspace::GoBack, window, cx);
3655            }))
3656            .tooltip({
3657                move |_window, cx| {
3658                    Tooltip::for_action_in("Go Back", &workspace::GoBack, &focus_handle, cx)
3659                }
3660            })
3661    }
3662
3663    fn project_has_git_repository(&self, cx: &App) -> bool {
3664        !self.project.read(cx).repositories(cx).is_empty()
3665    }
3666
3667    fn render_start_thread_in_selector(&self, cx: &mut Context<Self>) -> impl IntoElement {
3668        use settings::{NewThreadLocation, Settings};
3669
3670        let focus_handle = self.focus_handle(cx);
3671        let has_git_repo = self.project_has_git_repository(cx);
3672        let is_via_collab = self.project.read(cx).is_via_collab();
3673        let fs = self.fs.clone();
3674
3675        let is_creating = matches!(
3676            self.worktree_creation_status,
3677            Some(WorktreeCreationStatus::Creating)
3678        );
3679
3680        let current_target = self.start_thread_in;
3681        let trigger_label = self.start_thread_in.label();
3682
3683        let new_thread_location = AgentSettings::get_global(cx).new_thread_location;
3684        let is_local_default = new_thread_location == NewThreadLocation::LocalProject;
3685        let is_new_worktree_default = new_thread_location == NewThreadLocation::NewWorktree;
3686
3687        let icon = if self.start_thread_in_menu_handle.is_deployed() {
3688            IconName::ChevronUp
3689        } else {
3690            IconName::ChevronDown
3691        };
3692
3693        let trigger_button = Button::new("thread-target-trigger", trigger_label)
3694            .end_icon(Icon::new(icon).size(IconSize::XSmall).color(Color::Muted))
3695            .disabled(is_creating);
3696
3697        let dock_position = AgentSettings::get_global(cx).dock;
3698        let documentation_side = match dock_position {
3699            settings::DockPosition::Left => DocumentationSide::Right,
3700            settings::DockPosition::Bottom | settings::DockPosition::Right => {
3701                DocumentationSide::Left
3702            }
3703        };
3704
3705        PopoverMenu::new("thread-target-selector")
3706            .trigger_with_tooltip(trigger_button, {
3707                move |_window, cx| {
3708                    Tooltip::for_action_in(
3709                        "Start Thread In…",
3710                        &CycleStartThreadIn,
3711                        &focus_handle,
3712                        cx,
3713                    )
3714                }
3715            })
3716            .menu(move |window, cx| {
3717                let is_local_selected = current_target == StartThreadIn::LocalProject;
3718                let is_new_worktree_selected = current_target == StartThreadIn::NewWorktree;
3719                let fs = fs.clone();
3720
3721                Some(ContextMenu::build(window, cx, move |menu, _window, _cx| {
3722                    let new_worktree_disabled = !has_git_repo || is_via_collab;
3723
3724                    menu.header("Start Thread In…")
3725                        .item(
3726                            ContextMenuEntry::new("Current Worktree")
3727                                .toggleable(IconPosition::End, is_local_selected)
3728                                .documentation_aside(documentation_side, move |_| {
3729                                    HoldForDefault::new(is_local_default)
3730                                        .more_content(false)
3731                                        .into_any_element()
3732                                })
3733                                .handler({
3734                                    let fs = fs.clone();
3735                                    move |window, cx| {
3736                                        if window.modifiers().secondary() {
3737                                            update_settings_file(fs.clone(), cx, |settings, _| {
3738                                                settings
3739                                                    .agent
3740                                                    .get_or_insert_default()
3741                                                    .set_new_thread_location(
3742                                                        NewThreadLocation::LocalProject,
3743                                                    );
3744                                            });
3745                                        }
3746                                        window.dispatch_action(
3747                                            Box::new(StartThreadIn::LocalProject),
3748                                            cx,
3749                                        );
3750                                    }
3751                                }),
3752                        )
3753                        .item({
3754                            let entry = ContextMenuEntry::new("New Git Worktree")
3755                                .toggleable(IconPosition::End, is_new_worktree_selected)
3756                                .disabled(new_worktree_disabled)
3757                                .handler({
3758                                    let fs = fs.clone();
3759                                    move |window, cx| {
3760                                        if window.modifiers().secondary() {
3761                                            update_settings_file(fs.clone(), cx, |settings, _| {
3762                                                settings
3763                                                    .agent
3764                                                    .get_or_insert_default()
3765                                                    .set_new_thread_location(
3766                                                        NewThreadLocation::NewWorktree,
3767                                                    );
3768                                            });
3769                                        }
3770                                        window.dispatch_action(
3771                                            Box::new(StartThreadIn::NewWorktree),
3772                                            cx,
3773                                        );
3774                                    }
3775                                });
3776
3777                            if new_worktree_disabled {
3778                                entry.documentation_aside(documentation_side, move |_| {
3779                                    let reason = if !has_git_repo {
3780                                        "No git repository found in this project."
3781                                    } else {
3782                                        "Not available for remote/collab projects yet."
3783                                    };
3784                                    Label::new(reason)
3785                                        .color(Color::Muted)
3786                                        .size(LabelSize::Small)
3787                                        .into_any_element()
3788                                })
3789                            } else {
3790                                entry.documentation_aside(documentation_side, move |_| {
3791                                    HoldForDefault::new(is_new_worktree_default)
3792                                        .more_content(false)
3793                                        .into_any_element()
3794                                })
3795                            }
3796                        })
3797                }))
3798            })
3799            .with_handle(self.start_thread_in_menu_handle.clone())
3800            .anchor(Corner::TopLeft)
3801            .offset(gpui::Point {
3802                x: px(1.0),
3803                y: px(1.0),
3804            })
3805    }
3806
3807    fn render_toolbar(&self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
3808        let agent_server_store = self.project.read(cx).agent_server_store().clone();
3809        let has_visible_worktrees = self.project.read(cx).visible_worktrees(cx).next().is_some();
3810        let focus_handle = self.focus_handle(cx);
3811
3812        let (selected_agent_custom_icon, selected_agent_label) =
3813            if let AgentType::Custom { id, .. } = &self.selected_agent_type {
3814                let store = agent_server_store.read(cx);
3815                let icon = store.agent_icon(&id);
3816
3817                let label = store
3818                    .agent_display_name(&id)
3819                    .unwrap_or_else(|| self.selected_agent_type.label());
3820                (icon, label)
3821            } else {
3822                (None, self.selected_agent_type.label())
3823            };
3824
3825        let active_thread = match &self.active_view {
3826            ActiveView::AgentThread { conversation_view } => {
3827                conversation_view.read(cx).as_native_thread(cx)
3828            }
3829            ActiveView::Uninitialized
3830            | ActiveView::TextThread { .. }
3831            | ActiveView::History { .. }
3832            | ActiveView::Configuration => None,
3833        };
3834
3835        let new_thread_menu_builder: Rc<
3836            dyn Fn(&mut Window, &mut App) -> Option<Entity<ContextMenu>>,
3837        > = {
3838            let selected_agent = self.selected_agent_type.clone();
3839            let is_agent_selected = move |agent_type: AgentType| selected_agent == agent_type;
3840
3841            let workspace = self.workspace.clone();
3842            let is_via_collab = workspace
3843                .update(cx, |workspace, cx| {
3844                    workspace.project().read(cx).is_via_collab()
3845                })
3846                .unwrap_or_default();
3847
3848            let focus_handle = focus_handle.clone();
3849            let agent_server_store = agent_server_store;
3850
3851            Rc::new(move |window, cx| {
3852                telemetry::event!("New Thread Clicked");
3853
3854                let active_thread = active_thread.clone();
3855                Some(ContextMenu::build(window, cx, |menu, _window, cx| {
3856                    menu.context(focus_handle.clone())
3857                        .when_some(active_thread, |this, active_thread| {
3858                            let thread = active_thread.read(cx);
3859
3860                            if !thread.is_empty() {
3861                                let session_id = thread.id().clone();
3862                                this.item(
3863                                    ContextMenuEntry::new("New From Summary")
3864                                        .icon(IconName::ThreadFromSummary)
3865                                        .icon_color(Color::Muted)
3866                                        .handler(move |window, cx| {
3867                                            window.dispatch_action(
3868                                                Box::new(NewNativeAgentThreadFromSummary {
3869                                                    from_session_id: session_id.clone(),
3870                                                }),
3871                                                cx,
3872                                            );
3873                                        }),
3874                                )
3875                            } else {
3876                                this
3877                            }
3878                        })
3879                        .item(
3880                            ContextMenuEntry::new("Zed Agent")
3881                                .when(
3882                                    is_agent_selected(AgentType::NativeAgent)
3883                                        | is_agent_selected(AgentType::TextThread),
3884                                    |this| {
3885                                        this.action(Box::new(NewExternalAgentThread {
3886                                            agent: None,
3887                                        }))
3888                                    },
3889                                )
3890                                .icon(IconName::ZedAgent)
3891                                .icon_color(Color::Muted)
3892                                .handler({
3893                                    let workspace = workspace.clone();
3894                                    move |window, cx| {
3895                                        if let Some(workspace) = workspace.upgrade() {
3896                                            workspace.update(cx, |workspace, cx| {
3897                                                if let Some(panel) =
3898                                                    workspace.panel::<AgentPanel>(cx)
3899                                                {
3900                                                    panel.update(cx, |panel, cx| {
3901                                                        panel.new_agent_thread(
3902                                                            AgentType::NativeAgent,
3903                                                            window,
3904                                                            cx,
3905                                                        );
3906                                                    });
3907                                                }
3908                                            });
3909                                        }
3910                                    }
3911                                }),
3912                        )
3913                        .item(
3914                            ContextMenuEntry::new("Text Thread")
3915                                .action(NewTextThread.boxed_clone())
3916                                .icon(IconName::TextThread)
3917                                .icon_color(Color::Muted)
3918                                .handler({
3919                                    let workspace = workspace.clone();
3920                                    move |window, cx| {
3921                                        if let Some(workspace) = workspace.upgrade() {
3922                                            workspace.update(cx, |workspace, cx| {
3923                                                if let Some(panel) =
3924                                                    workspace.panel::<AgentPanel>(cx)
3925                                                {
3926                                                    panel.update(cx, |panel, cx| {
3927                                                        panel.new_agent_thread(
3928                                                            AgentType::TextThread,
3929                                                            window,
3930                                                            cx,
3931                                                        );
3932                                                    });
3933                                                }
3934                                            });
3935                                        }
3936                                    }
3937                                }),
3938                        )
3939                        .map(|mut menu| {
3940                            let agent_server_store = agent_server_store.read(cx);
3941                            let registry_store = project::AgentRegistryStore::try_global(cx);
3942                            let registry_store_ref = registry_store.as_ref().map(|s| s.read(cx));
3943
3944                            struct AgentMenuItem {
3945                                id: AgentId,
3946                                display_name: SharedString,
3947                            }
3948
3949                            let agent_items = agent_server_store
3950                                .external_agents()
3951                                .map(|agent_id| {
3952                                    let display_name = agent_server_store
3953                                        .agent_display_name(agent_id)
3954                                        .or_else(|| {
3955                                            registry_store_ref
3956                                                .as_ref()
3957                                                .and_then(|store| store.agent(agent_id))
3958                                                .map(|a| a.name().clone())
3959                                        })
3960                                        .unwrap_or_else(|| agent_id.0.clone());
3961                                    AgentMenuItem {
3962                                        id: agent_id.clone(),
3963                                        display_name,
3964                                    }
3965                                })
3966                                .sorted_unstable_by_key(|e| e.display_name.to_lowercase())
3967                                .collect::<Vec<_>>();
3968
3969                            if !agent_items.is_empty() {
3970                                menu = menu.separator().header("External Agents");
3971                            }
3972                            for item in &agent_items {
3973                                let mut entry = ContextMenuEntry::new(item.display_name.clone());
3974
3975                                let icon_path =
3976                                    agent_server_store.agent_icon(&item.id).or_else(|| {
3977                                        registry_store_ref
3978                                            .as_ref()
3979                                            .and_then(|store| store.agent(&item.id))
3980                                            .and_then(|a| a.icon_path().cloned())
3981                                    });
3982
3983                                if let Some(icon_path) = icon_path {
3984                                    entry = entry.custom_icon_svg(icon_path);
3985                                } else {
3986                                    entry = entry.icon(IconName::Sparkle);
3987                                }
3988
3989                                entry = entry
3990                                    .when(
3991                                        is_agent_selected(AgentType::Custom {
3992                                            id: item.id.clone(),
3993                                        }),
3994                                        |this| {
3995                                            this.action(Box::new(NewExternalAgentThread {
3996                                                agent: None,
3997                                            }))
3998                                        },
3999                                    )
4000                                    .icon_color(Color::Muted)
4001                                    .disabled(is_via_collab)
4002                                    .handler({
4003                                        let workspace = workspace.clone();
4004                                        let agent_id = item.id.clone();
4005                                        move |window, cx| {
4006                                            if let Some(workspace) = workspace.upgrade() {
4007                                                workspace.update(cx, |workspace, cx| {
4008                                                    if let Some(panel) =
4009                                                        workspace.panel::<AgentPanel>(cx)
4010                                                    {
4011                                                        panel.update(cx, |panel, cx| {
4012                                                            panel.new_agent_thread(
4013                                                                AgentType::Custom {
4014                                                                    id: agent_id.clone(),
4015                                                                },
4016                                                                window,
4017                                                                cx,
4018                                                            );
4019                                                        });
4020                                                    }
4021                                                });
4022                                            }
4023                                        }
4024                                    });
4025
4026                                menu = menu.item(entry);
4027                            }
4028
4029                            menu
4030                        })
4031                        .separator()
4032                        .item(
4033                            ContextMenuEntry::new("Add More Agents")
4034                                .icon(IconName::Plus)
4035                                .icon_color(Color::Muted)
4036                                .handler({
4037                                    move |window, cx| {
4038                                        window
4039                                            .dispatch_action(Box::new(zed_actions::AcpRegistry), cx)
4040                                    }
4041                                }),
4042                        )
4043                }))
4044            })
4045        };
4046
4047        let is_thread_loading = self
4048            .active_conversation_view()
4049            .map(|thread| thread.read(cx).is_loading())
4050            .unwrap_or(false);
4051
4052        let has_custom_icon = selected_agent_custom_icon.is_some();
4053        let selected_agent_custom_icon_for_button = selected_agent_custom_icon.clone();
4054        let selected_agent_builtin_icon = self.selected_agent_type.icon();
4055        let selected_agent_label_for_tooltip = selected_agent_label.clone();
4056
4057        let selected_agent = div()
4058            .id("selected_agent_icon")
4059            .when_some(selected_agent_custom_icon, |this, icon_path| {
4060                this.px_1()
4061                    .child(Icon::from_external_svg(icon_path).color(Color::Muted))
4062            })
4063            .when(!has_custom_icon, |this| {
4064                this.when_some(self.selected_agent_type.icon(), |this, icon| {
4065                    this.px_1().child(Icon::new(icon).color(Color::Muted))
4066                })
4067            })
4068            .tooltip(move |_, cx| {
4069                Tooltip::with_meta(
4070                    selected_agent_label_for_tooltip.clone(),
4071                    None,
4072                    "Selected Agent",
4073                    cx,
4074                )
4075            });
4076
4077        let selected_agent = if is_thread_loading {
4078            selected_agent
4079                .with_animation(
4080                    "pulsating-icon",
4081                    Animation::new(Duration::from_secs(1))
4082                        .repeat()
4083                        .with_easing(pulsating_between(0.2, 0.6)),
4084                    |icon, delta| icon.opacity(delta),
4085                )
4086                .into_any_element()
4087        } else {
4088            selected_agent.into_any_element()
4089        };
4090
4091        let show_history_menu = self.has_history_for_selected_agent(cx);
4092        let has_v2_flag = cx.has_flag::<AgentV2FeatureFlag>();
4093        let is_empty_state = !self.active_thread_has_messages(cx);
4094
4095        let is_in_history_or_config = matches!(
4096            &self.active_view,
4097            ActiveView::History { .. } | ActiveView::Configuration
4098        );
4099
4100        let is_text_thread = matches!(&self.active_view, ActiveView::TextThread { .. });
4101
4102        let is_full_screen = self.is_zoomed(window, cx);
4103
4104        let use_v2_empty_toolbar =
4105            has_v2_flag && is_empty_state && !is_in_history_or_config && !is_text_thread;
4106
4107        let base_container = h_flex()
4108            .id("agent-panel-toolbar")
4109            .h(Tab::container_height(cx))
4110            .max_w_full()
4111            .flex_none()
4112            .justify_between()
4113            .gap_2()
4114            .bg(cx.theme().colors().tab_bar_background)
4115            .border_b_1()
4116            .border_color(cx.theme().colors().border);
4117
4118        if use_v2_empty_toolbar {
4119            let (chevron_icon, icon_color, label_color) =
4120                if self.new_thread_menu_handle.is_deployed() {
4121                    (IconName::ChevronUp, Color::Accent, Color::Accent)
4122                } else {
4123                    (IconName::ChevronDown, Color::Muted, Color::Default)
4124                };
4125
4126            let agent_icon = if let Some(icon_path) = selected_agent_custom_icon_for_button {
4127                Icon::from_external_svg(icon_path)
4128                    .size(IconSize::Small)
4129                    .color(icon_color)
4130            } else {
4131                let icon_name = selected_agent_builtin_icon.unwrap_or(IconName::ZedAgent);
4132                Icon::new(icon_name).size(IconSize::Small).color(icon_color)
4133            };
4134
4135            let agent_selector_button = Button::new("agent-selector-trigger", selected_agent_label)
4136                .start_icon(agent_icon)
4137                .color(label_color)
4138                .end_icon(
4139                    Icon::new(chevron_icon)
4140                        .color(icon_color)
4141                        .size(IconSize::XSmall),
4142                );
4143
4144            let agent_selector_menu = PopoverMenu::new("new_thread_menu")
4145                .trigger_with_tooltip(agent_selector_button, {
4146                    move |_window, cx| {
4147                        Tooltip::for_action_in(
4148                            "New Thread…",
4149                            &ToggleNewThreadMenu,
4150                            &focus_handle,
4151                            cx,
4152                        )
4153                    }
4154                })
4155                .menu({
4156                    let builder = new_thread_menu_builder.clone();
4157                    move |window, cx| builder(window, cx)
4158                })
4159                .with_handle(self.new_thread_menu_handle.clone())
4160                .anchor(Corner::TopLeft)
4161                .offset(gpui::Point {
4162                    x: px(1.0),
4163                    y: px(1.0),
4164                });
4165
4166            base_container
4167                .child(
4168                    h_flex()
4169                        .size_full()
4170                        .gap(DynamicSpacing::Base04.rems(cx))
4171                        .pl(DynamicSpacing::Base04.rems(cx))
4172                        .child(agent_selector_menu)
4173                        .when(
4174                            has_visible_worktrees && self.project_has_git_repository(cx),
4175                            |this| this.child(self.render_start_thread_in_selector(cx)),
4176                        ),
4177                )
4178                .child(
4179                    h_flex()
4180                        .h_full()
4181                        .flex_none()
4182                        .gap_1()
4183                        .pl_1()
4184                        .pr_1()
4185                        .when(show_history_menu && !has_v2_flag, |this| {
4186                            this.child(self.render_recent_entries_menu(
4187                                IconName::MenuAltTemp,
4188                                Corner::TopRight,
4189                                cx,
4190                            ))
4191                        })
4192                        .when(is_full_screen, |this| {
4193                            this.child(
4194                                IconButton::new("disable-full-screen", IconName::Minimize)
4195                                    .icon_size(IconSize::Small)
4196                                    .tooltip(move |_, cx| {
4197                                        Tooltip::for_action("Disable Full Screen", &ToggleZoom, cx)
4198                                    })
4199                                    .on_click({
4200                                        cx.listener(move |_, _, window, cx| {
4201                                            window.dispatch_action(ToggleZoom.boxed_clone(), cx);
4202                                        })
4203                                    }),
4204                            )
4205                        })
4206                        .child(self.render_panel_options_menu(window, cx)),
4207                )
4208                .into_any_element()
4209        } else {
4210            let new_thread_menu = PopoverMenu::new("new_thread_menu")
4211                .trigger_with_tooltip(
4212                    IconButton::new("new_thread_menu_btn", IconName::Plus)
4213                        .icon_size(IconSize::Small),
4214                    {
4215                        move |_window, cx| {
4216                            Tooltip::for_action_in(
4217                                "New Thread\u{2026}",
4218                                &ToggleNewThreadMenu,
4219                                &focus_handle,
4220                                cx,
4221                            )
4222                        }
4223                    },
4224                )
4225                .anchor(Corner::TopRight)
4226                .with_handle(self.new_thread_menu_handle.clone())
4227                .menu(move |window, cx| new_thread_menu_builder(window, cx));
4228
4229            base_container
4230                .child(
4231                    h_flex()
4232                        .size_full()
4233                        .gap(DynamicSpacing::Base04.rems(cx))
4234                        .pl(DynamicSpacing::Base04.rems(cx))
4235                        .child(match &self.active_view {
4236                            ActiveView::History { .. } | ActiveView::Configuration => {
4237                                self.render_toolbar_back_button(cx).into_any_element()
4238                            }
4239                            _ => selected_agent.into_any_element(),
4240                        })
4241                        .child(self.render_title_view(window, cx)),
4242                )
4243                .child(
4244                    h_flex()
4245                        .h_full()
4246                        .flex_none()
4247                        .gap_1()
4248                        .pl_1()
4249                        .pr_1()
4250                        .child(new_thread_menu)
4251                        .when(show_history_menu && !has_v2_flag, |this| {
4252                            this.child(self.render_recent_entries_menu(
4253                                IconName::MenuAltTemp,
4254                                Corner::TopRight,
4255                                cx,
4256                            ))
4257                        })
4258                        .when(is_full_screen, |this| {
4259                            this.child(
4260                                IconButton::new("disable-full-screen", IconName::Minimize)
4261                                    .icon_size(IconSize::Small)
4262                                    .tooltip(move |_, cx| {
4263                                        Tooltip::for_action("Disable Full Screen", &ToggleZoom, cx)
4264                                    })
4265                                    .on_click({
4266                                        cx.listener(move |_, _, window, cx| {
4267                                            window.dispatch_action(ToggleZoom.boxed_clone(), cx);
4268                                        })
4269                                    }),
4270                            )
4271                        })
4272                        .child(self.render_panel_options_menu(window, cx)),
4273                )
4274                .into_any_element()
4275        }
4276    }
4277
4278    fn render_worktree_creation_status(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
4279        let status = self.worktree_creation_status.as_ref()?;
4280        match status {
4281            WorktreeCreationStatus::Creating => Some(
4282                h_flex()
4283                    .absolute()
4284                    .bottom_12()
4285                    .w_full()
4286                    .p_2()
4287                    .gap_1()
4288                    .justify_center()
4289                    .bg(cx.theme().colors().editor_background)
4290                    .child(
4291                        Icon::new(IconName::LoadCircle)
4292                            .size(IconSize::Small)
4293                            .color(Color::Muted)
4294                            .with_rotate_animation(3),
4295                    )
4296                    .child(
4297                        Label::new("Creating Worktree…")
4298                            .color(Color::Muted)
4299                            .size(LabelSize::Small),
4300                    )
4301                    .into_any_element(),
4302            ),
4303            WorktreeCreationStatus::Error(message) => Some(
4304                Callout::new()
4305                    .icon(IconName::Warning)
4306                    .severity(Severity::Warning)
4307                    .title(message.clone())
4308                    .into_any_element(),
4309            ),
4310        }
4311    }
4312
4313    fn should_render_trial_end_upsell(&self, cx: &mut Context<Self>) -> bool {
4314        if TrialEndUpsell::dismissed(cx) {
4315            return false;
4316        }
4317
4318        match &self.active_view {
4319            ActiveView::TextThread { .. } => {
4320                if LanguageModelRegistry::global(cx)
4321                    .read(cx)
4322                    .default_model()
4323                    .is_some_and(|model| {
4324                        model.provider.id() != language_model::ZED_CLOUD_PROVIDER_ID
4325                    })
4326                {
4327                    return false;
4328                }
4329            }
4330            ActiveView::Uninitialized
4331            | ActiveView::AgentThread { .. }
4332            | ActiveView::History { .. }
4333            | ActiveView::Configuration => return false,
4334        }
4335
4336        let plan = self.user_store.read(cx).plan();
4337        let has_previous_trial = self.user_store.read(cx).trial_started_at().is_some();
4338
4339        plan.is_some_and(|plan| plan == Plan::ZedFree) && has_previous_trial
4340    }
4341
4342    fn should_render_onboarding(&self, cx: &mut Context<Self>) -> bool {
4343        if self.on_boarding_upsell_dismissed.load(Ordering::Acquire) {
4344            return false;
4345        }
4346
4347        let user_store = self.user_store.read(cx);
4348
4349        if user_store.plan().is_some_and(|plan| plan == Plan::ZedPro)
4350            && user_store
4351                .subscription_period()
4352                .and_then(|period| period.0.checked_add_days(chrono::Days::new(1)))
4353                .is_some_and(|date| date < chrono::Utc::now())
4354        {
4355            OnboardingUpsell::set_dismissed(true, cx);
4356            self.on_boarding_upsell_dismissed
4357                .store(true, Ordering::Release);
4358            return false;
4359        }
4360
4361        let has_configured_non_zed_providers = LanguageModelRegistry::read_global(cx)
4362            .visible_providers()
4363            .iter()
4364            .any(|provider| {
4365                provider.is_authenticated(cx)
4366                    && provider.id() != language_model::ZED_CLOUD_PROVIDER_ID
4367            });
4368
4369        match &self.active_view {
4370            ActiveView::Uninitialized | ActiveView::History { .. } | ActiveView::Configuration => {
4371                false
4372            }
4373            ActiveView::AgentThread {
4374                conversation_view, ..
4375            } if conversation_view.read(cx).as_native_thread(cx).is_none() => false,
4376            ActiveView::AgentThread { conversation_view } => {
4377                let history_is_empty = conversation_view
4378                    .read(cx)
4379                    .history()
4380                    .is_none_or(|h| h.read(cx).is_empty());
4381                history_is_empty || !has_configured_non_zed_providers
4382            }
4383            ActiveView::TextThread { .. } => {
4384                let history_is_empty = self.text_thread_history.read(cx).is_empty();
4385                history_is_empty || !has_configured_non_zed_providers
4386            }
4387        }
4388    }
4389
4390    fn render_onboarding(
4391        &self,
4392        _window: &mut Window,
4393        cx: &mut Context<Self>,
4394    ) -> Option<impl IntoElement> {
4395        if !self.should_render_onboarding(cx) {
4396            return None;
4397        }
4398
4399        let text_thread_view = matches!(&self.active_view, ActiveView::TextThread { .. });
4400
4401        Some(
4402            div()
4403                .when(text_thread_view, |this| {
4404                    this.bg(cx.theme().colors().editor_background)
4405                })
4406                .child(self.onboarding.clone()),
4407        )
4408    }
4409
4410    fn render_trial_end_upsell(
4411        &self,
4412        _window: &mut Window,
4413        cx: &mut Context<Self>,
4414    ) -> Option<impl IntoElement> {
4415        if !self.should_render_trial_end_upsell(cx) {
4416            return None;
4417        }
4418
4419        Some(
4420            v_flex()
4421                .absolute()
4422                .inset_0()
4423                .size_full()
4424                .bg(cx.theme().colors().panel_background)
4425                .opacity(0.85)
4426                .block_mouse_except_scroll()
4427                .child(EndTrialUpsell::new(Arc::new({
4428                    let this = cx.entity();
4429                    move |_, cx| {
4430                        this.update(cx, |_this, cx| {
4431                            TrialEndUpsell::set_dismissed(true, cx);
4432                            cx.notify();
4433                        });
4434                    }
4435                }))),
4436        )
4437    }
4438
4439    fn emit_configuration_error_telemetry_if_needed(
4440        &mut self,
4441        configuration_error: Option<&ConfigurationError>,
4442    ) {
4443        let error_kind = configuration_error.map(|err| match err {
4444            ConfigurationError::NoProvider => "no_provider",
4445            ConfigurationError::ModelNotFound => "model_not_found",
4446            ConfigurationError::ProviderNotAuthenticated(_) => "provider_not_authenticated",
4447        });
4448
4449        let error_kind_string = error_kind.map(String::from);
4450
4451        if self.last_configuration_error_telemetry == error_kind_string {
4452            return;
4453        }
4454
4455        self.last_configuration_error_telemetry = error_kind_string;
4456
4457        if let Some(kind) = error_kind {
4458            let message = configuration_error
4459                .map(|err| err.to_string())
4460                .unwrap_or_default();
4461
4462            telemetry::event!("Agent Panel Error Shown", kind = kind, message = message,);
4463        }
4464    }
4465
4466    fn render_configuration_error(
4467        &self,
4468        border_bottom: bool,
4469        configuration_error: &ConfigurationError,
4470        focus_handle: &FocusHandle,
4471        cx: &mut App,
4472    ) -> impl IntoElement {
4473        let zed_provider_configured = AgentSettings::get_global(cx)
4474            .default_model
4475            .as_ref()
4476            .is_some_and(|selection| selection.provider.0.as_str() == "zed.dev");
4477
4478        let callout = if zed_provider_configured {
4479            Callout::new()
4480                .icon(IconName::Warning)
4481                .severity(Severity::Warning)
4482                .when(border_bottom, |this| {
4483                    this.border_position(ui::BorderPosition::Bottom)
4484                })
4485                .title("Sign in to continue using Zed as your LLM provider.")
4486                .actions_slot(
4487                    Button::new("sign_in", "Sign In")
4488                        .style(ButtonStyle::Tinted(ui::TintColor::Warning))
4489                        .label_size(LabelSize::Small)
4490                        .on_click({
4491                            let workspace = self.workspace.clone();
4492                            move |_, _, cx| {
4493                                let Ok(client) =
4494                                    workspace.update(cx, |workspace, _| workspace.client().clone())
4495                                else {
4496                                    return;
4497                                };
4498
4499                                cx.spawn(async move |cx| {
4500                                    client.sign_in_with_optional_connect(true, cx).await
4501                                })
4502                                .detach_and_log_err(cx);
4503                            }
4504                        }),
4505                )
4506        } else {
4507            Callout::new()
4508                .icon(IconName::Warning)
4509                .severity(Severity::Warning)
4510                .when(border_bottom, |this| {
4511                    this.border_position(ui::BorderPosition::Bottom)
4512                })
4513                .title(configuration_error.to_string())
4514                .actions_slot(
4515                    Button::new("settings", "Configure")
4516                        .style(ButtonStyle::Tinted(ui::TintColor::Warning))
4517                        .label_size(LabelSize::Small)
4518                        .key_binding(
4519                            KeyBinding::for_action_in(&OpenSettings, focus_handle, cx)
4520                                .map(|kb| kb.size(rems_from_px(12.))),
4521                        )
4522                        .on_click(|_event, window, cx| {
4523                            window.dispatch_action(OpenSettings.boxed_clone(), cx)
4524                        }),
4525                )
4526        };
4527
4528        match configuration_error {
4529            ConfigurationError::ModelNotFound
4530            | ConfigurationError::ProviderNotAuthenticated(_)
4531            | ConfigurationError::NoProvider => callout.into_any_element(),
4532        }
4533    }
4534
4535    fn render_text_thread(
4536        &self,
4537        text_thread_editor: &Entity<TextThreadEditor>,
4538        buffer_search_bar: &Entity<BufferSearchBar>,
4539        window: &mut Window,
4540        cx: &mut Context<Self>,
4541    ) -> Div {
4542        let mut registrar = buffer_search::DivRegistrar::new(
4543            |this, _, _cx| match &this.active_view {
4544                ActiveView::TextThread {
4545                    buffer_search_bar, ..
4546                } => Some(buffer_search_bar.clone()),
4547                _ => None,
4548            },
4549            cx,
4550        );
4551        BufferSearchBar::register(&mut registrar);
4552        registrar
4553            .into_div()
4554            .size_full()
4555            .relative()
4556            .map(|parent| {
4557                buffer_search_bar.update(cx, |buffer_search_bar, cx| {
4558                    if buffer_search_bar.is_dismissed() {
4559                        return parent;
4560                    }
4561                    parent.child(
4562                        div()
4563                            .p(DynamicSpacing::Base08.rems(cx))
4564                            .border_b_1()
4565                            .border_color(cx.theme().colors().border_variant)
4566                            .bg(cx.theme().colors().editor_background)
4567                            .child(buffer_search_bar.render(window, cx)),
4568                    )
4569                })
4570            })
4571            .child(text_thread_editor.clone())
4572            .child(self.render_drag_target(cx))
4573    }
4574
4575    fn render_drag_target(&self, cx: &Context<Self>) -> Div {
4576        let is_local = self.project.read(cx).is_local();
4577        div()
4578            .invisible()
4579            .absolute()
4580            .top_0()
4581            .right_0()
4582            .bottom_0()
4583            .left_0()
4584            .bg(cx.theme().colors().drop_target_background)
4585            .drag_over::<DraggedTab>(|this, _, _, _| this.visible())
4586            .drag_over::<DraggedSelection>(|this, _, _, _| this.visible())
4587            .when(is_local, |this| {
4588                this.drag_over::<ExternalPaths>(|this, _, _, _| this.visible())
4589            })
4590            .on_drop(cx.listener(move |this, tab: &DraggedTab, window, cx| {
4591                let item = tab.pane.read(cx).item_for_index(tab.ix);
4592                let project_paths = item
4593                    .and_then(|item| item.project_path(cx))
4594                    .into_iter()
4595                    .collect::<Vec<_>>();
4596                this.handle_drop(project_paths, vec![], window, cx);
4597            }))
4598            .on_drop(
4599                cx.listener(move |this, selection: &DraggedSelection, window, cx| {
4600                    let project_paths = selection
4601                        .items()
4602                        .filter_map(|item| this.project.read(cx).path_for_entry(item.entry_id, cx))
4603                        .collect::<Vec<_>>();
4604                    this.handle_drop(project_paths, vec![], window, cx);
4605                }),
4606            )
4607            .on_drop(cx.listener(move |this, paths: &ExternalPaths, window, cx| {
4608                let tasks = paths
4609                    .paths()
4610                    .iter()
4611                    .map(|path| {
4612                        Workspace::project_path_for_path(this.project.clone(), path, false, cx)
4613                    })
4614                    .collect::<Vec<_>>();
4615                cx.spawn_in(window, async move |this, cx| {
4616                    let mut paths = vec![];
4617                    let mut added_worktrees = vec![];
4618                    let opened_paths = futures::future::join_all(tasks).await;
4619                    for entry in opened_paths {
4620                        if let Some((worktree, project_path)) = entry.log_err() {
4621                            added_worktrees.push(worktree);
4622                            paths.push(project_path);
4623                        }
4624                    }
4625                    this.update_in(cx, |this, window, cx| {
4626                        this.handle_drop(paths, added_worktrees, window, cx);
4627                    })
4628                    .ok();
4629                })
4630                .detach();
4631            }))
4632    }
4633
4634    fn handle_drop(
4635        &mut self,
4636        paths: Vec<ProjectPath>,
4637        added_worktrees: Vec<Entity<Worktree>>,
4638        window: &mut Window,
4639        cx: &mut Context<Self>,
4640    ) {
4641        match &self.active_view {
4642            ActiveView::AgentThread { conversation_view } => {
4643                conversation_view.update(cx, |conversation_view, cx| {
4644                    conversation_view.insert_dragged_files(paths, added_worktrees, window, cx);
4645                });
4646            }
4647            ActiveView::TextThread {
4648                text_thread_editor, ..
4649            } => {
4650                text_thread_editor.update(cx, |text_thread_editor, cx| {
4651                    TextThreadEditor::insert_dragged_files(
4652                        text_thread_editor,
4653                        paths,
4654                        added_worktrees,
4655                        window,
4656                        cx,
4657                    );
4658                });
4659            }
4660            ActiveView::Uninitialized | ActiveView::History { .. } | ActiveView::Configuration => {}
4661        }
4662    }
4663
4664    fn render_workspace_trust_message(&self, cx: &Context<Self>) -> Option<impl IntoElement> {
4665        if !self.show_trust_workspace_message {
4666            return None;
4667        }
4668
4669        let description = "To protect your system, third-party code—like MCP servers—won't run until you mark this workspace as safe.";
4670
4671        Some(
4672            Callout::new()
4673                .icon(IconName::Warning)
4674                .severity(Severity::Warning)
4675                .border_position(ui::BorderPosition::Bottom)
4676                .title("You're in Restricted Mode")
4677                .description(description)
4678                .actions_slot(
4679                    Button::new("open-trust-modal", "Configure Project Trust")
4680                        .label_size(LabelSize::Small)
4681                        .style(ButtonStyle::Outlined)
4682                        .on_click({
4683                            cx.listener(move |this, _, window, cx| {
4684                                this.workspace
4685                                    .update(cx, |workspace, cx| {
4686                                        workspace
4687                                            .show_worktree_trust_security_modal(true, window, cx)
4688                                    })
4689                                    .log_err();
4690                            })
4691                        }),
4692                ),
4693        )
4694    }
4695
4696    fn key_context(&self) -> KeyContext {
4697        let mut key_context = KeyContext::new_with_defaults();
4698        key_context.add("AgentPanel");
4699        match &self.active_view {
4700            ActiveView::AgentThread { .. } => key_context.add("acp_thread"),
4701            ActiveView::TextThread { .. } => key_context.add("text_thread"),
4702            ActiveView::Uninitialized | ActiveView::History { .. } | ActiveView::Configuration => {}
4703        }
4704        key_context
4705    }
4706}
4707
4708impl Render for AgentPanel {
4709    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
4710        // WARNING: Changes to this element hierarchy can have
4711        // non-obvious implications to the layout of children.
4712        //
4713        // If you need to change it, please confirm:
4714        // - The message editor expands (cmd-option-esc) correctly
4715        // - When expanded, the buttons at the bottom of the panel are displayed correctly
4716        // - Font size works as expected and can be changed with cmd-+/cmd-
4717        // - Scrolling in all views works as expected
4718        // - Files can be dropped into the panel
4719        let content = v_flex()
4720            .relative()
4721            .size_full()
4722            .justify_between()
4723            .key_context(self.key_context())
4724            .on_action(cx.listener(|this, action: &NewThread, window, cx| {
4725                this.new_thread(action, window, cx);
4726            }))
4727            .on_action(cx.listener(|this, _: &OpenHistory, window, cx| {
4728                this.open_history(window, cx);
4729            }))
4730            .on_action(cx.listener(|this, _: &OpenSettings, window, cx| {
4731                this.open_configuration(window, cx);
4732            }))
4733            .on_action(cx.listener(Self::open_active_thread_as_markdown))
4734            .on_action(cx.listener(Self::deploy_rules_library))
4735            .on_action(cx.listener(Self::go_back))
4736            .on_action(cx.listener(Self::toggle_navigation_menu))
4737            .on_action(cx.listener(Self::toggle_options_menu))
4738            .on_action(cx.listener(Self::increase_font_size))
4739            .on_action(cx.listener(Self::decrease_font_size))
4740            .on_action(cx.listener(Self::reset_font_size))
4741            .on_action(cx.listener(Self::toggle_zoom))
4742            .on_action(cx.listener(|this, _: &ReauthenticateAgent, window, cx| {
4743                if let Some(conversation_view) = this.active_conversation_view() {
4744                    conversation_view.update(cx, |conversation_view, cx| {
4745                        conversation_view.reauthenticate(window, cx)
4746                    })
4747                }
4748            }))
4749            .child(self.render_toolbar(window, cx))
4750            .children(self.render_workspace_trust_message(cx))
4751            .children(self.render_onboarding(window, cx))
4752            .map(|parent| {
4753                // Emit configuration error telemetry before entering the match to avoid borrow conflicts
4754                if matches!(&self.active_view, ActiveView::TextThread { .. }) {
4755                    let model_registry = LanguageModelRegistry::read_global(cx);
4756                    let configuration_error =
4757                        model_registry.configuration_error(model_registry.default_model(), cx);
4758                    self.emit_configuration_error_telemetry_if_needed(configuration_error.as_ref());
4759                }
4760
4761                match &self.active_view {
4762                    ActiveView::Uninitialized => parent,
4763                    ActiveView::AgentThread {
4764                        conversation_view, ..
4765                    } => parent
4766                        .child(conversation_view.clone())
4767                        .child(self.render_drag_target(cx)),
4768                    ActiveView::History { history: kind } => match kind {
4769                        History::AgentThreads { view } => parent.child(view.clone()),
4770                        History::TextThreads => parent.child(self.text_thread_history.clone()),
4771                    },
4772                    ActiveView::TextThread {
4773                        text_thread_editor,
4774                        buffer_search_bar,
4775                        ..
4776                    } => {
4777                        let model_registry = LanguageModelRegistry::read_global(cx);
4778                        let configuration_error =
4779                            model_registry.configuration_error(model_registry.default_model(), cx);
4780
4781                        parent
4782                            .map(|this| {
4783                                if !self.should_render_onboarding(cx)
4784                                    && let Some(err) = configuration_error.as_ref()
4785                                {
4786                                    this.child(self.render_configuration_error(
4787                                        true,
4788                                        err,
4789                                        &self.focus_handle(cx),
4790                                        cx,
4791                                    ))
4792                                } else {
4793                                    this
4794                                }
4795                            })
4796                            .child(self.render_text_thread(
4797                                text_thread_editor,
4798                                buffer_search_bar,
4799                                window,
4800                                cx,
4801                            ))
4802                    }
4803                    ActiveView::Configuration => parent.children(self.configuration.clone()),
4804                }
4805            })
4806            .children(self.render_worktree_creation_status(cx))
4807            .children(self.render_trial_end_upsell(window, cx));
4808
4809        match self.active_view.which_font_size_used() {
4810            WhichFontSize::AgentFont => {
4811                WithRemSize::new(ThemeSettings::get_global(cx).agent_ui_font_size(cx))
4812                    .size_full()
4813                    .child(content)
4814                    .into_any()
4815            }
4816            _ => content.into_any(),
4817        }
4818    }
4819}
4820
4821struct PromptLibraryInlineAssist {
4822    workspace: WeakEntity<Workspace>,
4823}
4824
4825impl PromptLibraryInlineAssist {
4826    pub fn new(workspace: WeakEntity<Workspace>) -> Self {
4827        Self { workspace }
4828    }
4829}
4830
4831impl rules_library::InlineAssistDelegate for PromptLibraryInlineAssist {
4832    fn assist(
4833        &self,
4834        prompt_editor: &Entity<Editor>,
4835        initial_prompt: Option<String>,
4836        window: &mut Window,
4837        cx: &mut Context<RulesLibrary>,
4838    ) {
4839        InlineAssistant::update_global(cx, |assistant, cx| {
4840            let Some(workspace) = self.workspace.upgrade() else {
4841                return;
4842            };
4843            let Some(panel) = workspace.read(cx).panel::<AgentPanel>(cx) else {
4844                return;
4845            };
4846            let history = panel
4847                .read(cx)
4848                .connection_store()
4849                .read(cx)
4850                .entry(&crate::Agent::NativeAgent)
4851                .and_then(|s| s.read(cx).history())
4852                .map(|h| h.downgrade());
4853            let project = workspace.read(cx).project().downgrade();
4854            let panel = panel.read(cx);
4855            let thread_store = panel.thread_store().clone();
4856            assistant.assist(
4857                prompt_editor,
4858                self.workspace.clone(),
4859                project,
4860                thread_store,
4861                None,
4862                history,
4863                initial_prompt,
4864                window,
4865                cx,
4866            );
4867        })
4868    }
4869
4870    fn focus_agent_panel(
4871        &self,
4872        workspace: &mut Workspace,
4873        window: &mut Window,
4874        cx: &mut Context<Workspace>,
4875    ) -> bool {
4876        workspace.focus_panel::<AgentPanel>(window, cx).is_some()
4877    }
4878}
4879
4880pub struct ConcreteAssistantPanelDelegate;
4881
4882impl AgentPanelDelegate for ConcreteAssistantPanelDelegate {
4883    fn active_text_thread_editor(
4884        &self,
4885        workspace: &mut Workspace,
4886        _window: &mut Window,
4887        cx: &mut Context<Workspace>,
4888    ) -> Option<Entity<TextThreadEditor>> {
4889        let panel = workspace.panel::<AgentPanel>(cx)?;
4890        panel.read(cx).active_text_thread_editor()
4891    }
4892
4893    fn open_local_text_thread(
4894        &self,
4895        workspace: &mut Workspace,
4896        path: Arc<Path>,
4897        window: &mut Window,
4898        cx: &mut Context<Workspace>,
4899    ) -> Task<Result<()>> {
4900        let Some(panel) = workspace.panel::<AgentPanel>(cx) else {
4901            return Task::ready(Err(anyhow!("Agent panel not found")));
4902        };
4903
4904        panel.update(cx, |panel, cx| {
4905            panel.open_saved_text_thread(path, window, cx)
4906        })
4907    }
4908
4909    fn open_remote_text_thread(
4910        &self,
4911        _workspace: &mut Workspace,
4912        _text_thread_id: assistant_text_thread::TextThreadId,
4913        _window: &mut Window,
4914        _cx: &mut Context<Workspace>,
4915    ) -> Task<Result<Entity<TextThreadEditor>>> {
4916        Task::ready(Err(anyhow!("opening remote context not implemented")))
4917    }
4918
4919    fn quote_selection(
4920        &self,
4921        workspace: &mut Workspace,
4922        selection_ranges: Vec<Range<Anchor>>,
4923        buffer: Entity<MultiBuffer>,
4924        window: &mut Window,
4925        cx: &mut Context<Workspace>,
4926    ) {
4927        let Some(panel) = workspace.panel::<AgentPanel>(cx) else {
4928            return;
4929        };
4930
4931        if !panel.focus_handle(cx).contains_focused(window, cx) {
4932            workspace.toggle_panel_focus::<AgentPanel>(window, cx);
4933        }
4934
4935        panel.update(cx, |_, cx| {
4936            // Wait to create a new context until the workspace is no longer
4937            // being updated.
4938            cx.defer_in(window, move |panel, window, cx| {
4939                if let Some(conversation_view) = panel.active_conversation_view() {
4940                    conversation_view.update(cx, |conversation_view, cx| {
4941                        conversation_view.insert_selections(window, cx);
4942                    });
4943                } else if let Some(text_thread_editor) = panel.active_text_thread_editor() {
4944                    let snapshot = buffer.read(cx).snapshot(cx);
4945                    let selection_ranges = selection_ranges
4946                        .into_iter()
4947                        .map(|range| range.to_point(&snapshot))
4948                        .collect::<Vec<_>>();
4949
4950                    text_thread_editor.update(cx, |text_thread_editor, cx| {
4951                        text_thread_editor.quote_ranges(selection_ranges, snapshot, window, cx)
4952                    });
4953                }
4954            });
4955        });
4956    }
4957
4958    fn quote_terminal_text(
4959        &self,
4960        workspace: &mut Workspace,
4961        text: String,
4962        window: &mut Window,
4963        cx: &mut Context<Workspace>,
4964    ) {
4965        let Some(panel) = workspace.panel::<AgentPanel>(cx) else {
4966            return;
4967        };
4968
4969        if !panel.focus_handle(cx).contains_focused(window, cx) {
4970            workspace.toggle_panel_focus::<AgentPanel>(window, cx);
4971        }
4972
4973        panel.update(cx, |_, cx| {
4974            // Wait to create a new context until the workspace is no longer
4975            // being updated.
4976            cx.defer_in(window, move |panel, window, cx| {
4977                if let Some(conversation_view) = panel.active_conversation_view() {
4978                    conversation_view.update(cx, |conversation_view, cx| {
4979                        conversation_view.insert_terminal_text(text, window, cx);
4980                    });
4981                } else if let Some(text_thread_editor) = panel.active_text_thread_editor() {
4982                    text_thread_editor.update(cx, |text_thread_editor, cx| {
4983                        text_thread_editor.quote_terminal_text(text, window, cx)
4984                    });
4985                }
4986            });
4987        });
4988    }
4989}
4990
4991struct OnboardingUpsell;
4992
4993impl Dismissable for OnboardingUpsell {
4994    const KEY: &'static str = "dismissed-trial-upsell";
4995}
4996
4997struct TrialEndUpsell;
4998
4999impl Dismissable for TrialEndUpsell {
5000    const KEY: &'static str = "dismissed-trial-end-upsell";
5001}
5002
5003/// Test-only helper methods
5004#[cfg(any(test, feature = "test-support"))]
5005impl AgentPanel {
5006    pub fn test_new(
5007        workspace: &Workspace,
5008        text_thread_store: Entity<assistant_text_thread::TextThreadStore>,
5009        window: &mut Window,
5010        cx: &mut Context<Self>,
5011    ) -> Self {
5012        Self::new(workspace, text_thread_store, None, window, cx)
5013    }
5014
5015    /// Opens an external thread using an arbitrary AgentServer.
5016    ///
5017    /// This is a test-only helper that allows visual tests and integration tests
5018    /// to inject a stub server without modifying production code paths.
5019    /// Not compiled into production builds.
5020    pub fn open_external_thread_with_server(
5021        &mut self,
5022        server: Rc<dyn AgentServer>,
5023        window: &mut Window,
5024        cx: &mut Context<Self>,
5025    ) {
5026        let workspace = self.workspace.clone();
5027        let project = self.project.clone();
5028
5029        let ext_agent = Agent::Custom {
5030            id: server.agent_id(),
5031        };
5032
5033        self.create_agent_thread(
5034            server, None, None, None, None, workspace, project, ext_agent, true, window, cx,
5035        );
5036    }
5037
5038    /// Returns the currently active thread view, if any.
5039    ///
5040    /// This is a test-only accessor that exposes the private `active_thread_view()`
5041    /// method for test assertions. Not compiled into production builds.
5042    pub fn active_thread_view_for_tests(&self) -> Option<&Entity<ConversationView>> {
5043        self.active_conversation_view()
5044    }
5045
5046    /// Sets the start_thread_in value directly, bypassing validation.
5047    ///
5048    /// This is a test-only helper for visual tests that need to show specific
5049    /// start_thread_in states without requiring a real git repository.
5050    pub fn set_start_thread_in_for_tests(&mut self, target: StartThreadIn, cx: &mut Context<Self>) {
5051        self.start_thread_in = target;
5052        cx.notify();
5053    }
5054
5055    /// Returns the current worktree creation status.
5056    ///
5057    /// This is a test-only helper for visual tests.
5058    pub fn worktree_creation_status_for_tests(&self) -> Option<&WorktreeCreationStatus> {
5059        self.worktree_creation_status.as_ref()
5060    }
5061
5062    /// Sets the worktree creation status directly.
5063    ///
5064    /// This is a test-only helper for visual tests that need to show the
5065    /// "Creating worktree…" spinner or error banners.
5066    pub fn set_worktree_creation_status_for_tests(
5067        &mut self,
5068        status: Option<WorktreeCreationStatus>,
5069        cx: &mut Context<Self>,
5070    ) {
5071        self.worktree_creation_status = status;
5072        cx.notify();
5073    }
5074
5075    /// Opens the history view.
5076    ///
5077    /// This is a test-only helper that exposes the private `open_history()`
5078    /// method for visual tests.
5079    pub fn open_history_for_tests(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5080        self.open_history(window, cx);
5081    }
5082
5083    /// Opens the start_thread_in selector popover menu.
5084    ///
5085    /// This is a test-only helper for visual tests.
5086    pub fn open_start_thread_in_menu_for_tests(
5087        &mut self,
5088        window: &mut Window,
5089        cx: &mut Context<Self>,
5090    ) {
5091        self.start_thread_in_menu_handle.show(window, cx);
5092    }
5093
5094    /// Dismisses the start_thread_in dropdown menu.
5095    ///
5096    /// This is a test-only helper for visual tests.
5097    pub fn close_start_thread_in_menu_for_tests(&mut self, cx: &mut Context<Self>) {
5098        self.start_thread_in_menu_handle.hide(cx);
5099    }
5100}
5101
5102#[cfg(test)]
5103mod tests {
5104    use super::*;
5105    use crate::conversation_view::tests::{StubAgentServer, init_test};
5106    use crate::test_support::{
5107        active_session_id, open_thread_with_connection, open_thread_with_custom_connection,
5108        send_message,
5109    };
5110    use acp_thread::{StubAgentConnection, ThreadStatus};
5111    use agent_servers::CODEX_ID;
5112    use assistant_text_thread::TextThreadStore;
5113    use feature_flags::FeatureFlagAppExt;
5114    use fs::FakeFs;
5115    use gpui::{TestAppContext, VisualTestContext};
5116    use project::Project;
5117    use serde_json::json;
5118    use std::time::Instant;
5119    use workspace::MultiWorkspace;
5120
5121    #[gpui::test]
5122    async fn test_active_thread_serialize_and_load_round_trip(cx: &mut TestAppContext) {
5123        init_test(cx);
5124        cx.update(|cx| {
5125            cx.update_flags(true, vec!["agent-v2".to_string()]);
5126            agent::ThreadStore::init_global(cx);
5127            language_model::LanguageModelRegistry::test(cx);
5128        });
5129
5130        // --- Create a MultiWorkspace window with two workspaces ---
5131        let fs = FakeFs::new(cx.executor());
5132        let project_a = Project::test(fs.clone(), [], cx).await;
5133        let project_b = Project::test(fs, [], cx).await;
5134
5135        let multi_workspace =
5136            cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
5137
5138        let workspace_a = multi_workspace
5139            .read_with(cx, |multi_workspace, _cx| {
5140                multi_workspace.workspace().clone()
5141            })
5142            .unwrap();
5143
5144        let workspace_b = multi_workspace
5145            .update(cx, |multi_workspace, window, cx| {
5146                multi_workspace.test_add_workspace(project_b.clone(), window, cx)
5147            })
5148            .unwrap();
5149
5150        workspace_a.update(cx, |workspace, _cx| {
5151            workspace.set_random_database_id();
5152        });
5153        workspace_b.update(cx, |workspace, _cx| {
5154            workspace.set_random_database_id();
5155        });
5156
5157        let cx = &mut VisualTestContext::from_window(multi_workspace.into(), cx);
5158
5159        // --- Set up workspace A: with an active thread ---
5160        let panel_a = workspace_a.update_in(cx, |workspace, window, cx| {
5161            let text_thread_store = cx.new(|cx| TextThreadStore::fake(project_a.clone(), cx));
5162            cx.new(|cx| AgentPanel::new(workspace, text_thread_store, None, window, cx))
5163        });
5164
5165        panel_a.update_in(cx, |panel, window, cx| {
5166            panel.open_external_thread_with_server(
5167                Rc::new(StubAgentServer::default_response()),
5168                window,
5169                cx,
5170            );
5171        });
5172
5173        cx.run_until_parked();
5174
5175        panel_a.read_with(cx, |panel, cx| {
5176            assert!(
5177                panel.active_agent_thread(cx).is_some(),
5178                "workspace A should have an active thread after connection"
5179            );
5180        });
5181
5182        let agent_type_a = panel_a.read_with(cx, |panel, _cx| panel.selected_agent_type.clone());
5183
5184        // --- Set up workspace B: ClaudeCode, no active thread ---
5185        let panel_b = workspace_b.update_in(cx, |workspace, window, cx| {
5186            let text_thread_store = cx.new(|cx| TextThreadStore::fake(project_b.clone(), cx));
5187            cx.new(|cx| AgentPanel::new(workspace, text_thread_store, None, window, cx))
5188        });
5189
5190        panel_b.update(cx, |panel, _cx| {
5191            panel.selected_agent_type = AgentType::Custom {
5192                id: "claude-acp".into(),
5193            };
5194        });
5195
5196        // --- Serialize both panels ---
5197        panel_a.update(cx, |panel, cx| panel.serialize(cx));
5198        panel_b.update(cx, |panel, cx| panel.serialize(cx));
5199        cx.run_until_parked();
5200
5201        // --- Load fresh panels for each workspace and verify independent state ---
5202        let prompt_builder = Arc::new(prompt_store::PromptBuilder::new(None).unwrap());
5203
5204        let async_cx = cx.update(|window, cx| window.to_async(cx));
5205        let loaded_a = AgentPanel::load(workspace_a.downgrade(), prompt_builder.clone(), async_cx)
5206            .await
5207            .expect("panel A load should succeed");
5208        cx.run_until_parked();
5209
5210        let async_cx = cx.update(|window, cx| window.to_async(cx));
5211        let loaded_b = AgentPanel::load(workspace_b.downgrade(), prompt_builder.clone(), async_cx)
5212            .await
5213            .expect("panel B load should succeed");
5214        cx.run_until_parked();
5215
5216        // Workspace A should restore its thread and agent type
5217        loaded_a.read_with(cx, |panel, _cx| {
5218            assert_eq!(
5219                panel.selected_agent_type, agent_type_a,
5220                "workspace A agent type should be restored"
5221            );
5222            assert!(
5223                panel.active_conversation_view().is_some(),
5224                "workspace A should have its active thread restored"
5225            );
5226        });
5227
5228        // Workspace B should restore its own agent type, with no thread
5229        loaded_b.read_with(cx, |panel, _cx| {
5230            assert_eq!(
5231                panel.selected_agent_type,
5232                AgentType::Custom {
5233                    id: "claude-acp".into()
5234                },
5235                "workspace B agent type should be restored"
5236            );
5237            assert!(
5238                panel.active_conversation_view().is_none(),
5239                "workspace B should have no active thread"
5240            );
5241        });
5242    }
5243
5244    // Simple regression test
5245    #[gpui::test]
5246    async fn test_new_text_thread_action_handler(cx: &mut TestAppContext) {
5247        init_test(cx);
5248
5249        let fs = FakeFs::new(cx.executor());
5250
5251        cx.update(|cx| {
5252            cx.update_flags(true, vec!["agent-v2".to_string()]);
5253            agent::ThreadStore::init_global(cx);
5254            language_model::LanguageModelRegistry::test(cx);
5255            let slash_command_registry =
5256                assistant_slash_command::SlashCommandRegistry::default_global(cx);
5257            slash_command_registry
5258                .register_command(assistant_slash_commands::DefaultSlashCommand, false);
5259            <dyn fs::Fs>::set_global(fs.clone(), cx);
5260        });
5261
5262        let project = Project::test(fs.clone(), [], cx).await;
5263
5264        let multi_workspace =
5265            cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
5266
5267        let workspace_a = multi_workspace
5268            .read_with(cx, |multi_workspace, _cx| {
5269                multi_workspace.workspace().clone()
5270            })
5271            .unwrap();
5272
5273        let cx = &mut VisualTestContext::from_window(multi_workspace.into(), cx);
5274
5275        workspace_a.update_in(cx, |workspace, window, cx| {
5276            let text_thread_store = cx.new(|cx| TextThreadStore::fake(project.clone(), cx));
5277            let panel =
5278                cx.new(|cx| AgentPanel::new(workspace, text_thread_store, None, window, cx));
5279            workspace.add_panel(panel, window, cx);
5280        });
5281
5282        cx.run_until_parked();
5283
5284        workspace_a.update_in(cx, |_, window, cx| {
5285            window.dispatch_action(NewTextThread.boxed_clone(), cx);
5286        });
5287
5288        cx.run_until_parked();
5289    }
5290
5291    /// Extracts the text from a Text content block, panicking if it's not Text.
5292    fn expect_text_block(block: &acp::ContentBlock) -> &str {
5293        match block {
5294            acp::ContentBlock::Text(t) => t.text.as_str(),
5295            other => panic!("expected Text block, got {:?}", other),
5296        }
5297    }
5298
5299    /// Extracts the (text_content, uri) from a Resource content block, panicking
5300    /// if it's not a TextResourceContents resource.
5301    fn expect_resource_block(block: &acp::ContentBlock) -> (&str, &str) {
5302        match block {
5303            acp::ContentBlock::Resource(r) => match &r.resource {
5304                acp::EmbeddedResourceResource::TextResourceContents(t) => {
5305                    (t.text.as_str(), t.uri.as_str())
5306                }
5307                other => panic!("expected TextResourceContents, got {:?}", other),
5308            },
5309            other => panic!("expected Resource block, got {:?}", other),
5310        }
5311    }
5312
5313    #[test]
5314    fn test_build_conflict_resolution_prompt_single_conflict() {
5315        let conflicts = vec![ConflictContent {
5316            file_path: "src/main.rs".to_string(),
5317            conflict_text: "<<<<<<< HEAD\nlet x = 1;\n=======\nlet x = 2;\n>>>>>>> feature"
5318                .to_string(),
5319            ours_branch_name: "HEAD".to_string(),
5320            theirs_branch_name: "feature".to_string(),
5321        }];
5322
5323        let blocks = build_conflict_resolution_prompt(&conflicts);
5324        // 2 Text blocks + 1 ResourceLink + 1 Resource for the conflict
5325        assert_eq!(
5326            blocks.len(),
5327            4,
5328            "expected 2 text + 1 resource link + 1 resource block"
5329        );
5330
5331        let intro_text = expect_text_block(&blocks[0]);
5332        assert!(
5333            intro_text.contains("Please resolve the following merge conflict in"),
5334            "prompt should include single-conflict intro text"
5335        );
5336
5337        match &blocks[1] {
5338            acp::ContentBlock::ResourceLink(link) => {
5339                assert!(
5340                    link.uri.contains("file://"),
5341                    "resource link URI should use file scheme"
5342                );
5343                assert!(
5344                    link.uri.contains("main.rs"),
5345                    "resource link URI should reference file path"
5346                );
5347            }
5348            other => panic!("expected ResourceLink block, got {:?}", other),
5349        }
5350
5351        let body_text = expect_text_block(&blocks[2]);
5352        assert!(
5353            body_text.contains("`HEAD` (ours)"),
5354            "prompt should mention ours branch"
5355        );
5356        assert!(
5357            body_text.contains("`feature` (theirs)"),
5358            "prompt should mention theirs branch"
5359        );
5360        assert!(
5361            body_text.contains("editing the file directly"),
5362            "prompt should instruct the agent to edit the file"
5363        );
5364
5365        let (resource_text, resource_uri) = expect_resource_block(&blocks[3]);
5366        assert!(
5367            resource_text.contains("<<<<<<< HEAD"),
5368            "resource should contain the conflict text"
5369        );
5370        assert!(
5371            resource_uri.contains("merge-conflict"),
5372            "resource URI should use the merge-conflict scheme"
5373        );
5374        assert!(
5375            resource_uri.contains("main.rs"),
5376            "resource URI should reference the file path"
5377        );
5378    }
5379
5380    #[test]
5381    fn test_build_conflict_resolution_prompt_multiple_conflicts_same_file() {
5382        let conflicts = vec![
5383            ConflictContent {
5384                file_path: "src/lib.rs".to_string(),
5385                conflict_text: "<<<<<<< main\nfn a() {}\n=======\nfn a_v2() {}\n>>>>>>> dev"
5386                    .to_string(),
5387                ours_branch_name: "main".to_string(),
5388                theirs_branch_name: "dev".to_string(),
5389            },
5390            ConflictContent {
5391                file_path: "src/lib.rs".to_string(),
5392                conflict_text: "<<<<<<< main\nfn b() {}\n=======\nfn b_v2() {}\n>>>>>>> dev"
5393                    .to_string(),
5394                ours_branch_name: "main".to_string(),
5395                theirs_branch_name: "dev".to_string(),
5396            },
5397        ];
5398
5399        let blocks = build_conflict_resolution_prompt(&conflicts);
5400        // 1 Text instruction + 2 Resource blocks
5401        assert_eq!(blocks.len(), 3, "expected 1 text + 2 resource blocks");
5402
5403        let text = expect_text_block(&blocks[0]);
5404        assert!(
5405            text.contains("all 2 merge conflicts"),
5406            "prompt should mention the total count"
5407        );
5408        assert!(
5409            text.contains("`main` (ours)"),
5410            "prompt should mention ours branch"
5411        );
5412        assert!(
5413            text.contains("`dev` (theirs)"),
5414            "prompt should mention theirs branch"
5415        );
5416        // Single file, so "file" not "files"
5417        assert!(
5418            text.contains("file directly"),
5419            "single file should use singular 'file'"
5420        );
5421
5422        let (resource_a, _) = expect_resource_block(&blocks[1]);
5423        let (resource_b, _) = expect_resource_block(&blocks[2]);
5424        assert!(
5425            resource_a.contains("fn a()"),
5426            "first resource should contain first conflict"
5427        );
5428        assert!(
5429            resource_b.contains("fn b()"),
5430            "second resource should contain second conflict"
5431        );
5432    }
5433
5434    #[test]
5435    fn test_build_conflict_resolution_prompt_multiple_conflicts_different_files() {
5436        let conflicts = vec![
5437            ConflictContent {
5438                file_path: "src/a.rs".to_string(),
5439                conflict_text: "<<<<<<< main\nA\n=======\nB\n>>>>>>> dev".to_string(),
5440                ours_branch_name: "main".to_string(),
5441                theirs_branch_name: "dev".to_string(),
5442            },
5443            ConflictContent {
5444                file_path: "src/b.rs".to_string(),
5445                conflict_text: "<<<<<<< main\nC\n=======\nD\n>>>>>>> dev".to_string(),
5446                ours_branch_name: "main".to_string(),
5447                theirs_branch_name: "dev".to_string(),
5448            },
5449        ];
5450
5451        let blocks = build_conflict_resolution_prompt(&conflicts);
5452        // 1 Text instruction + 2 Resource blocks
5453        assert_eq!(blocks.len(), 3, "expected 1 text + 2 resource blocks");
5454
5455        let text = expect_text_block(&blocks[0]);
5456        assert!(
5457            text.contains("files directly"),
5458            "multiple files should use plural 'files'"
5459        );
5460
5461        let (_, uri_a) = expect_resource_block(&blocks[1]);
5462        let (_, uri_b) = expect_resource_block(&blocks[2]);
5463        assert!(
5464            uri_a.contains("a.rs"),
5465            "first resource URI should reference a.rs"
5466        );
5467        assert!(
5468            uri_b.contains("b.rs"),
5469            "second resource URI should reference b.rs"
5470        );
5471    }
5472
5473    #[test]
5474    fn test_build_conflicted_files_resolution_prompt_file_paths_only() {
5475        let file_paths = vec![
5476            "src/main.rs".to_string(),
5477            "src/lib.rs".to_string(),
5478            "tests/integration.rs".to_string(),
5479        ];
5480
5481        let blocks = build_conflicted_files_resolution_prompt(&file_paths);
5482        // 1 instruction Text block + (ResourceLink + newline Text) per file
5483        assert_eq!(
5484            blocks.len(),
5485            1 + (file_paths.len() * 2),
5486            "expected instruction text plus resource links and separators"
5487        );
5488
5489        let text = expect_text_block(&blocks[0]);
5490        assert!(
5491            text.contains("unresolved merge conflicts"),
5492            "prompt should describe the task"
5493        );
5494        assert!(
5495            text.contains("conflict markers"),
5496            "prompt should mention conflict markers"
5497        );
5498
5499        for (index, path) in file_paths.iter().enumerate() {
5500            let link_index = 1 + (index * 2);
5501            let newline_index = link_index + 1;
5502
5503            match &blocks[link_index] {
5504                acp::ContentBlock::ResourceLink(link) => {
5505                    assert!(
5506                        link.uri.contains("file://"),
5507                        "resource link URI should use file scheme"
5508                    );
5509                    assert!(
5510                        link.uri.contains(path),
5511                        "resource link URI should reference file path: {path}"
5512                    );
5513                }
5514                other => panic!(
5515                    "expected ResourceLink block at index {}, got {:?}",
5516                    link_index, other
5517                ),
5518            }
5519
5520            let separator = expect_text_block(&blocks[newline_index]);
5521            assert_eq!(
5522                separator, "\n",
5523                "expected newline separator after each file"
5524            );
5525        }
5526    }
5527
5528    #[test]
5529    fn test_build_conflict_resolution_prompt_empty_conflicts() {
5530        let blocks = build_conflict_resolution_prompt(&[]);
5531        assert!(
5532            blocks.is_empty(),
5533            "empty conflicts should produce no blocks, got {} blocks",
5534            blocks.len()
5535        );
5536    }
5537
5538    #[test]
5539    fn test_build_conflicted_files_resolution_prompt_empty_paths() {
5540        let blocks = build_conflicted_files_resolution_prompt(&[]);
5541        assert!(
5542            blocks.is_empty(),
5543            "empty paths should produce no blocks, got {} blocks",
5544            blocks.len()
5545        );
5546    }
5547
5548    #[test]
5549    fn test_conflict_resource_block_structure() {
5550        let conflict = ConflictContent {
5551            file_path: "src/utils.rs".to_string(),
5552            conflict_text: "<<<<<<< HEAD\nold code\n=======\nnew code\n>>>>>>> branch".to_string(),
5553            ours_branch_name: "HEAD".to_string(),
5554            theirs_branch_name: "branch".to_string(),
5555        };
5556
5557        let block = conflict_resource_block(&conflict);
5558        let (text, uri) = expect_resource_block(&block);
5559
5560        assert_eq!(
5561            text, conflict.conflict_text,
5562            "resource text should be the raw conflict"
5563        );
5564        assert!(
5565            uri.starts_with("zed:///agent/merge-conflict"),
5566            "URI should use the zed merge-conflict scheme, got: {uri}"
5567        );
5568        assert!(uri.contains("utils.rs"), "URI should encode the file path");
5569    }
5570
5571    fn open_generating_thread_with_loadable_connection(
5572        panel: &Entity<AgentPanel>,
5573        connection: &StubAgentConnection,
5574        cx: &mut VisualTestContext,
5575    ) -> acp::SessionId {
5576        open_thread_with_custom_connection(panel, connection.clone(), cx);
5577        let session_id = active_session_id(panel, cx);
5578        send_message(panel, cx);
5579        cx.update(|_, cx| {
5580            connection.send_update(
5581                session_id.clone(),
5582                acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new("done".into())),
5583                cx,
5584            );
5585        });
5586        cx.run_until_parked();
5587        session_id
5588    }
5589
5590    fn open_idle_thread_with_non_loadable_connection(
5591        panel: &Entity<AgentPanel>,
5592        connection: &StubAgentConnection,
5593        cx: &mut VisualTestContext,
5594    ) -> acp::SessionId {
5595        open_thread_with_custom_connection(panel, connection.clone(), cx);
5596        let session_id = active_session_id(panel, cx);
5597
5598        connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
5599            acp::ContentChunk::new("done".into()),
5600        )]);
5601        send_message(panel, cx);
5602
5603        session_id
5604    }
5605
5606    async fn setup_panel(cx: &mut TestAppContext) -> (Entity<AgentPanel>, VisualTestContext) {
5607        init_test(cx);
5608        cx.update(|cx| {
5609            cx.update_flags(true, vec!["agent-v2".to_string()]);
5610            agent::ThreadStore::init_global(cx);
5611            language_model::LanguageModelRegistry::test(cx);
5612        });
5613
5614        let fs = FakeFs::new(cx.executor());
5615        let project = Project::test(fs.clone(), [], cx).await;
5616
5617        let multi_workspace =
5618            cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
5619
5620        let workspace = multi_workspace
5621            .read_with(cx, |mw, _cx| mw.workspace().clone())
5622            .unwrap();
5623
5624        let mut cx = VisualTestContext::from_window(multi_workspace.into(), cx);
5625
5626        let panel = workspace.update_in(&mut cx, |workspace, window, cx| {
5627            let text_thread_store = cx.new(|cx| TextThreadStore::fake(project.clone(), cx));
5628            cx.new(|cx| AgentPanel::new(workspace, text_thread_store, None, window, cx))
5629        });
5630
5631        (panel, cx)
5632    }
5633
5634    #[gpui::test]
5635    async fn test_running_thread_retained_when_navigating_away(cx: &mut TestAppContext) {
5636        let (panel, mut cx) = setup_panel(cx).await;
5637
5638        let connection_a = StubAgentConnection::new();
5639        open_thread_with_connection(&panel, connection_a.clone(), &mut cx);
5640        send_message(&panel, &mut cx);
5641
5642        let session_id_a = active_session_id(&panel, &cx);
5643
5644        // Send a chunk to keep thread A generating (don't end the turn).
5645        cx.update(|_, cx| {
5646            connection_a.send_update(
5647                session_id_a.clone(),
5648                acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new("chunk".into())),
5649                cx,
5650            );
5651        });
5652        cx.run_until_parked();
5653
5654        // Verify thread A is generating.
5655        panel.read_with(&cx, |panel, cx| {
5656            let thread = panel.active_agent_thread(cx).unwrap();
5657            assert_eq!(thread.read(cx).status(), ThreadStatus::Generating);
5658            assert!(panel.background_threads.is_empty());
5659        });
5660
5661        // Open a new thread B — thread A should be retained in background.
5662        let connection_b = StubAgentConnection::new();
5663        open_thread_with_connection(&panel, connection_b, &mut cx);
5664
5665        panel.read_with(&cx, |panel, _cx| {
5666            assert_eq!(
5667                panel.background_threads.len(),
5668                1,
5669                "Running thread A should be retained in background_views"
5670            );
5671            assert!(
5672                panel.background_threads.contains_key(&session_id_a),
5673                "Background view should be keyed by thread A's session ID"
5674            );
5675        });
5676    }
5677
5678    #[gpui::test]
5679    async fn test_idle_non_loadable_thread_retained_when_navigating_away(cx: &mut TestAppContext) {
5680        let (panel, mut cx) = setup_panel(cx).await;
5681
5682        let connection_a = StubAgentConnection::new();
5683        connection_a.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
5684            acp::ContentChunk::new("Response".into()),
5685        )]);
5686        open_thread_with_connection(&panel, connection_a, &mut cx);
5687        send_message(&panel, &mut cx);
5688
5689        let weak_view_a = panel.read_with(&cx, |panel, _cx| {
5690            panel.active_conversation_view().unwrap().downgrade()
5691        });
5692        let session_id_a = active_session_id(&panel, &cx);
5693
5694        // Thread A should be idle (auto-completed via set_next_prompt_updates).
5695        panel.read_with(&cx, |panel, cx| {
5696            let thread = panel.active_agent_thread(cx).unwrap();
5697            assert_eq!(thread.read(cx).status(), ThreadStatus::Idle);
5698        });
5699
5700        // Open a new thread B — thread A should be retained because it is not loadable.
5701        let connection_b = StubAgentConnection::new();
5702        open_thread_with_connection(&panel, connection_b, &mut cx);
5703
5704        panel.read_with(&cx, |panel, _cx| {
5705            assert_eq!(
5706                panel.background_threads.len(),
5707                1,
5708                "Idle non-loadable thread A should be retained in background_views"
5709            );
5710            assert!(
5711                panel.background_threads.contains_key(&session_id_a),
5712                "Background view should be keyed by thread A's session ID"
5713            );
5714        });
5715
5716        assert!(
5717            weak_view_a.upgrade().is_some(),
5718            "Idle non-loadable ConnectionView should still be retained"
5719        );
5720    }
5721
5722    #[gpui::test]
5723    async fn test_background_thread_promoted_via_load(cx: &mut TestAppContext) {
5724        let (panel, mut cx) = setup_panel(cx).await;
5725
5726        let connection_a = StubAgentConnection::new();
5727        open_thread_with_connection(&panel, connection_a.clone(), &mut cx);
5728        send_message(&panel, &mut cx);
5729
5730        let session_id_a = active_session_id(&panel, &cx);
5731
5732        // Keep thread A generating.
5733        cx.update(|_, cx| {
5734            connection_a.send_update(
5735                session_id_a.clone(),
5736                acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new("chunk".into())),
5737                cx,
5738            );
5739        });
5740        cx.run_until_parked();
5741
5742        // Open thread B — thread A goes to background.
5743        let connection_b = StubAgentConnection::new();
5744        open_thread_with_connection(&panel, connection_b, &mut cx);
5745
5746        let session_id_b = active_session_id(&panel, &cx);
5747
5748        panel.read_with(&cx, |panel, _cx| {
5749            assert_eq!(panel.background_threads.len(), 1);
5750            assert!(panel.background_threads.contains_key(&session_id_a));
5751        });
5752
5753        // Load thread A back via load_agent_thread — should promote from background.
5754        panel.update_in(&mut cx, |panel, window, cx| {
5755            panel.load_agent_thread(
5756                panel.selected_agent().expect("selected agent must be set"),
5757                session_id_a.clone(),
5758                None,
5759                None,
5760                true,
5761                window,
5762                cx,
5763            );
5764        });
5765
5766        // Thread A should now be the active view, promoted from background.
5767        let active_session = active_session_id(&panel, &cx);
5768        assert_eq!(
5769            active_session, session_id_a,
5770            "Thread A should be the active thread after promotion"
5771        );
5772
5773        panel.read_with(&cx, |panel, _cx| {
5774            assert!(
5775                !panel.background_threads.contains_key(&session_id_a),
5776                "Promoted thread A should no longer be in background_views"
5777            );
5778            assert!(
5779                panel.background_threads.contains_key(&session_id_b),
5780                "Thread B (idle, non-loadable) should remain retained in background_views"
5781            );
5782        });
5783    }
5784
5785    #[gpui::test]
5786    async fn test_cleanup_background_threads_keeps_five_most_recent_idle_loadable_threads(
5787        cx: &mut TestAppContext,
5788    ) {
5789        let (panel, mut cx) = setup_panel(cx).await;
5790        let connection = StubAgentConnection::new()
5791            .with_supports_load_session(true)
5792            .with_agent_id("loadable-stub".into())
5793            .with_telemetry_id("loadable-stub".into());
5794        let mut session_ids = Vec::new();
5795
5796        for _ in 0..7 {
5797            session_ids.push(open_generating_thread_with_loadable_connection(
5798                &panel,
5799                &connection,
5800                &mut cx,
5801            ));
5802        }
5803
5804        let base_time = Instant::now();
5805
5806        for session_id in session_ids.iter().take(6) {
5807            connection.end_turn(session_id.clone(), acp::StopReason::EndTurn);
5808        }
5809        cx.run_until_parked();
5810
5811        panel.update(&mut cx, |panel, cx| {
5812            for (index, session_id) in session_ids.iter().take(6).enumerate() {
5813                let conversation_view = panel
5814                    .background_threads
5815                    .get(session_id)
5816                    .expect("background thread should exist")
5817                    .clone();
5818                conversation_view.update(cx, |view, cx| {
5819                    view.set_updated_at(base_time + Duration::from_secs(index as u64), cx);
5820                });
5821            }
5822            panel.cleanup_background_threads(cx);
5823        });
5824
5825        panel.read_with(&cx, |panel, _cx| {
5826            assert_eq!(
5827                panel.background_threads.len(),
5828                5,
5829                "cleanup should keep at most five idle loadable background threads"
5830            );
5831            assert!(
5832                !panel.background_threads.contains_key(&session_ids[0]),
5833                "oldest idle loadable background thread should be removed"
5834            );
5835            for session_id in &session_ids[1..6] {
5836                assert!(
5837                    panel.background_threads.contains_key(session_id),
5838                    "more recent idle loadable background threads should be retained"
5839                );
5840            }
5841            assert!(
5842                !panel.background_threads.contains_key(&session_ids[6]),
5843                "the active thread should not also be stored as a background thread"
5844            );
5845        });
5846    }
5847
5848    #[gpui::test]
5849    async fn test_cleanup_background_threads_preserves_idle_non_loadable_threads(
5850        cx: &mut TestAppContext,
5851    ) {
5852        let (panel, mut cx) = setup_panel(cx).await;
5853
5854        let non_loadable_connection = StubAgentConnection::new();
5855        let non_loadable_session_id = open_idle_thread_with_non_loadable_connection(
5856            &panel,
5857            &non_loadable_connection,
5858            &mut cx,
5859        );
5860
5861        let loadable_connection = StubAgentConnection::new()
5862            .with_supports_load_session(true)
5863            .with_agent_id("loadable-stub".into())
5864            .with_telemetry_id("loadable-stub".into());
5865        let mut loadable_session_ids = Vec::new();
5866
5867        for _ in 0..7 {
5868            loadable_session_ids.push(open_generating_thread_with_loadable_connection(
5869                &panel,
5870                &loadable_connection,
5871                &mut cx,
5872            ));
5873        }
5874
5875        let base_time = Instant::now();
5876
5877        for session_id in loadable_session_ids.iter().take(6) {
5878            loadable_connection.end_turn(session_id.clone(), acp::StopReason::EndTurn);
5879        }
5880        cx.run_until_parked();
5881
5882        panel.update(&mut cx, |panel, cx| {
5883            for (index, session_id) in loadable_session_ids.iter().take(6).enumerate() {
5884                let conversation_view = panel
5885                    .background_threads
5886                    .get(session_id)
5887                    .expect("background thread should exist")
5888                    .clone();
5889                conversation_view.update(cx, |view, cx| {
5890                    view.set_updated_at(base_time + Duration::from_secs(index as u64), cx);
5891                });
5892            }
5893            panel.cleanup_background_threads(cx);
5894        });
5895
5896        panel.read_with(&cx, |panel, _cx| {
5897            assert_eq!(
5898                panel.background_threads.len(),
5899                6,
5900                "cleanup should keep the non-loadable idle thread in addition to five loadable ones"
5901            );
5902            assert!(
5903                panel
5904                    .background_threads
5905                    .contains_key(&non_loadable_session_id),
5906                "idle non-loadable background threads should not be cleanup candidates"
5907            );
5908            assert!(
5909                !panel
5910                    .background_threads
5911                    .contains_key(&loadable_session_ids[0]),
5912                "oldest idle loadable background thread should still be removed"
5913            );
5914            for session_id in &loadable_session_ids[1..6] {
5915                assert!(
5916                    panel.background_threads.contains_key(session_id),
5917                    "more recent idle loadable background threads should be retained"
5918                );
5919            }
5920            assert!(
5921                !panel
5922                    .background_threads
5923                    .contains_key(&loadable_session_ids[6]),
5924                "the active loadable thread should not also be stored as a background thread"
5925            );
5926        });
5927    }
5928
5929    #[gpui::test]
5930    async fn test_thread_target_local_project(cx: &mut TestAppContext) {
5931        init_test(cx);
5932        cx.update(|cx| {
5933            cx.update_flags(true, vec!["agent-v2".to_string()]);
5934            agent::ThreadStore::init_global(cx);
5935            language_model::LanguageModelRegistry::test(cx);
5936        });
5937
5938        let fs = FakeFs::new(cx.executor());
5939        fs.insert_tree(
5940            "/project",
5941            json!({
5942                ".git": {},
5943                "src": {
5944                    "main.rs": "fn main() {}"
5945                }
5946            }),
5947        )
5948        .await;
5949        fs.set_branch_name(Path::new("/project/.git"), Some("main"));
5950
5951        let project = Project::test(fs.clone(), [Path::new("/project")], cx).await;
5952
5953        let multi_workspace =
5954            cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
5955
5956        let workspace = multi_workspace
5957            .read_with(cx, |multi_workspace, _cx| {
5958                multi_workspace.workspace().clone()
5959            })
5960            .unwrap();
5961
5962        workspace.update(cx, |workspace, _cx| {
5963            workspace.set_random_database_id();
5964        });
5965
5966        let cx = &mut VisualTestContext::from_window(multi_workspace.into(), cx);
5967
5968        // Wait for the project to discover the git repository.
5969        cx.run_until_parked();
5970
5971        let panel = workspace.update_in(cx, |workspace, window, cx| {
5972            let text_thread_store = cx.new(|cx| TextThreadStore::fake(project.clone(), cx));
5973            let panel =
5974                cx.new(|cx| AgentPanel::new(workspace, text_thread_store, None, window, cx));
5975            workspace.add_panel(panel.clone(), window, cx);
5976            panel
5977        });
5978
5979        cx.run_until_parked();
5980
5981        // Default thread target should be LocalProject.
5982        panel.read_with(cx, |panel, _cx| {
5983            assert_eq!(
5984                *panel.start_thread_in(),
5985                StartThreadIn::LocalProject,
5986                "default thread target should be LocalProject"
5987            );
5988        });
5989
5990        // Start a new thread with the default LocalProject target.
5991        // Use StubAgentServer so the thread connects immediately in tests.
5992        panel.update_in(cx, |panel, window, cx| {
5993            panel.open_external_thread_with_server(
5994                Rc::new(StubAgentServer::default_response()),
5995                window,
5996                cx,
5997            );
5998        });
5999
6000        cx.run_until_parked();
6001
6002        // MultiWorkspace should still have exactly one workspace (no worktree created).
6003        multi_workspace
6004            .read_with(cx, |multi_workspace, _cx| {
6005                assert_eq!(
6006                    multi_workspace.workspaces().len(),
6007                    1,
6008                    "LocalProject should not create a new workspace"
6009                );
6010            })
6011            .unwrap();
6012
6013        // The thread should be active in the panel.
6014        panel.read_with(cx, |panel, cx| {
6015            assert!(
6016                panel.active_agent_thread(cx).is_some(),
6017                "a thread should be running in the current workspace"
6018            );
6019        });
6020
6021        // The thread target should still be LocalProject (unchanged).
6022        panel.read_with(cx, |panel, _cx| {
6023            assert_eq!(
6024                *panel.start_thread_in(),
6025                StartThreadIn::LocalProject,
6026                "thread target should remain LocalProject"
6027            );
6028        });
6029
6030        // No worktree creation status should be set.
6031        panel.read_with(cx, |panel, _cx| {
6032            assert!(
6033                panel.worktree_creation_status.is_none(),
6034                "no worktree creation should have occurred"
6035            );
6036        });
6037    }
6038
6039    #[gpui::test]
6040    async fn test_thread_target_serialization_round_trip(cx: &mut TestAppContext) {
6041        init_test(cx);
6042        cx.update(|cx| {
6043            cx.update_flags(true, vec!["agent-v2".to_string()]);
6044            agent::ThreadStore::init_global(cx);
6045            language_model::LanguageModelRegistry::test(cx);
6046        });
6047
6048        let fs = FakeFs::new(cx.executor());
6049        fs.insert_tree(
6050            "/project",
6051            json!({
6052                ".git": {},
6053                "src": {
6054                    "main.rs": "fn main() {}"
6055                }
6056            }),
6057        )
6058        .await;
6059        fs.set_branch_name(Path::new("/project/.git"), Some("main"));
6060
6061        let project = Project::test(fs.clone(), [Path::new("/project")], cx).await;
6062
6063        let multi_workspace =
6064            cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
6065
6066        let workspace = multi_workspace
6067            .read_with(cx, |multi_workspace, _cx| {
6068                multi_workspace.workspace().clone()
6069            })
6070            .unwrap();
6071
6072        workspace.update(cx, |workspace, _cx| {
6073            workspace.set_random_database_id();
6074        });
6075
6076        let cx = &mut VisualTestContext::from_window(multi_workspace.into(), cx);
6077
6078        // Wait for the project to discover the git repository.
6079        cx.run_until_parked();
6080
6081        let panel = workspace.update_in(cx, |workspace, window, cx| {
6082            let text_thread_store = cx.new(|cx| TextThreadStore::fake(project.clone(), cx));
6083            let panel =
6084                cx.new(|cx| AgentPanel::new(workspace, text_thread_store, None, window, cx));
6085            workspace.add_panel(panel.clone(), window, cx);
6086            panel
6087        });
6088
6089        cx.run_until_parked();
6090
6091        // Default should be LocalProject.
6092        panel.read_with(cx, |panel, _cx| {
6093            assert_eq!(*panel.start_thread_in(), StartThreadIn::LocalProject);
6094        });
6095
6096        // Change thread target to NewWorktree.
6097        panel.update_in(cx, |panel, window, cx| {
6098            panel.set_start_thread_in(&StartThreadIn::NewWorktree, window, cx);
6099        });
6100
6101        panel.read_with(cx, |panel, _cx| {
6102            assert_eq!(
6103                *panel.start_thread_in(),
6104                StartThreadIn::NewWorktree,
6105                "thread target should be NewWorktree after set_thread_target"
6106            );
6107        });
6108
6109        // Let serialization complete.
6110        cx.run_until_parked();
6111
6112        // Load a fresh panel from the serialized data.
6113        let prompt_builder = Arc::new(prompt_store::PromptBuilder::new(None).unwrap());
6114        let async_cx = cx.update(|window, cx| window.to_async(cx));
6115        let loaded_panel =
6116            AgentPanel::load(workspace.downgrade(), prompt_builder.clone(), async_cx)
6117                .await
6118                .expect("panel load should succeed");
6119        cx.run_until_parked();
6120
6121        loaded_panel.read_with(cx, |panel, _cx| {
6122            assert_eq!(
6123                *panel.start_thread_in(),
6124                StartThreadIn::NewWorktree,
6125                "thread target should survive serialization round-trip"
6126            );
6127        });
6128    }
6129
6130    #[gpui::test]
6131    async fn test_set_active_blocked_during_worktree_creation(cx: &mut TestAppContext) {
6132        init_test(cx);
6133
6134        let fs = FakeFs::new(cx.executor());
6135        cx.update(|cx| {
6136            cx.update_flags(true, vec!["agent-v2".to_string()]);
6137            agent::ThreadStore::init_global(cx);
6138            language_model::LanguageModelRegistry::test(cx);
6139            <dyn fs::Fs>::set_global(fs.clone(), cx);
6140        });
6141
6142        fs.insert_tree(
6143            "/project",
6144            json!({
6145                ".git": {},
6146                "src": {
6147                    "main.rs": "fn main() {}"
6148                }
6149            }),
6150        )
6151        .await;
6152
6153        let project = Project::test(fs.clone(), [Path::new("/project")], cx).await;
6154
6155        let multi_workspace =
6156            cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
6157
6158        let workspace = multi_workspace
6159            .read_with(cx, |multi_workspace, _cx| {
6160                multi_workspace.workspace().clone()
6161            })
6162            .unwrap();
6163
6164        let cx = &mut VisualTestContext::from_window(multi_workspace.into(), cx);
6165
6166        let panel = workspace.update_in(cx, |workspace, window, cx| {
6167            let text_thread_store = cx.new(|cx| TextThreadStore::fake(project.clone(), cx));
6168            let panel =
6169                cx.new(|cx| AgentPanel::new(workspace, text_thread_store, None, window, cx));
6170            workspace.add_panel(panel.clone(), window, cx);
6171            panel
6172        });
6173
6174        cx.run_until_parked();
6175
6176        // Simulate worktree creation in progress and reset to Uninitialized
6177        panel.update_in(cx, |panel, window, cx| {
6178            panel.worktree_creation_status = Some(WorktreeCreationStatus::Creating);
6179            panel.active_view = ActiveView::Uninitialized;
6180            Panel::set_active(panel, true, window, cx);
6181            assert!(
6182                matches!(panel.active_view, ActiveView::Uninitialized),
6183                "set_active should not create a thread while worktree is being created"
6184            );
6185        });
6186
6187        // Clear the creation status and use open_external_thread_with_server
6188        // (which bypasses new_agent_thread) to verify the panel can transition
6189        // out of Uninitialized. We can't call set_active directly because
6190        // new_agent_thread requires full agent server infrastructure.
6191        panel.update_in(cx, |panel, window, cx| {
6192            panel.worktree_creation_status = None;
6193            panel.active_view = ActiveView::Uninitialized;
6194            panel.open_external_thread_with_server(
6195                Rc::new(StubAgentServer::default_response()),
6196                window,
6197                cx,
6198            );
6199        });
6200
6201        cx.run_until_parked();
6202
6203        panel.read_with(cx, |panel, _cx| {
6204            assert!(
6205                !matches!(panel.active_view, ActiveView::Uninitialized),
6206                "panel should transition out of Uninitialized once worktree creation is cleared"
6207            );
6208        });
6209    }
6210
6211    #[test]
6212    fn test_deserialize_agent_type_variants() {
6213        assert_eq!(
6214            serde_json::from_str::<AgentType>(r#""NativeAgent""#).unwrap(),
6215            AgentType::NativeAgent,
6216        );
6217        assert_eq!(
6218            serde_json::from_str::<AgentType>(r#""TextThread""#).unwrap(),
6219            AgentType::TextThread,
6220        );
6221        assert_eq!(
6222            serde_json::from_str::<AgentType>(r#"{"Custom":{"name":"my-agent"}}"#).unwrap(),
6223            AgentType::Custom {
6224                id: "my-agent".into(),
6225            },
6226        );
6227    }
6228
6229    #[gpui::test]
6230    async fn test_worktree_creation_preserves_selected_agent(cx: &mut TestAppContext) {
6231        init_test(cx);
6232
6233        let app_state = cx.update(|cx| {
6234            cx.update_flags(true, vec!["agent-v2".to_string()]);
6235            agent::ThreadStore::init_global(cx);
6236            language_model::LanguageModelRegistry::test(cx);
6237
6238            let app_state = workspace::AppState::test(cx);
6239            workspace::init(app_state.clone(), cx);
6240            app_state
6241        });
6242
6243        let fs = app_state.fs.as_fake();
6244        fs.insert_tree(
6245            "/project",
6246            json!({
6247                ".git": {},
6248                "src": {
6249                    "main.rs": "fn main() {}"
6250                }
6251            }),
6252        )
6253        .await;
6254        fs.set_branch_name(Path::new("/project/.git"), Some("main"));
6255
6256        let project = Project::test(app_state.fs.clone(), [Path::new("/project")], cx).await;
6257
6258        let multi_workspace =
6259            cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
6260
6261        let workspace = multi_workspace
6262            .read_with(cx, |multi_workspace, _cx| {
6263                multi_workspace.workspace().clone()
6264            })
6265            .unwrap();
6266
6267        workspace.update(cx, |workspace, _cx| {
6268            workspace.set_random_database_id();
6269        });
6270
6271        // Register a callback so new workspaces also get an AgentPanel.
6272        cx.update(|cx| {
6273            cx.observe_new(
6274                |workspace: &mut Workspace,
6275                 window: Option<&mut Window>,
6276                 cx: &mut Context<Workspace>| {
6277                    if let Some(window) = window {
6278                        let project = workspace.project().clone();
6279                        let text_thread_store =
6280                            cx.new(|cx| TextThreadStore::fake(project.clone(), cx));
6281                        let panel = cx.new(|cx| {
6282                            AgentPanel::new(workspace, text_thread_store, None, window, cx)
6283                        });
6284                        workspace.add_panel(panel, window, cx);
6285                    }
6286                },
6287            )
6288            .detach();
6289        });
6290
6291        let cx = &mut VisualTestContext::from_window(multi_workspace.into(), cx);
6292
6293        // Wait for the project to discover the git repository.
6294        cx.run_until_parked();
6295
6296        let panel = workspace.update_in(cx, |workspace, window, cx| {
6297            let text_thread_store = cx.new(|cx| TextThreadStore::fake(project.clone(), cx));
6298            let panel =
6299                cx.new(|cx| AgentPanel::new(workspace, text_thread_store, None, window, cx));
6300            workspace.add_panel(panel.clone(), window, cx);
6301            panel
6302        });
6303
6304        cx.run_until_parked();
6305
6306        // Open a thread (needed so there's an active thread view).
6307        panel.update_in(cx, |panel, window, cx| {
6308            panel.open_external_thread_with_server(
6309                Rc::new(StubAgentServer::default_response()),
6310                window,
6311                cx,
6312            );
6313        });
6314
6315        cx.run_until_parked();
6316
6317        // Set the selected agent to Codex (a custom agent) and start_thread_in
6318        // to NewWorktree. We do this AFTER opening the thread because
6319        // open_external_thread_with_server overrides selected_agent_type.
6320        panel.update_in(cx, |panel, window, cx| {
6321            panel.selected_agent_type = AgentType::Custom {
6322                id: CODEX_ID.into(),
6323            };
6324            panel.set_start_thread_in(&StartThreadIn::NewWorktree, window, cx);
6325        });
6326
6327        // Verify the panel has the Codex agent selected.
6328        panel.read_with(cx, |panel, _cx| {
6329            assert_eq!(
6330                panel.selected_agent_type,
6331                AgentType::Custom {
6332                    id: CODEX_ID.into()
6333                },
6334            );
6335        });
6336
6337        // Directly call handle_worktree_creation_requested, which is what
6338        // handle_first_send_requested does when start_thread_in == NewWorktree.
6339        let content = vec![acp::ContentBlock::Text(acp::TextContent::new(
6340            "Hello from test",
6341        ))];
6342        panel.update_in(cx, |panel, window, cx| {
6343            panel.handle_worktree_creation_requested(content, window, cx);
6344        });
6345
6346        // Let the async worktree creation + workspace setup complete.
6347        cx.run_until_parked();
6348
6349        // Find the new workspace's AgentPanel and verify it used the Codex agent.
6350        let found_codex = multi_workspace
6351            .read_with(cx, |multi_workspace, cx| {
6352                // There should be more than one workspace now (the original + the new worktree).
6353                assert!(
6354                    multi_workspace.workspaces().len() > 1,
6355                    "expected a new workspace to have been created, found {}",
6356                    multi_workspace.workspaces().len(),
6357                );
6358
6359                // Check the newest workspace's panel for the correct agent.
6360                let new_workspace = multi_workspace
6361                    .workspaces()
6362                    .iter()
6363                    .find(|ws| ws.entity_id() != workspace.entity_id())
6364                    .expect("should find the new workspace");
6365                let new_panel = new_workspace
6366                    .read(cx)
6367                    .panel::<AgentPanel>(cx)
6368                    .expect("new workspace should have an AgentPanel");
6369
6370                new_panel.read(cx).selected_agent_type.clone()
6371            })
6372            .unwrap();
6373
6374        assert_eq!(
6375            found_codex,
6376            AgentType::Custom {
6377                id: CODEX_ID.into()
6378            },
6379            "the new worktree workspace should use the same agent (Codex) that was selected in the original panel",
6380        );
6381    }
6382
6383    #[gpui::test]
6384    async fn test_work_dirs_update_when_worktrees_change(cx: &mut TestAppContext) {
6385        use crate::thread_metadata_store::ThreadMetadataStore;
6386
6387        init_test(cx);
6388        cx.update(|cx| {
6389            cx.update_flags(true, vec!["agent-v2".to_string()]);
6390            agent::ThreadStore::init_global(cx);
6391            language_model::LanguageModelRegistry::test(cx);
6392        });
6393
6394        // Set up a project with one worktree.
6395        let fs = FakeFs::new(cx.executor());
6396        fs.insert_tree("/project_a", json!({ "file.txt": "" }))
6397            .await;
6398        let project = Project::test(fs.clone(), [Path::new("/project_a")], cx).await;
6399
6400        let multi_workspace =
6401            cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
6402        let workspace = multi_workspace
6403            .read_with(cx, |mw, _cx| mw.workspace().clone())
6404            .unwrap();
6405        let mut cx = VisualTestContext::from_window(multi_workspace.into(), cx);
6406
6407        let panel = workspace.update_in(&mut cx, |workspace, window, cx| {
6408            let text_thread_store = cx.new(|cx| TextThreadStore::fake(project.clone(), cx));
6409            cx.new(|cx| AgentPanel::new(workspace, text_thread_store, None, window, cx))
6410        });
6411
6412        // Open thread A and send a message. With empty next_prompt_updates it
6413        // stays generating, so opening B will move A to background_threads.
6414        let connection_a = StubAgentConnection::new().with_agent_id("agent-a".into());
6415        open_thread_with_custom_connection(&panel, connection_a.clone(), &mut cx);
6416        send_message(&panel, &mut cx);
6417        let session_id_a = active_session_id(&panel, &cx);
6418
6419        // Open thread C — thread A (generating) moves to background.
6420        // Thread C completes immediately (idle), then opening B moves C to background too.
6421        let connection_c = StubAgentConnection::new().with_agent_id("agent-c".into());
6422        connection_c.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
6423            acp::ContentChunk::new("done".into()),
6424        )]);
6425        open_thread_with_custom_connection(&panel, connection_c.clone(), &mut cx);
6426        send_message(&panel, &mut cx);
6427        let session_id_c = active_session_id(&panel, &cx);
6428
6429        // Snapshot thread C's initial work_dirs before adding worktrees.
6430        let initial_c_paths = panel.read_with(&cx, |panel, cx| {
6431            let thread = panel.active_agent_thread(cx).unwrap();
6432            thread.read(cx).work_dirs().cloned().unwrap()
6433        });
6434
6435        // Open thread B — thread C (idle, non-loadable) is retained in background.
6436        let connection_b = StubAgentConnection::new().with_agent_id("agent-b".into());
6437        open_thread_with_custom_connection(&panel, connection_b.clone(), &mut cx);
6438        send_message(&panel, &mut cx);
6439        let session_id_b = active_session_id(&panel, &cx);
6440
6441        let metadata_store = cx.update(|_, cx| ThreadMetadataStore::global(cx));
6442
6443        panel.read_with(&cx, |panel, _cx| {
6444            assert!(
6445                panel.background_threads.contains_key(&session_id_a),
6446                "Thread A should be in background_threads"
6447            );
6448            assert!(
6449                panel.background_threads.contains_key(&session_id_c),
6450                "Thread C should be in background_threads"
6451            );
6452        });
6453
6454        // Verify initial work_dirs for thread B contain only /project_a.
6455        let initial_b_paths = panel.read_with(&cx, |panel, cx| {
6456            let thread = panel.active_agent_thread(cx).unwrap();
6457            thread.read(cx).work_dirs().cloned().unwrap()
6458        });
6459        assert_eq!(
6460            initial_b_paths.ordered_paths().collect::<Vec<_>>(),
6461            vec![&PathBuf::from("/project_a")],
6462            "Thread B should initially have only /project_a"
6463        );
6464
6465        // Now add a second worktree to the project.
6466        fs.insert_tree("/project_b", json!({ "other.txt": "" }))
6467            .await;
6468        let (new_tree, _) = project
6469            .update(&mut cx, |project, cx| {
6470                project.find_or_create_worktree("/project_b", true, cx)
6471            })
6472            .await
6473            .unwrap();
6474        cx.read(|cx| new_tree.read(cx).as_local().unwrap().scan_complete())
6475            .await;
6476        cx.run_until_parked();
6477
6478        // Verify thread B's (active) work_dirs now include both worktrees.
6479        let updated_b_paths = panel.read_with(&cx, |panel, cx| {
6480            let thread = panel.active_agent_thread(cx).unwrap();
6481            thread.read(cx).work_dirs().cloned().unwrap()
6482        });
6483        let mut b_paths_sorted = updated_b_paths.ordered_paths().cloned().collect::<Vec<_>>();
6484        b_paths_sorted.sort();
6485        assert_eq!(
6486            b_paths_sorted,
6487            vec![PathBuf::from("/project_a"), PathBuf::from("/project_b")],
6488            "Thread B work_dirs should include both worktrees after adding /project_b"
6489        );
6490
6491        // Verify thread A's (background) work_dirs are also updated.
6492        let updated_a_paths = panel.read_with(&cx, |panel, cx| {
6493            let bg_view = panel.background_threads.get(&session_id_a).unwrap();
6494            let root_thread = bg_view.read(cx).root_thread(cx).unwrap();
6495            root_thread
6496                .read(cx)
6497                .thread
6498                .read(cx)
6499                .work_dirs()
6500                .cloned()
6501                .unwrap()
6502        });
6503        let mut a_paths_sorted = updated_a_paths.ordered_paths().cloned().collect::<Vec<_>>();
6504        a_paths_sorted.sort();
6505        assert_eq!(
6506            a_paths_sorted,
6507            vec![PathBuf::from("/project_a"), PathBuf::from("/project_b")],
6508            "Thread A work_dirs should include both worktrees after adding /project_b"
6509        );
6510
6511        // Verify thread C  was NOT updated.
6512        let unchanged_c_paths = panel.read_with(&cx, |panel, cx| {
6513            let bg_view = panel.background_threads.get(&session_id_c).unwrap();
6514            let root_thread = bg_view.read(cx).root_thread(cx).unwrap();
6515            root_thread
6516                .read(cx)
6517                .thread
6518                .read(cx)
6519                .work_dirs()
6520                .cloned()
6521                .unwrap()
6522        });
6523        assert_eq!(
6524            unchanged_c_paths, initial_c_paths,
6525            "Thread C (idle background) work_dirs should not change when worktrees change"
6526        );
6527
6528        // Verify the metadata store reflects the new paths for running threads only.
6529        cx.run_until_parked();
6530        for (label, session_id) in [("thread B", &session_id_b), ("thread A", &session_id_a)] {
6531            let metadata_paths = metadata_store.read_with(&cx, |store, _cx| {
6532                let metadata = store
6533                    .entry(session_id)
6534                    .unwrap_or_else(|| panic!("{label} thread metadata should exist"));
6535                metadata.folder_paths.clone()
6536            });
6537            let mut sorted = metadata_paths.ordered_paths().cloned().collect::<Vec<_>>();
6538            sorted.sort();
6539            assert_eq!(
6540                sorted,
6541                vec![PathBuf::from("/project_a"), PathBuf::from("/project_b")],
6542                "{label} thread metadata folder_paths should include both worktrees"
6543            );
6544        }
6545
6546        // Now remove a worktree and verify work_dirs shrink.
6547        let worktree_b_id = new_tree.read_with(&cx, |tree, _| tree.id());
6548        project.update(&mut cx, |project, cx| {
6549            project.remove_worktree(worktree_b_id, cx);
6550        });
6551        cx.run_until_parked();
6552
6553        let after_remove_b = panel.read_with(&cx, |panel, cx| {
6554            let thread = panel.active_agent_thread(cx).unwrap();
6555            thread.read(cx).work_dirs().cloned().unwrap()
6556        });
6557        assert_eq!(
6558            after_remove_b.ordered_paths().collect::<Vec<_>>(),
6559            vec![&PathBuf::from("/project_a")],
6560            "Thread B work_dirs should revert to only /project_a after removing /project_b"
6561        );
6562
6563        let after_remove_a = panel.read_with(&cx, |panel, cx| {
6564            let bg_view = panel.background_threads.get(&session_id_a).unwrap();
6565            let root_thread = bg_view.read(cx).root_thread(cx).unwrap();
6566            root_thread
6567                .read(cx)
6568                .thread
6569                .read(cx)
6570                .work_dirs()
6571                .cloned()
6572                .unwrap()
6573        });
6574        assert_eq!(
6575            after_remove_a.ordered_paths().collect::<Vec<_>>(),
6576            vec![&PathBuf::from("/project_a")],
6577            "Thread A work_dirs should revert to only /project_a after removing /project_b"
6578        );
6579    }
6580}