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 fn remove_thread(&mut self, session_id: &acp::SessionId, cx: &mut Context<Self>) {
2106        self.background_threads.remove(session_id);
2107        cx.notify();
2108    }
2109
2110    pub(crate) fn active_native_agent_thread(&self, cx: &App) -> Option<Entity<agent::Thread>> {
2111        match &self.active_view {
2112            ActiveView::AgentThread {
2113                conversation_view, ..
2114            } => conversation_view.read(cx).as_native_thread(cx),
2115            _ => None,
2116        }
2117    }
2118
2119    pub(crate) fn active_text_thread_editor(&self) -> Option<Entity<TextThreadEditor>> {
2120        match &self.active_view {
2121            ActiveView::TextThread {
2122                text_thread_editor, ..
2123            } => Some(text_thread_editor.clone()),
2124            _ => None,
2125        }
2126    }
2127
2128    fn set_active_view(
2129        &mut self,
2130        new_view: ActiveView,
2131        focus: bool,
2132        window: &mut Window,
2133        cx: &mut Context<Self>,
2134    ) {
2135        let was_in_agent_history = matches!(
2136            self.active_view,
2137            ActiveView::History {
2138                history: History::AgentThreads { .. }
2139            }
2140        );
2141        let current_is_uninitialized = matches!(self.active_view, ActiveView::Uninitialized);
2142        let current_is_history = matches!(self.active_view, ActiveView::History { .. });
2143        let new_is_history = matches!(new_view, ActiveView::History { .. });
2144
2145        let current_is_config = matches!(self.active_view, ActiveView::Configuration);
2146        let new_is_config = matches!(new_view, ActiveView::Configuration);
2147
2148        let current_is_overlay = current_is_history || current_is_config;
2149        let new_is_overlay = new_is_history || new_is_config;
2150
2151        if current_is_uninitialized || (current_is_overlay && !new_is_overlay) {
2152            self.active_view = new_view;
2153        } else if !current_is_overlay && new_is_overlay {
2154            self.previous_view = Some(std::mem::replace(&mut self.active_view, new_view));
2155        } else {
2156            let old_view = std::mem::replace(&mut self.active_view, new_view);
2157            if !new_is_overlay {
2158                if let Some(previous) = self.previous_view.take() {
2159                    self.retain_running_thread(previous, cx);
2160                }
2161            }
2162            self.retain_running_thread(old_view, cx);
2163        }
2164
2165        // Subscribe to the active ThreadView's events (e.g. FirstSendRequested)
2166        // so the panel can intercept the first send for worktree creation.
2167        // Re-subscribe whenever the ConnectionView changes, since the inner
2168        // ThreadView may have been replaced (e.g. navigating between threads).
2169        self._active_view_observation = match &self.active_view {
2170            ActiveView::AgentThread { conversation_view } => {
2171                self._thread_view_subscription =
2172                    Self::subscribe_to_active_thread_view(conversation_view, window, cx);
2173                let focus_handle = conversation_view.focus_handle(cx);
2174                self._active_thread_focus_subscription =
2175                    Some(cx.on_focus_in(&focus_handle, window, |_this, _window, cx| {
2176                        cx.emit(AgentPanelEvent::ThreadFocused);
2177                        cx.notify();
2178                    }));
2179                Some(cx.observe_in(
2180                    conversation_view,
2181                    window,
2182                    |this, server_view, window, cx| {
2183                        this._thread_view_subscription =
2184                            Self::subscribe_to_active_thread_view(&server_view, window, cx);
2185                        cx.emit(AgentPanelEvent::ActiveViewChanged);
2186                        this.serialize(cx);
2187                        cx.notify();
2188                    },
2189                ))
2190            }
2191            _ => {
2192                self._thread_view_subscription = None;
2193                self._active_thread_focus_subscription = None;
2194                None
2195            }
2196        };
2197
2198        if let ActiveView::History { history } = &self.active_view {
2199            if !was_in_agent_history && let History::AgentThreads { view } = history {
2200                view.update(cx, |view, cx| {
2201                    view.history()
2202                        .update(cx, |history, cx| history.refresh_full_history(cx))
2203                });
2204            }
2205        }
2206
2207        if focus {
2208            self.focus_handle(cx).focus(window, cx);
2209        }
2210        cx.emit(AgentPanelEvent::ActiveViewChanged);
2211    }
2212
2213    fn populate_recently_updated_menu_section(
2214        mut menu: ContextMenu,
2215        panel: Entity<Self>,
2216        history: History,
2217        cx: &mut Context<ContextMenu>,
2218    ) -> ContextMenu {
2219        match history {
2220            History::AgentThreads { view } => {
2221                let entries = view
2222                    .read(cx)
2223                    .history()
2224                    .read(cx)
2225                    .sessions()
2226                    .iter()
2227                    .take(RECENTLY_UPDATED_MENU_LIMIT)
2228                    .cloned()
2229                    .collect::<Vec<_>>();
2230
2231                if entries.is_empty() {
2232                    return menu;
2233                }
2234
2235                menu = menu.header("Recently Updated");
2236
2237                for entry in entries {
2238                    let title = entry
2239                        .title
2240                        .as_ref()
2241                        .filter(|title| !title.is_empty())
2242                        .cloned()
2243                        .unwrap_or_else(|| SharedString::new_static(DEFAULT_THREAD_TITLE));
2244
2245                    menu = menu.entry(title, None, {
2246                        let panel = panel.downgrade();
2247                        let entry = entry.clone();
2248                        move |window, cx| {
2249                            let entry = entry.clone();
2250                            panel
2251                                .update(cx, move |this, cx| {
2252                                    if let Some(agent) = this.selected_agent() {
2253                                        this.load_agent_thread(
2254                                            agent,
2255                                            entry.session_id.clone(),
2256                                            entry.work_dirs.clone(),
2257                                            entry.title.clone(),
2258                                            true,
2259                                            window,
2260                                            cx,
2261                                        );
2262                                    }
2263                                })
2264                                .ok();
2265                        }
2266                    });
2267                }
2268            }
2269            History::TextThreads => {
2270                let entries = panel
2271                    .read(cx)
2272                    .text_thread_store
2273                    .read(cx)
2274                    .ordered_text_threads()
2275                    .take(RECENTLY_UPDATED_MENU_LIMIT)
2276                    .cloned()
2277                    .collect::<Vec<_>>();
2278
2279                if entries.is_empty() {
2280                    return menu;
2281                }
2282
2283                menu = menu.header("Recent Text Threads");
2284
2285                for entry in entries {
2286                    let title = if entry.title.is_empty() {
2287                        SharedString::new_static(DEFAULT_THREAD_TITLE)
2288                    } else {
2289                        entry.title.clone()
2290                    };
2291
2292                    menu = menu.entry(title, None, {
2293                        let panel = panel.downgrade();
2294                        let entry = entry.clone();
2295                        move |window, cx| {
2296                            let path = entry.path.clone();
2297                            panel
2298                                .update(cx, move |this, cx| {
2299                                    this.open_saved_text_thread(path.clone(), window, cx)
2300                                        .detach_and_log_err(cx);
2301                                })
2302                                .ok();
2303                        }
2304                    });
2305                }
2306            }
2307        }
2308
2309        menu.separator()
2310    }
2311
2312    fn subscribe_to_active_thread_view(
2313        server_view: &Entity<ConversationView>,
2314        window: &mut Window,
2315        cx: &mut Context<Self>,
2316    ) -> Option<Subscription> {
2317        server_view.read(cx).active_thread().cloned().map(|tv| {
2318            cx.subscribe_in(
2319                &tv,
2320                window,
2321                |this, view, event: &AcpThreadViewEvent, window, cx| match event {
2322                    AcpThreadViewEvent::FirstSendRequested { content } => {
2323                        this.handle_first_send_requested(view.clone(), content.clone(), window, cx);
2324                    }
2325                    AcpThreadViewEvent::MessageSentOrQueued => {
2326                        let session_id = view.read(cx).thread.read(cx).session_id().clone();
2327                        cx.emit(AgentPanelEvent::MessageSentOrQueued { session_id });
2328                    }
2329                },
2330            )
2331        })
2332    }
2333
2334    pub fn start_thread_in(&self) -> &StartThreadIn {
2335        &self.start_thread_in
2336    }
2337
2338    fn set_start_thread_in(
2339        &mut self,
2340        action: &StartThreadIn,
2341        window: &mut Window,
2342        cx: &mut Context<Self>,
2343    ) {
2344        if matches!(action, StartThreadIn::NewWorktree) && !cx.has_flag::<AgentV2FeatureFlag>() {
2345            return;
2346        }
2347
2348        let new_target = match *action {
2349            StartThreadIn::LocalProject => StartThreadIn::LocalProject,
2350            StartThreadIn::NewWorktree => {
2351                if !self.project_has_git_repository(cx) {
2352                    log::error!(
2353                        "set_start_thread_in: cannot use NewWorktree without a git repository"
2354                    );
2355                    return;
2356                }
2357                if self.project.read(cx).is_via_collab() {
2358                    log::error!("set_start_thread_in: cannot use NewWorktree in a collab project");
2359                    return;
2360                }
2361                StartThreadIn::NewWorktree
2362            }
2363        };
2364        self.start_thread_in = new_target;
2365        if let Some(thread) = self.active_thread_view(cx) {
2366            thread.update(cx, |thread, cx| thread.focus_handle(cx).focus(window, cx));
2367        }
2368        self.serialize(cx);
2369        cx.notify();
2370    }
2371
2372    fn cycle_start_thread_in(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2373        let next = match self.start_thread_in {
2374            StartThreadIn::LocalProject => StartThreadIn::NewWorktree,
2375            StartThreadIn::NewWorktree => StartThreadIn::LocalProject,
2376        };
2377        self.set_start_thread_in(&next, window, cx);
2378    }
2379
2380    fn reset_start_thread_in_to_default(&mut self, cx: &mut Context<Self>) {
2381        use settings::{NewThreadLocation, Settings};
2382        let default = AgentSettings::get_global(cx).new_thread_location;
2383        let start_thread_in = match default {
2384            NewThreadLocation::LocalProject => StartThreadIn::LocalProject,
2385            NewThreadLocation::NewWorktree => {
2386                if self.project_has_git_repository(cx) {
2387                    StartThreadIn::NewWorktree
2388                } else {
2389                    StartThreadIn::LocalProject
2390                }
2391            }
2392        };
2393        if self.start_thread_in != start_thread_in {
2394            self.start_thread_in = start_thread_in;
2395            self.serialize(cx);
2396            cx.notify();
2397        }
2398    }
2399
2400    pub(crate) fn selected_agent(&self) -> Option<Agent> {
2401        match &self.selected_agent_type {
2402            AgentType::NativeAgent => Some(Agent::NativeAgent),
2403            AgentType::Custom { id } => Some(Agent::Custom { id: id.clone() }),
2404            AgentType::TextThread => None,
2405        }
2406    }
2407
2408    fn sync_agent_servers_from_extensions(&mut self, cx: &mut Context<Self>) {
2409        if let Some(extension_store) = ExtensionStore::try_global(cx) {
2410            let (manifests, extensions_dir) = {
2411                let store = extension_store.read(cx);
2412                let installed = store.installed_extensions();
2413                let manifests: Vec<_> = installed
2414                    .iter()
2415                    .map(|(id, entry)| (id.clone(), entry.manifest.clone()))
2416                    .collect();
2417                let extensions_dir = paths::extensions_dir().join("installed");
2418                (manifests, extensions_dir)
2419            };
2420
2421            self.project.update(cx, |project, cx| {
2422                project.agent_server_store().update(cx, |store, cx| {
2423                    let manifest_refs: Vec<_> = manifests
2424                        .iter()
2425                        .map(|(id, manifest)| (id.as_ref(), manifest.as_ref()))
2426                        .collect();
2427                    store.sync_extension_agents(manifest_refs, extensions_dir, cx);
2428                });
2429            });
2430        }
2431    }
2432
2433    pub fn new_agent_thread_with_external_source_prompt(
2434        &mut self,
2435        external_source_prompt: Option<ExternalSourcePrompt>,
2436        window: &mut Window,
2437        cx: &mut Context<Self>,
2438    ) {
2439        self.external_thread(
2440            None,
2441            None,
2442            None,
2443            None,
2444            external_source_prompt.map(AgentInitialContent::from),
2445            true,
2446            window,
2447            cx,
2448        );
2449    }
2450
2451    pub fn new_agent_thread(
2452        &mut self,
2453        agent: AgentType,
2454        window: &mut Window,
2455        cx: &mut Context<Self>,
2456    ) {
2457        self.reset_start_thread_in_to_default(cx);
2458        self.new_agent_thread_inner(agent, true, window, cx);
2459    }
2460
2461    fn new_agent_thread_inner(
2462        &mut self,
2463        agent: AgentType,
2464        focus: bool,
2465        window: &mut Window,
2466        cx: &mut Context<Self>,
2467    ) {
2468        match agent {
2469            AgentType::TextThread => {
2470                window.dispatch_action(NewTextThread.boxed_clone(), cx);
2471            }
2472            AgentType::NativeAgent => self.external_thread(
2473                Some(crate::Agent::NativeAgent),
2474                None,
2475                None,
2476                None,
2477                None,
2478                focus,
2479                window,
2480                cx,
2481            ),
2482            AgentType::Custom { id } => self.external_thread(
2483                Some(crate::Agent::Custom { id }),
2484                None,
2485                None,
2486                None,
2487                None,
2488                focus,
2489                window,
2490                cx,
2491            ),
2492        }
2493    }
2494
2495    pub fn load_agent_thread(
2496        &mut self,
2497        agent: Agent,
2498        session_id: acp::SessionId,
2499        work_dirs: Option<PathList>,
2500        title: Option<SharedString>,
2501        focus: bool,
2502        window: &mut Window,
2503        cx: &mut Context<Self>,
2504    ) {
2505        if let Some(conversation_view) = self.background_threads.remove(&session_id) {
2506            self.set_active_view(
2507                ActiveView::AgentThread { conversation_view },
2508                focus,
2509                window,
2510                cx,
2511            );
2512            return;
2513        }
2514
2515        if let ActiveView::AgentThread { conversation_view } = &self.active_view {
2516            if conversation_view
2517                .read(cx)
2518                .active_thread()
2519                .map(|t| t.read(cx).id.clone())
2520                == Some(session_id.clone())
2521            {
2522                cx.emit(AgentPanelEvent::ActiveViewChanged);
2523                return;
2524            }
2525        }
2526
2527        if let Some(ActiveView::AgentThread { conversation_view }) = &self.previous_view {
2528            if conversation_view
2529                .read(cx)
2530                .active_thread()
2531                .map(|t| t.read(cx).id.clone())
2532                == Some(session_id.clone())
2533            {
2534                let view = self.previous_view.take().unwrap();
2535                self.set_active_view(view, focus, window, cx);
2536                return;
2537            }
2538        }
2539
2540        self.external_thread(
2541            Some(agent),
2542            Some(session_id),
2543            work_dirs,
2544            title,
2545            None,
2546            focus,
2547            window,
2548            cx,
2549        );
2550    }
2551
2552    pub(crate) fn create_agent_thread(
2553        &mut self,
2554        server: Rc<dyn AgentServer>,
2555        resume_session_id: Option<acp::SessionId>,
2556        work_dirs: Option<PathList>,
2557        title: Option<SharedString>,
2558        initial_content: Option<AgentInitialContent>,
2559        workspace: WeakEntity<Workspace>,
2560        project: Entity<Project>,
2561        ext_agent: Agent,
2562        focus: bool,
2563        window: &mut Window,
2564        cx: &mut Context<Self>,
2565    ) {
2566        let selected_agent = AgentType::from(ext_agent.clone());
2567        if self.selected_agent_type != selected_agent {
2568            self.selected_agent_type = selected_agent;
2569            self.serialize(cx);
2570        }
2571        let thread_store = server
2572            .clone()
2573            .downcast::<agent::NativeAgentServer>()
2574            .is_some()
2575            .then(|| self.thread_store.clone());
2576
2577        let connection_store = self.connection_store.clone();
2578
2579        let conversation_view = cx.new(|cx| {
2580            crate::ConversationView::new(
2581                server,
2582                connection_store,
2583                ext_agent,
2584                resume_session_id,
2585                work_dirs,
2586                title,
2587                initial_content,
2588                workspace.clone(),
2589                project,
2590                thread_store,
2591                self.prompt_store.clone(),
2592                window,
2593                cx,
2594            )
2595        });
2596
2597        cx.observe(&conversation_view, |this, server_view, cx| {
2598            let is_active = this
2599                .active_conversation_view()
2600                .is_some_and(|active| active.entity_id() == server_view.entity_id());
2601            if is_active {
2602                cx.emit(AgentPanelEvent::ActiveViewChanged);
2603                this.serialize(cx);
2604            } else {
2605                cx.emit(AgentPanelEvent::BackgroundThreadChanged);
2606            }
2607            cx.notify();
2608        })
2609        .detach();
2610
2611        self.set_active_view(
2612            ActiveView::AgentThread { conversation_view },
2613            focus,
2614            window,
2615            cx,
2616        );
2617    }
2618
2619    pub fn active_thread_is_draft(&self, cx: &App) -> bool {
2620        self.active_conversation_view().is_some()
2621            && self
2622                .active_agent_thread(cx)
2623                .map_or(true, |thread| thread.read(cx).is_draft())
2624    }
2625
2626    fn handle_first_send_requested(
2627        &mut self,
2628        thread_view: Entity<ThreadView>,
2629        content: Vec<acp::ContentBlock>,
2630        window: &mut Window,
2631        cx: &mut Context<Self>,
2632    ) {
2633        if self.start_thread_in == StartThreadIn::NewWorktree {
2634            self.handle_worktree_creation_requested(content, window, cx);
2635        } else {
2636            cx.defer_in(window, move |_this, window, cx| {
2637                thread_view.update(cx, |thread_view, cx| {
2638                    let editor = thread_view.message_editor.clone();
2639                    thread_view.send_impl(editor, window, cx);
2640                });
2641            });
2642        }
2643    }
2644
2645    // TODO: The mapping from workspace root paths to git repositories needs a
2646    // unified approach across the codebase: this method, `sidebar::is_root_repo`,
2647    // thread persistence (which PathList is saved to the database), and thread
2648    // querying (which PathList is used to read threads back). All of these need
2649    // to agree on how repos are resolved for a given workspace, especially in
2650    // multi-root and nested-repo configurations.
2651    /// Partitions the project's visible worktrees into git-backed repositories
2652    /// and plain (non-git) paths. Git repos will have worktrees created for
2653    /// them; non-git paths are carried over to the new workspace as-is.
2654    ///
2655    /// When multiple worktrees map to the same repository, the most specific
2656    /// match wins (deepest work directory path), with a deterministic
2657    /// tie-break on entity id. Each repository appears at most once.
2658    fn classify_worktrees(
2659        &self,
2660        cx: &App,
2661    ) -> (Vec<Entity<project::git_store::Repository>>, Vec<PathBuf>) {
2662        let project = &self.project;
2663        let repositories = project.read(cx).repositories(cx).clone();
2664        let mut git_repos: Vec<Entity<project::git_store::Repository>> = Vec::new();
2665        let mut non_git_paths: Vec<PathBuf> = Vec::new();
2666        let mut seen_repo_ids = std::collections::HashSet::new();
2667
2668        for worktree in project.read(cx).visible_worktrees(cx) {
2669            let wt_path = worktree.read(cx).abs_path();
2670
2671            let matching_repo = repositories
2672                .iter()
2673                .filter_map(|(id, repo)| {
2674                    let work_dir = repo.read(cx).work_directory_abs_path.clone();
2675                    if wt_path.starts_with(work_dir.as_ref())
2676                        || work_dir.starts_with(wt_path.as_ref())
2677                    {
2678                        Some((*id, repo.clone(), work_dir.as_ref().components().count()))
2679                    } else {
2680                        None
2681                    }
2682                })
2683                .max_by(
2684                    |(left_id, _left_repo, left_depth), (right_id, _right_repo, right_depth)| {
2685                        left_depth
2686                            .cmp(right_depth)
2687                            .then_with(|| left_id.cmp(right_id))
2688                    },
2689                );
2690
2691            if let Some((id, repo, _)) = matching_repo {
2692                if seen_repo_ids.insert(id) {
2693                    git_repos.push(repo);
2694                }
2695            } else {
2696                non_git_paths.push(wt_path.to_path_buf());
2697            }
2698        }
2699
2700        (git_repos, non_git_paths)
2701    }
2702
2703    /// Kicks off an async git-worktree creation for each repository. Returns:
2704    ///
2705    /// - `creation_infos`: a vec of `(repo, new_path, receiver)` tuples—the
2706    ///   receiver resolves once the git worktree command finishes.
2707    /// - `path_remapping`: `(old_work_dir, new_worktree_path)` pairs used
2708    ///   later to remap open editor tabs into the new workspace.
2709    fn start_worktree_creations(
2710        git_repos: &[Entity<project::git_store::Repository>],
2711        branch_name: &str,
2712        worktree_directory_setting: &str,
2713        cx: &mut Context<Self>,
2714    ) -> Result<(
2715        Vec<(
2716            Entity<project::git_store::Repository>,
2717            PathBuf,
2718            futures::channel::oneshot::Receiver<Result<()>>,
2719        )>,
2720        Vec<(PathBuf, PathBuf)>,
2721    )> {
2722        let mut creation_infos = Vec::new();
2723        let mut path_remapping = Vec::new();
2724
2725        for repo in git_repos {
2726            let (work_dir, new_path, receiver) = repo.update(cx, |repo, _cx| {
2727                let new_path =
2728                    repo.path_for_new_linked_worktree(branch_name, worktree_directory_setting)?;
2729                let receiver =
2730                    repo.create_worktree(branch_name.to_string(), new_path.clone(), None);
2731                let work_dir = repo.work_directory_abs_path.clone();
2732                anyhow::Ok((work_dir, new_path, receiver))
2733            })?;
2734            path_remapping.push((work_dir.to_path_buf(), new_path.clone()));
2735            creation_infos.push((repo.clone(), new_path, receiver));
2736        }
2737
2738        Ok((creation_infos, path_remapping))
2739    }
2740
2741    /// Waits for every in-flight worktree creation to complete. If any
2742    /// creation fails, all successfully-created worktrees are rolled back
2743    /// (removed) so the project isn't left in a half-migrated state.
2744    async fn await_and_rollback_on_failure(
2745        creation_infos: Vec<(
2746            Entity<project::git_store::Repository>,
2747            PathBuf,
2748            futures::channel::oneshot::Receiver<Result<()>>,
2749        )>,
2750        cx: &mut AsyncWindowContext,
2751    ) -> Result<Vec<PathBuf>> {
2752        let mut created_paths: Vec<PathBuf> = Vec::new();
2753        let mut repos_and_paths: Vec<(Entity<project::git_store::Repository>, PathBuf)> =
2754            Vec::new();
2755        let mut first_error: Option<anyhow::Error> = None;
2756
2757        for (repo, new_path, receiver) in creation_infos {
2758            match receiver.await {
2759                Ok(Ok(())) => {
2760                    created_paths.push(new_path.clone());
2761                    repos_and_paths.push((repo, new_path));
2762                }
2763                Ok(Err(err)) => {
2764                    if first_error.is_none() {
2765                        first_error = Some(err);
2766                    }
2767                }
2768                Err(_canceled) => {
2769                    if first_error.is_none() {
2770                        first_error = Some(anyhow!("Worktree creation was canceled"));
2771                    }
2772                }
2773            }
2774        }
2775
2776        let Some(err) = first_error else {
2777            return Ok(created_paths);
2778        };
2779
2780        // Rollback all successfully created worktrees
2781        let mut rollback_receivers = Vec::new();
2782        for (rollback_repo, rollback_path) in &repos_and_paths {
2783            if let Ok(receiver) = cx.update(|_, cx| {
2784                rollback_repo.update(cx, |repo, _cx| {
2785                    repo.remove_worktree(rollback_path.clone(), true)
2786                })
2787            }) {
2788                rollback_receivers.push((rollback_path.clone(), receiver));
2789            }
2790        }
2791        let mut rollback_failures: Vec<String> = Vec::new();
2792        for (path, receiver) in rollback_receivers {
2793            match receiver.await {
2794                Ok(Ok(())) => {}
2795                Ok(Err(rollback_err)) => {
2796                    log::error!(
2797                        "failed to rollback worktree at {}: {rollback_err}",
2798                        path.display()
2799                    );
2800                    rollback_failures.push(format!("{}: {rollback_err}", path.display()));
2801                }
2802                Err(rollback_err) => {
2803                    log::error!(
2804                        "failed to rollback worktree at {}: {rollback_err}",
2805                        path.display()
2806                    );
2807                    rollback_failures.push(format!("{}: {rollback_err}", path.display()));
2808                }
2809            }
2810        }
2811        let mut error_message = format!("Failed to create worktree: {err}");
2812        if !rollback_failures.is_empty() {
2813            error_message.push_str("\n\nFailed to clean up: ");
2814            error_message.push_str(&rollback_failures.join(", "));
2815        }
2816        Err(anyhow!(error_message))
2817    }
2818
2819    fn set_worktree_creation_error(
2820        &mut self,
2821        message: SharedString,
2822        window: &mut Window,
2823        cx: &mut Context<Self>,
2824    ) {
2825        self.worktree_creation_status = Some(WorktreeCreationStatus::Error(message));
2826        if matches!(self.active_view, ActiveView::Uninitialized) {
2827            let selected_agent_type = self.selected_agent_type.clone();
2828            self.new_agent_thread(selected_agent_type, window, cx);
2829        }
2830        cx.notify();
2831    }
2832
2833    fn handle_worktree_creation_requested(
2834        &mut self,
2835        content: Vec<acp::ContentBlock>,
2836        window: &mut Window,
2837        cx: &mut Context<Self>,
2838    ) {
2839        if matches!(
2840            self.worktree_creation_status,
2841            Some(WorktreeCreationStatus::Creating)
2842        ) {
2843            return;
2844        }
2845
2846        self.worktree_creation_status = Some(WorktreeCreationStatus::Creating);
2847        cx.notify();
2848
2849        let (git_repos, non_git_paths) = self.classify_worktrees(cx);
2850
2851        if git_repos.is_empty() {
2852            self.set_worktree_creation_error(
2853                "No git repositories found in the project".into(),
2854                window,
2855                cx,
2856            );
2857            return;
2858        }
2859
2860        // Kick off branch listing as early as possible so it can run
2861        // concurrently with the remaining synchronous setup work.
2862        let branch_receivers: Vec<_> = git_repos
2863            .iter()
2864            .map(|repo| repo.update(cx, |repo, _cx| repo.branches()))
2865            .collect();
2866
2867        let worktree_directory_setting = ProjectSettings::get_global(cx)
2868            .git
2869            .worktree_directory
2870            .clone();
2871
2872        let active_file_path = self.workspace.upgrade().and_then(|workspace| {
2873            let workspace = workspace.read(cx);
2874            let active_item = workspace.active_item(cx)?;
2875            let project_path = active_item.project_path(cx)?;
2876            workspace
2877                .project()
2878                .read(cx)
2879                .absolute_path(&project_path, cx)
2880        });
2881
2882        let workspace = self.workspace.clone();
2883        let window_handle = window
2884            .window_handle()
2885            .downcast::<workspace::MultiWorkspace>();
2886
2887        let selected_agent = self.selected_agent();
2888
2889        let task = cx.spawn_in(window, async move |this, cx| {
2890            // Await the branch listings we kicked off earlier.
2891            let mut existing_branches = Vec::new();
2892            for result in futures::future::join_all(branch_receivers).await {
2893                match result {
2894                    Ok(Ok(branches)) => {
2895                        for branch in branches {
2896                            existing_branches.push(branch.name().to_string());
2897                        }
2898                    }
2899                    Ok(Err(err)) => {
2900                        Err::<(), _>(err).log_err();
2901                    }
2902                    Err(_) => {}
2903                }
2904            }
2905
2906            let existing_branch_refs: Vec<&str> =
2907                existing_branches.iter().map(|s| s.as_str()).collect();
2908            let mut rng = rand::rng();
2909            let branch_name =
2910                match crate::branch_names::generate_branch_name(&existing_branch_refs, &mut rng) {
2911                    Some(name) => name,
2912                    None => {
2913                        this.update_in(cx, |this, window, cx| {
2914                            this.set_worktree_creation_error(
2915                                "Failed to generate a unique branch name".into(),
2916                                window,
2917                                cx,
2918                            );
2919                        })?;
2920                        return anyhow::Ok(());
2921                    }
2922                };
2923
2924            let (creation_infos, path_remapping) = match this.update_in(cx, |_this, _window, cx| {
2925                Self::start_worktree_creations(
2926                    &git_repos,
2927                    &branch_name,
2928                    &worktree_directory_setting,
2929                    cx,
2930                )
2931            }) {
2932                Ok(Ok(result)) => result,
2933                Ok(Err(err)) | Err(err) => {
2934                    this.update_in(cx, |this, window, cx| {
2935                        this.set_worktree_creation_error(
2936                            format!("Failed to validate worktree directory: {err}").into(),
2937                            window,
2938                            cx,
2939                        );
2940                    })
2941                    .log_err();
2942                    return anyhow::Ok(());
2943                }
2944            };
2945
2946            let created_paths = match Self::await_and_rollback_on_failure(creation_infos, cx).await
2947            {
2948                Ok(paths) => paths,
2949                Err(err) => {
2950                    this.update_in(cx, |this, window, cx| {
2951                        this.set_worktree_creation_error(format!("{err}").into(), window, cx);
2952                    })?;
2953                    return anyhow::Ok(());
2954                }
2955            };
2956
2957            let mut all_paths = created_paths;
2958            let has_non_git = !non_git_paths.is_empty();
2959            all_paths.extend(non_git_paths.iter().cloned());
2960
2961            let app_state = match workspace.upgrade() {
2962                Some(workspace) => cx.update(|_, cx| workspace.read(cx).app_state().clone())?,
2963                None => {
2964                    this.update_in(cx, |this, window, cx| {
2965                        this.set_worktree_creation_error(
2966                            "Workspace no longer available".into(),
2967                            window,
2968                            cx,
2969                        );
2970                    })?;
2971                    return anyhow::Ok(());
2972                }
2973            };
2974
2975            let this_for_error = this.clone();
2976            if let Err(err) = Self::setup_new_workspace(
2977                this,
2978                all_paths,
2979                app_state,
2980                window_handle,
2981                active_file_path,
2982                path_remapping,
2983                non_git_paths,
2984                has_non_git,
2985                content,
2986                selected_agent,
2987                cx,
2988            )
2989            .await
2990            {
2991                this_for_error
2992                    .update_in(cx, |this, window, cx| {
2993                        this.set_worktree_creation_error(
2994                            format!("Failed to set up workspace: {err}").into(),
2995                            window,
2996                            cx,
2997                        );
2998                    })
2999                    .log_err();
3000            }
3001            anyhow::Ok(())
3002        });
3003
3004        self._worktree_creation_task = Some(cx.foreground_executor().spawn(async move {
3005            task.await.log_err();
3006        }));
3007    }
3008
3009    async fn setup_new_workspace(
3010        this: WeakEntity<Self>,
3011        all_paths: Vec<PathBuf>,
3012        app_state: Arc<workspace::AppState>,
3013        window_handle: Option<gpui::WindowHandle<workspace::MultiWorkspace>>,
3014        active_file_path: Option<PathBuf>,
3015        path_remapping: Vec<(PathBuf, PathBuf)>,
3016        non_git_paths: Vec<PathBuf>,
3017        has_non_git: bool,
3018        content: Vec<acp::ContentBlock>,
3019        selected_agent: Option<Agent>,
3020        cx: &mut AsyncWindowContext,
3021    ) -> Result<()> {
3022        let OpenResult {
3023            window: new_window_handle,
3024            workspace: new_workspace,
3025            ..
3026        } = cx
3027            .update(|_window, cx| {
3028                Workspace::new_local(
3029                    all_paths,
3030                    app_state,
3031                    window_handle,
3032                    None,
3033                    None,
3034                    OpenMode::Add,
3035                    cx,
3036                )
3037            })?
3038            .await?;
3039
3040        let panels_task = new_workspace.update(cx, |workspace, _cx| workspace.take_panels_task());
3041
3042        if let Some(task) = panels_task {
3043            task.await.log_err();
3044        }
3045
3046        new_workspace
3047            .update(cx, |workspace, cx| {
3048                workspace.project().read(cx).wait_for_initial_scan(cx)
3049            })
3050            .await;
3051
3052        new_workspace
3053            .update(cx, |workspace, cx| {
3054                let repos = workspace
3055                    .project()
3056                    .read(cx)
3057                    .repositories(cx)
3058                    .values()
3059                    .cloned()
3060                    .collect::<Vec<_>>();
3061
3062                let tasks = repos
3063                    .into_iter()
3064                    .map(|repo| repo.update(cx, |repo, _| repo.barrier()));
3065                futures::future::join_all(tasks)
3066            })
3067            .await;
3068
3069        let initial_content = AgentInitialContent::ContentBlock {
3070            blocks: content,
3071            auto_submit: true,
3072        };
3073
3074        new_window_handle.update(cx, |_multi_workspace, window, cx| {
3075            new_workspace.update(cx, |workspace, cx| {
3076                if has_non_git {
3077                    let toast_id = workspace::notifications::NotificationId::unique::<AgentPanel>();
3078                    workspace.show_toast(
3079                        workspace::Toast::new(
3080                            toast_id,
3081                            "Some project folders are not git repositories. \
3082                             They were included as-is without creating a worktree.",
3083                        ),
3084                        cx,
3085                    );
3086                }
3087
3088                // If we had an active buffer, remap its path and reopen it.
3089                let had_active_file = active_file_path.is_some();
3090                let remapped_active_path = active_file_path.and_then(|original_path| {
3091                    let best_match = path_remapping
3092                        .iter()
3093                        .filter_map(|(old_root, new_root)| {
3094                            original_path.strip_prefix(old_root).ok().map(|relative| {
3095                                (old_root.components().count(), new_root.join(relative))
3096                            })
3097                        })
3098                        .max_by_key(|(depth, _)| *depth);
3099
3100                    if let Some((_, remapped_path)) = best_match {
3101                        return Some(remapped_path);
3102                    }
3103
3104                    for non_git in &non_git_paths {
3105                        if original_path.starts_with(non_git) {
3106                            return Some(original_path);
3107                        }
3108                    }
3109                    None
3110                });
3111
3112                if had_active_file && remapped_active_path.is_none() {
3113                    log::warn!(
3114                        "Active file could not be remapped to the new worktree; it will not be reopened"
3115                    );
3116                }
3117
3118                if let Some(path) = remapped_active_path {
3119                    let open_task = workspace.open_paths(
3120                        vec![path],
3121                        workspace::OpenOptions::default(),
3122                        None,
3123                        window,
3124                        cx,
3125                    );
3126                    cx.spawn(async move |_, _| -> anyhow::Result<()> {
3127                        for item in open_task.await.into_iter().flatten() {
3128                            item?;
3129                        }
3130                        Ok(())
3131                    })
3132                    .detach_and_log_err(cx);
3133                }
3134
3135                workspace.focus_panel::<AgentPanel>(window, cx);
3136
3137                // If no active buffer was open, zoom the agent panel
3138                // (equivalent to cmd-esc fullscreen behavior).
3139                // This must happen after focus_panel, which activates
3140                // and opens the panel in the dock.
3141
3142                if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
3143                    panel.update(cx, |panel, cx| {
3144                        panel.external_thread(
3145                            selected_agent,
3146                            None,
3147                            None,
3148                            None,
3149                            Some(initial_content),
3150                            true,
3151                            window,
3152                            cx,
3153                        );
3154                    });
3155                }
3156            });
3157        })?;
3158
3159        new_window_handle.update(cx, |multi_workspace, window, cx| {
3160            multi_workspace.activate(new_workspace.clone(), window, cx);
3161        })?;
3162
3163        this.update_in(cx, |this, window, cx| {
3164            this.worktree_creation_status = None;
3165
3166            if let Some(thread_view) = this.active_thread_view(cx) {
3167                thread_view.update(cx, |thread_view, cx| {
3168                    thread_view
3169                        .message_editor
3170                        .update(cx, |editor, cx| editor.clear(window, cx));
3171                });
3172            }
3173
3174            cx.notify();
3175        })?;
3176
3177        anyhow::Ok(())
3178    }
3179}
3180
3181impl Focusable for AgentPanel {
3182    fn focus_handle(&self, cx: &App) -> FocusHandle {
3183        match &self.active_view {
3184            ActiveView::Uninitialized => self.focus_handle.clone(),
3185            ActiveView::AgentThread {
3186                conversation_view, ..
3187            } => conversation_view.focus_handle(cx),
3188            ActiveView::History { history: kind } => match kind {
3189                History::AgentThreads { view } => view.read(cx).focus_handle(cx),
3190                History::TextThreads => self.text_thread_history.focus_handle(cx),
3191            },
3192            ActiveView::TextThread {
3193                text_thread_editor, ..
3194            } => text_thread_editor.focus_handle(cx),
3195            ActiveView::Configuration => {
3196                if let Some(configuration) = self.configuration.as_ref() {
3197                    configuration.focus_handle(cx)
3198                } else {
3199                    self.focus_handle.clone()
3200                }
3201            }
3202        }
3203    }
3204}
3205
3206fn agent_panel_dock_position(cx: &App) -> DockPosition {
3207    AgentSettings::get_global(cx).dock.into()
3208}
3209
3210pub enum AgentPanelEvent {
3211    ActiveViewChanged,
3212    ThreadFocused,
3213    BackgroundThreadChanged,
3214    MessageSentOrQueued { session_id: acp::SessionId },
3215}
3216
3217impl EventEmitter<PanelEvent> for AgentPanel {}
3218impl EventEmitter<AgentPanelEvent> for AgentPanel {}
3219
3220impl Panel for AgentPanel {
3221    fn persistent_name() -> &'static str {
3222        "AgentPanel"
3223    }
3224
3225    fn panel_key() -> &'static str {
3226        AGENT_PANEL_KEY
3227    }
3228
3229    fn position(&self, _window: &Window, cx: &App) -> DockPosition {
3230        agent_panel_dock_position(cx)
3231    }
3232
3233    fn position_is_valid(&self, position: DockPosition) -> bool {
3234        position != DockPosition::Bottom
3235    }
3236
3237    fn set_position(&mut self, position: DockPosition, _: &mut Window, cx: &mut Context<Self>) {
3238        settings::update_settings_file(self.fs.clone(), cx, move |settings, _| {
3239            settings
3240                .agent
3241                .get_or_insert_default()
3242                .set_dock(position.into());
3243        });
3244    }
3245
3246    fn default_size(&self, window: &Window, cx: &App) -> Pixels {
3247        let settings = AgentSettings::get_global(cx);
3248        match self.position(window, cx) {
3249            DockPosition::Left | DockPosition::Right => settings.default_width,
3250            DockPosition::Bottom => settings.default_height,
3251        }
3252    }
3253
3254    fn supports_flexible_size(&self) -> bool {
3255        true
3256    }
3257
3258    fn has_flexible_size(&self, _window: &Window, cx: &App) -> bool {
3259        AgentSettings::get_global(cx).flexible
3260    }
3261
3262    fn set_flexible_size(&mut self, flexible: bool, _window: &mut Window, cx: &mut Context<Self>) {
3263        settings::update_settings_file(self.fs.clone(), cx, move |settings, _| {
3264            settings
3265                .agent
3266                .get_or_insert_default()
3267                .set_flexible_size(flexible);
3268        });
3269    }
3270
3271    fn set_active(&mut self, active: bool, window: &mut Window, cx: &mut Context<Self>) {
3272        if active
3273            && matches!(self.active_view, ActiveView::Uninitialized)
3274            && !matches!(
3275                self.worktree_creation_status,
3276                Some(WorktreeCreationStatus::Creating)
3277            )
3278        {
3279            let selected_agent_type = self.selected_agent_type.clone();
3280            self.new_agent_thread_inner(selected_agent_type, false, window, cx);
3281        }
3282    }
3283
3284    fn remote_id() -> Option<proto::PanelId> {
3285        Some(proto::PanelId::AssistantPanel)
3286    }
3287
3288    fn icon(&self, _window: &Window, cx: &App) -> Option<IconName> {
3289        (self.enabled(cx) && AgentSettings::get_global(cx).button).then_some(IconName::ZedAssistant)
3290    }
3291
3292    fn icon_tooltip(&self, _window: &Window, _cx: &App) -> Option<&'static str> {
3293        Some("Agent Panel")
3294    }
3295
3296    fn toggle_action(&self) -> Box<dyn Action> {
3297        Box::new(ToggleFocus)
3298    }
3299
3300    fn activation_priority(&self) -> u32 {
3301        0
3302    }
3303
3304    fn enabled(&self, cx: &App) -> bool {
3305        AgentSettings::get_global(cx).enabled(cx)
3306    }
3307
3308    fn is_agent_panel(&self) -> bool {
3309        true
3310    }
3311
3312    fn is_zoomed(&self, _window: &Window, _cx: &App) -> bool {
3313        self.zoomed
3314    }
3315
3316    fn set_zoomed(&mut self, zoomed: bool, _window: &mut Window, cx: &mut Context<Self>) {
3317        self.zoomed = zoomed;
3318        cx.notify();
3319    }
3320}
3321
3322impl AgentPanel {
3323    fn render_title_view(&self, _window: &mut Window, cx: &Context<Self>) -> AnyElement {
3324        const LOADING_SUMMARY_PLACEHOLDER: &str = "Loading Summary…";
3325
3326        let content = match &self.active_view {
3327            ActiveView::AgentThread { conversation_view } => {
3328                let server_view_ref = conversation_view.read(cx);
3329                let is_generating_title = server_view_ref.as_native_thread(cx).is_some()
3330                    && server_view_ref.root_thread(cx).map_or(false, |tv| {
3331                        tv.read(cx).thread.read(cx).has_provisional_title()
3332                    });
3333
3334                if let Some(title_editor) = server_view_ref
3335                    .root_thread(cx)
3336                    .map(|r| r.read(cx).title_editor.clone())
3337                {
3338                    if is_generating_title {
3339                        Label::new(DEFAULT_THREAD_TITLE)
3340                            .color(Color::Muted)
3341                            .truncate()
3342                            .with_animation(
3343                                "generating_title",
3344                                Animation::new(Duration::from_secs(2))
3345                                    .repeat()
3346                                    .with_easing(pulsating_between(0.4, 0.8)),
3347                                |label, delta| label.alpha(delta),
3348                            )
3349                            .into_any_element()
3350                    } else {
3351                        div()
3352                            .w_full()
3353                            .on_action({
3354                                let conversation_view = conversation_view.downgrade();
3355                                move |_: &menu::Confirm, window, cx| {
3356                                    if let Some(conversation_view) = conversation_view.upgrade() {
3357                                        conversation_view.focus_handle(cx).focus(window, cx);
3358                                    }
3359                                }
3360                            })
3361                            .on_action({
3362                                let conversation_view = conversation_view.downgrade();
3363                                move |_: &editor::actions::Cancel, window, cx| {
3364                                    if let Some(conversation_view) = conversation_view.upgrade() {
3365                                        conversation_view.focus_handle(cx).focus(window, cx);
3366                                    }
3367                                }
3368                            })
3369                            .child(title_editor)
3370                            .into_any_element()
3371                    }
3372                } else {
3373                    Label::new(conversation_view.read(cx).title(cx))
3374                        .color(Color::Muted)
3375                        .truncate()
3376                        .into_any_element()
3377                }
3378            }
3379            ActiveView::TextThread {
3380                title_editor,
3381                text_thread_editor,
3382                ..
3383            } => {
3384                let summary = text_thread_editor.read(cx).text_thread().read(cx).summary();
3385
3386                match summary {
3387                    TextThreadSummary::Pending => Label::new(TextThreadSummary::DEFAULT)
3388                        .color(Color::Muted)
3389                        .truncate()
3390                        .into_any_element(),
3391                    TextThreadSummary::Content(summary) => {
3392                        if summary.done {
3393                            div()
3394                                .w_full()
3395                                .child(title_editor.clone())
3396                                .into_any_element()
3397                        } else {
3398                            Label::new(LOADING_SUMMARY_PLACEHOLDER)
3399                                .truncate()
3400                                .color(Color::Muted)
3401                                .with_animation(
3402                                    "generating_title",
3403                                    Animation::new(Duration::from_secs(2))
3404                                        .repeat()
3405                                        .with_easing(pulsating_between(0.4, 0.8)),
3406                                    |label, delta| label.alpha(delta),
3407                                )
3408                                .into_any_element()
3409                        }
3410                    }
3411                    TextThreadSummary::Error => h_flex()
3412                        .w_full()
3413                        .child(title_editor.clone())
3414                        .child(
3415                            IconButton::new("retry-summary-generation", IconName::RotateCcw)
3416                                .icon_size(IconSize::Small)
3417                                .on_click({
3418                                    let text_thread_editor = text_thread_editor.clone();
3419                                    move |_, _window, cx| {
3420                                        text_thread_editor.update(cx, |text_thread_editor, cx| {
3421                                            text_thread_editor.regenerate_summary(cx);
3422                                        });
3423                                    }
3424                                })
3425                                .tooltip(move |_window, cx| {
3426                                    cx.new(|_| {
3427                                        Tooltip::new("Failed to generate title")
3428                                            .meta("Click to try again")
3429                                    })
3430                                    .into()
3431                                }),
3432                        )
3433                        .into_any_element(),
3434                }
3435            }
3436            ActiveView::History { history: kind } => {
3437                let title = match kind {
3438                    History::AgentThreads { .. } => "History",
3439                    History::TextThreads => "Text Thread History",
3440                };
3441                Label::new(title).truncate().into_any_element()
3442            }
3443            ActiveView::Configuration => Label::new("Settings").truncate().into_any_element(),
3444            ActiveView::Uninitialized => Label::new("Agent").truncate().into_any_element(),
3445        };
3446
3447        h_flex()
3448            .key_context("TitleEditor")
3449            .id("TitleEditor")
3450            .flex_grow()
3451            .w_full()
3452            .max_w_full()
3453            .overflow_x_scroll()
3454            .child(content)
3455            .into_any()
3456    }
3457
3458    fn handle_regenerate_thread_title(conversation_view: Entity<ConversationView>, cx: &mut App) {
3459        conversation_view.update(cx, |conversation_view, cx| {
3460            if let Some(thread) = conversation_view.as_native_thread(cx) {
3461                thread.update(cx, |thread, cx| {
3462                    thread.generate_title(cx);
3463                });
3464            }
3465        });
3466    }
3467
3468    fn handle_regenerate_text_thread_title(
3469        text_thread_editor: Entity<TextThreadEditor>,
3470        cx: &mut App,
3471    ) {
3472        text_thread_editor.update(cx, |text_thread_editor, cx| {
3473            text_thread_editor.regenerate_summary(cx);
3474        });
3475    }
3476
3477    fn render_panel_options_menu(
3478        &self,
3479        window: &mut Window,
3480        cx: &mut Context<Self>,
3481    ) -> impl IntoElement {
3482        let focus_handle = self.focus_handle(cx);
3483
3484        let full_screen_label = if self.is_zoomed(window, cx) {
3485            "Disable Full Screen"
3486        } else {
3487            "Enable Full Screen"
3488        };
3489
3490        let text_thread_view = match &self.active_view {
3491            ActiveView::TextThread {
3492                text_thread_editor, ..
3493            } => Some(text_thread_editor.clone()),
3494            _ => None,
3495        };
3496        let text_thread_with_messages = match &self.active_view {
3497            ActiveView::TextThread {
3498                text_thread_editor, ..
3499            } => text_thread_editor
3500                .read(cx)
3501                .text_thread()
3502                .read(cx)
3503                .messages(cx)
3504                .any(|message| message.role == language_model::Role::Assistant),
3505            _ => false,
3506        };
3507
3508        let conversation_view = match &self.active_view {
3509            ActiveView::AgentThread { conversation_view } => Some(conversation_view.clone()),
3510            _ => None,
3511        };
3512        let thread_with_messages = match &self.active_view {
3513            ActiveView::AgentThread { conversation_view } => {
3514                conversation_view.read(cx).has_user_submitted_prompt(cx)
3515            }
3516            _ => false,
3517        };
3518        let has_auth_methods = match &self.active_view {
3519            ActiveView::AgentThread { conversation_view } => {
3520                conversation_view.read(cx).has_auth_methods()
3521            }
3522            _ => false,
3523        };
3524
3525        PopoverMenu::new("agent-options-menu")
3526            .trigger_with_tooltip(
3527                IconButton::new("agent-options-menu", IconName::Ellipsis)
3528                    .icon_size(IconSize::Small),
3529                {
3530                    let focus_handle = focus_handle.clone();
3531                    move |_window, cx| {
3532                        Tooltip::for_action_in(
3533                            "Toggle Agent Menu",
3534                            &ToggleOptionsMenu,
3535                            &focus_handle,
3536                            cx,
3537                        )
3538                    }
3539                },
3540            )
3541            .anchor(Corner::TopRight)
3542            .with_handle(self.agent_panel_menu_handle.clone())
3543            .menu({
3544                move |window, cx| {
3545                    Some(ContextMenu::build(window, cx, |mut menu, _window, _| {
3546                        menu = menu.context(focus_handle.clone());
3547
3548                        if thread_with_messages | text_thread_with_messages {
3549                            menu = menu.header("Current Thread");
3550
3551                            if let Some(text_thread_view) = text_thread_view.as_ref() {
3552                                menu = menu
3553                                    .entry("Regenerate Thread Title", None, {
3554                                        let text_thread_view = text_thread_view.clone();
3555                                        move |_, cx| {
3556                                            Self::handle_regenerate_text_thread_title(
3557                                                text_thread_view.clone(),
3558                                                cx,
3559                                            );
3560                                        }
3561                                    })
3562                                    .separator();
3563                            }
3564
3565                            if let Some(conversation_view) = conversation_view.as_ref() {
3566                                menu = menu
3567                                    .entry("Regenerate Thread Title", None, {
3568                                        let conversation_view = conversation_view.clone();
3569                                        move |_, cx| {
3570                                            Self::handle_regenerate_thread_title(
3571                                                conversation_view.clone(),
3572                                                cx,
3573                                            );
3574                                        }
3575                                    })
3576                                    .separator();
3577                            }
3578                        }
3579
3580                        menu = menu
3581                            .header("MCP Servers")
3582                            .action(
3583                                "View Server Extensions",
3584                                Box::new(zed_actions::Extensions {
3585                                    category_filter: Some(
3586                                        zed_actions::ExtensionCategoryFilter::ContextServers,
3587                                    ),
3588                                    id: None,
3589                                }),
3590                            )
3591                            .action("Add Custom Server…", Box::new(AddContextServer))
3592                            .separator()
3593                            .action("Rules", Box::new(OpenRulesLibrary::default()))
3594                            .action("Profiles", Box::new(ManageProfiles::default()))
3595                            .action("Settings", Box::new(OpenSettings))
3596                            .separator()
3597                            .action("Toggle Threads Sidebar", Box::new(ToggleWorkspaceSidebar))
3598                            .action(full_screen_label, Box::new(ToggleZoom));
3599
3600                        if has_auth_methods {
3601                            menu = menu.action("Reauthenticate", Box::new(ReauthenticateAgent))
3602                        }
3603
3604                        menu
3605                    }))
3606                }
3607            })
3608    }
3609
3610    fn render_recent_entries_menu(
3611        &self,
3612        icon: IconName,
3613        corner: Corner,
3614        cx: &mut Context<Self>,
3615    ) -> impl IntoElement {
3616        let focus_handle = self.focus_handle(cx);
3617
3618        PopoverMenu::new("agent-nav-menu")
3619            .trigger_with_tooltip(
3620                IconButton::new("agent-nav-menu", icon).icon_size(IconSize::Small),
3621                {
3622                    move |_window, cx| {
3623                        Tooltip::for_action_in(
3624                            "Toggle Recently Updated Threads",
3625                            &ToggleNavigationMenu,
3626                            &focus_handle,
3627                            cx,
3628                        )
3629                    }
3630                },
3631            )
3632            .anchor(corner)
3633            .with_handle(self.agent_navigation_menu_handle.clone())
3634            .menu({
3635                let menu = self.agent_navigation_menu.clone();
3636                move |window, cx| {
3637                    telemetry::event!("View Thread History Clicked");
3638
3639                    if let Some(menu) = menu.as_ref() {
3640                        menu.update(cx, |_, cx| {
3641                            cx.defer_in(window, |menu, window, cx| {
3642                                menu.rebuild(window, cx);
3643                            });
3644                        })
3645                    }
3646                    menu.clone()
3647                }
3648            })
3649    }
3650
3651    fn render_toolbar_back_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
3652        let focus_handle = self.focus_handle(cx);
3653
3654        IconButton::new("go-back", IconName::ArrowLeft)
3655            .icon_size(IconSize::Small)
3656            .on_click(cx.listener(|this, _, window, cx| {
3657                this.go_back(&workspace::GoBack, window, cx);
3658            }))
3659            .tooltip({
3660                move |_window, cx| {
3661                    Tooltip::for_action_in("Go Back", &workspace::GoBack, &focus_handle, cx)
3662                }
3663            })
3664    }
3665
3666    fn project_has_git_repository(&self, cx: &App) -> bool {
3667        !self.project.read(cx).repositories(cx).is_empty()
3668    }
3669
3670    fn render_start_thread_in_selector(&self, cx: &mut Context<Self>) -> impl IntoElement {
3671        use settings::{NewThreadLocation, Settings};
3672
3673        let focus_handle = self.focus_handle(cx);
3674        let has_git_repo = self.project_has_git_repository(cx);
3675        let is_via_collab = self.project.read(cx).is_via_collab();
3676        let fs = self.fs.clone();
3677
3678        let is_creating = matches!(
3679            self.worktree_creation_status,
3680            Some(WorktreeCreationStatus::Creating)
3681        );
3682
3683        let current_target = self.start_thread_in;
3684        let trigger_label = self.start_thread_in.label();
3685
3686        let new_thread_location = AgentSettings::get_global(cx).new_thread_location;
3687        let is_local_default = new_thread_location == NewThreadLocation::LocalProject;
3688        let is_new_worktree_default = new_thread_location == NewThreadLocation::NewWorktree;
3689
3690        let icon = if self.start_thread_in_menu_handle.is_deployed() {
3691            IconName::ChevronUp
3692        } else {
3693            IconName::ChevronDown
3694        };
3695
3696        let trigger_button = Button::new("thread-target-trigger", trigger_label)
3697            .end_icon(Icon::new(icon).size(IconSize::XSmall).color(Color::Muted))
3698            .disabled(is_creating);
3699
3700        let dock_position = AgentSettings::get_global(cx).dock;
3701        let documentation_side = match dock_position {
3702            settings::DockPosition::Left => DocumentationSide::Right,
3703            settings::DockPosition::Bottom | settings::DockPosition::Right => {
3704                DocumentationSide::Left
3705            }
3706        };
3707
3708        PopoverMenu::new("thread-target-selector")
3709            .trigger_with_tooltip(trigger_button, {
3710                move |_window, cx| {
3711                    Tooltip::for_action_in(
3712                        "Start Thread In…",
3713                        &CycleStartThreadIn,
3714                        &focus_handle,
3715                        cx,
3716                    )
3717                }
3718            })
3719            .menu(move |window, cx| {
3720                let is_local_selected = current_target == StartThreadIn::LocalProject;
3721                let is_new_worktree_selected = current_target == StartThreadIn::NewWorktree;
3722                let fs = fs.clone();
3723
3724                Some(ContextMenu::build(window, cx, move |menu, _window, _cx| {
3725                    let new_worktree_disabled = !has_git_repo || is_via_collab;
3726
3727                    menu.header("Start Thread In…")
3728                        .item(
3729                            ContextMenuEntry::new("Current Worktree")
3730                                .toggleable(IconPosition::End, is_local_selected)
3731                                .documentation_aside(documentation_side, move |_| {
3732                                    HoldForDefault::new(is_local_default)
3733                                        .more_content(false)
3734                                        .into_any_element()
3735                                })
3736                                .handler({
3737                                    let fs = fs.clone();
3738                                    move |window, cx| {
3739                                        if window.modifiers().secondary() {
3740                                            update_settings_file(fs.clone(), cx, |settings, _| {
3741                                                settings
3742                                                    .agent
3743                                                    .get_or_insert_default()
3744                                                    .set_new_thread_location(
3745                                                        NewThreadLocation::LocalProject,
3746                                                    );
3747                                            });
3748                                        }
3749                                        window.dispatch_action(
3750                                            Box::new(StartThreadIn::LocalProject),
3751                                            cx,
3752                                        );
3753                                    }
3754                                }),
3755                        )
3756                        .item({
3757                            let entry = ContextMenuEntry::new("New Git Worktree")
3758                                .toggleable(IconPosition::End, is_new_worktree_selected)
3759                                .disabled(new_worktree_disabled)
3760                                .handler({
3761                                    let fs = fs.clone();
3762                                    move |window, cx| {
3763                                        if window.modifiers().secondary() {
3764                                            update_settings_file(fs.clone(), cx, |settings, _| {
3765                                                settings
3766                                                    .agent
3767                                                    .get_or_insert_default()
3768                                                    .set_new_thread_location(
3769                                                        NewThreadLocation::NewWorktree,
3770                                                    );
3771                                            });
3772                                        }
3773                                        window.dispatch_action(
3774                                            Box::new(StartThreadIn::NewWorktree),
3775                                            cx,
3776                                        );
3777                                    }
3778                                });
3779
3780                            if new_worktree_disabled {
3781                                entry.documentation_aside(documentation_side, move |_| {
3782                                    let reason = if !has_git_repo {
3783                                        "No git repository found in this project."
3784                                    } else {
3785                                        "Not available for remote/collab projects yet."
3786                                    };
3787                                    Label::new(reason)
3788                                        .color(Color::Muted)
3789                                        .size(LabelSize::Small)
3790                                        .into_any_element()
3791                                })
3792                            } else {
3793                                entry.documentation_aside(documentation_side, move |_| {
3794                                    HoldForDefault::new(is_new_worktree_default)
3795                                        .more_content(false)
3796                                        .into_any_element()
3797                                })
3798                            }
3799                        })
3800                }))
3801            })
3802            .with_handle(self.start_thread_in_menu_handle.clone())
3803            .anchor(Corner::TopLeft)
3804            .offset(gpui::Point {
3805                x: px(1.0),
3806                y: px(1.0),
3807            })
3808    }
3809
3810    fn render_toolbar(&self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
3811        let agent_server_store = self.project.read(cx).agent_server_store().clone();
3812        let has_visible_worktrees = self.project.read(cx).visible_worktrees(cx).next().is_some();
3813        let focus_handle = self.focus_handle(cx);
3814
3815        let (selected_agent_custom_icon, selected_agent_label) =
3816            if let AgentType::Custom { id, .. } = &self.selected_agent_type {
3817                let store = agent_server_store.read(cx);
3818                let icon = store.agent_icon(&id);
3819
3820                let label = store
3821                    .agent_display_name(&id)
3822                    .unwrap_or_else(|| self.selected_agent_type.label());
3823                (icon, label)
3824            } else {
3825                (None, self.selected_agent_type.label())
3826            };
3827
3828        let active_thread = match &self.active_view {
3829            ActiveView::AgentThread { conversation_view } => {
3830                conversation_view.read(cx).as_native_thread(cx)
3831            }
3832            ActiveView::Uninitialized
3833            | ActiveView::TextThread { .. }
3834            | ActiveView::History { .. }
3835            | ActiveView::Configuration => None,
3836        };
3837
3838        let new_thread_menu_builder: Rc<
3839            dyn Fn(&mut Window, &mut App) -> Option<Entity<ContextMenu>>,
3840        > = {
3841            let selected_agent = self.selected_agent_type.clone();
3842            let is_agent_selected = move |agent_type: AgentType| selected_agent == agent_type;
3843
3844            let workspace = self.workspace.clone();
3845            let is_via_collab = workspace
3846                .update(cx, |workspace, cx| {
3847                    workspace.project().read(cx).is_via_collab()
3848                })
3849                .unwrap_or_default();
3850
3851            let focus_handle = focus_handle.clone();
3852            let agent_server_store = agent_server_store;
3853
3854            Rc::new(move |window, cx| {
3855                telemetry::event!("New Thread Clicked");
3856
3857                let active_thread = active_thread.clone();
3858                Some(ContextMenu::build(window, cx, |menu, _window, cx| {
3859                    menu.context(focus_handle.clone())
3860                        .when_some(active_thread, |this, active_thread| {
3861                            let thread = active_thread.read(cx);
3862
3863                            if !thread.is_empty() {
3864                                let session_id = thread.id().clone();
3865                                this.item(
3866                                    ContextMenuEntry::new("New From Summary")
3867                                        .icon(IconName::ThreadFromSummary)
3868                                        .icon_color(Color::Muted)
3869                                        .handler(move |window, cx| {
3870                                            window.dispatch_action(
3871                                                Box::new(NewNativeAgentThreadFromSummary {
3872                                                    from_session_id: session_id.clone(),
3873                                                }),
3874                                                cx,
3875                                            );
3876                                        }),
3877                                )
3878                            } else {
3879                                this
3880                            }
3881                        })
3882                        .item(
3883                            ContextMenuEntry::new("Zed Agent")
3884                                .when(
3885                                    is_agent_selected(AgentType::NativeAgent)
3886                                        | is_agent_selected(AgentType::TextThread),
3887                                    |this| {
3888                                        this.action(Box::new(NewExternalAgentThread {
3889                                            agent: None,
3890                                        }))
3891                                    },
3892                                )
3893                                .icon(IconName::ZedAgent)
3894                                .icon_color(Color::Muted)
3895                                .handler({
3896                                    let workspace = workspace.clone();
3897                                    move |window, cx| {
3898                                        if let Some(workspace) = workspace.upgrade() {
3899                                            workspace.update(cx, |workspace, cx| {
3900                                                if let Some(panel) =
3901                                                    workspace.panel::<AgentPanel>(cx)
3902                                                {
3903                                                    panel.update(cx, |panel, cx| {
3904                                                        panel.new_agent_thread(
3905                                                            AgentType::NativeAgent,
3906                                                            window,
3907                                                            cx,
3908                                                        );
3909                                                    });
3910                                                }
3911                                            });
3912                                        }
3913                                    }
3914                                }),
3915                        )
3916                        .item(
3917                            ContextMenuEntry::new("Text Thread")
3918                                .action(NewTextThread.boxed_clone())
3919                                .icon(IconName::TextThread)
3920                                .icon_color(Color::Muted)
3921                                .handler({
3922                                    let workspace = workspace.clone();
3923                                    move |window, cx| {
3924                                        if let Some(workspace) = workspace.upgrade() {
3925                                            workspace.update(cx, |workspace, cx| {
3926                                                if let Some(panel) =
3927                                                    workspace.panel::<AgentPanel>(cx)
3928                                                {
3929                                                    panel.update(cx, |panel, cx| {
3930                                                        panel.new_agent_thread(
3931                                                            AgentType::TextThread,
3932                                                            window,
3933                                                            cx,
3934                                                        );
3935                                                    });
3936                                                }
3937                                            });
3938                                        }
3939                                    }
3940                                }),
3941                        )
3942                        .map(|mut menu| {
3943                            let agent_server_store = agent_server_store.read(cx);
3944                            let registry_store = project::AgentRegistryStore::try_global(cx);
3945                            let registry_store_ref = registry_store.as_ref().map(|s| s.read(cx));
3946
3947                            struct AgentMenuItem {
3948                                id: AgentId,
3949                                display_name: SharedString,
3950                            }
3951
3952                            let agent_items = agent_server_store
3953                                .external_agents()
3954                                .map(|agent_id| {
3955                                    let display_name = agent_server_store
3956                                        .agent_display_name(agent_id)
3957                                        .or_else(|| {
3958                                            registry_store_ref
3959                                                .as_ref()
3960                                                .and_then(|store| store.agent(agent_id))
3961                                                .map(|a| a.name().clone())
3962                                        })
3963                                        .unwrap_or_else(|| agent_id.0.clone());
3964                                    AgentMenuItem {
3965                                        id: agent_id.clone(),
3966                                        display_name,
3967                                    }
3968                                })
3969                                .sorted_unstable_by_key(|e| e.display_name.to_lowercase())
3970                                .collect::<Vec<_>>();
3971
3972                            if !agent_items.is_empty() {
3973                                menu = menu.separator().header("External Agents");
3974                            }
3975                            for item in &agent_items {
3976                                let mut entry = ContextMenuEntry::new(item.display_name.clone());
3977
3978                                let icon_path =
3979                                    agent_server_store.agent_icon(&item.id).or_else(|| {
3980                                        registry_store_ref
3981                                            .as_ref()
3982                                            .and_then(|store| store.agent(&item.id))
3983                                            .and_then(|a| a.icon_path().cloned())
3984                                    });
3985
3986                                if let Some(icon_path) = icon_path {
3987                                    entry = entry.custom_icon_svg(icon_path);
3988                                } else {
3989                                    entry = entry.icon(IconName::Sparkle);
3990                                }
3991
3992                                entry = entry
3993                                    .when(
3994                                        is_agent_selected(AgentType::Custom {
3995                                            id: item.id.clone(),
3996                                        }),
3997                                        |this| {
3998                                            this.action(Box::new(NewExternalAgentThread {
3999                                                agent: None,
4000                                            }))
4001                                        },
4002                                    )
4003                                    .icon_color(Color::Muted)
4004                                    .disabled(is_via_collab)
4005                                    .handler({
4006                                        let workspace = workspace.clone();
4007                                        let agent_id = item.id.clone();
4008                                        move |window, cx| {
4009                                            if let Some(workspace) = workspace.upgrade() {
4010                                                workspace.update(cx, |workspace, cx| {
4011                                                    if let Some(panel) =
4012                                                        workspace.panel::<AgentPanel>(cx)
4013                                                    {
4014                                                        panel.update(cx, |panel, cx| {
4015                                                            panel.new_agent_thread(
4016                                                                AgentType::Custom {
4017                                                                    id: agent_id.clone(),
4018                                                                },
4019                                                                window,
4020                                                                cx,
4021                                                            );
4022                                                        });
4023                                                    }
4024                                                });
4025                                            }
4026                                        }
4027                                    });
4028
4029                                menu = menu.item(entry);
4030                            }
4031
4032                            menu
4033                        })
4034                        .separator()
4035                        .item(
4036                            ContextMenuEntry::new("Add More Agents")
4037                                .icon(IconName::Plus)
4038                                .icon_color(Color::Muted)
4039                                .handler({
4040                                    move |window, cx| {
4041                                        window
4042                                            .dispatch_action(Box::new(zed_actions::AcpRegistry), cx)
4043                                    }
4044                                }),
4045                        )
4046                }))
4047            })
4048        };
4049
4050        let is_thread_loading = self
4051            .active_conversation_view()
4052            .map(|thread| thread.read(cx).is_loading())
4053            .unwrap_or(false);
4054
4055        let has_custom_icon = selected_agent_custom_icon.is_some();
4056        let selected_agent_custom_icon_for_button = selected_agent_custom_icon.clone();
4057        let selected_agent_builtin_icon = self.selected_agent_type.icon();
4058        let selected_agent_label_for_tooltip = selected_agent_label.clone();
4059
4060        let selected_agent = div()
4061            .id("selected_agent_icon")
4062            .when_some(selected_agent_custom_icon, |this, icon_path| {
4063                this.px_1()
4064                    .child(Icon::from_external_svg(icon_path).color(Color::Muted))
4065            })
4066            .when(!has_custom_icon, |this| {
4067                this.when_some(self.selected_agent_type.icon(), |this, icon| {
4068                    this.px_1().child(Icon::new(icon).color(Color::Muted))
4069                })
4070            })
4071            .tooltip(move |_, cx| {
4072                Tooltip::with_meta(
4073                    selected_agent_label_for_tooltip.clone(),
4074                    None,
4075                    "Selected Agent",
4076                    cx,
4077                )
4078            });
4079
4080        let selected_agent = if is_thread_loading {
4081            selected_agent
4082                .with_animation(
4083                    "pulsating-icon",
4084                    Animation::new(Duration::from_secs(1))
4085                        .repeat()
4086                        .with_easing(pulsating_between(0.2, 0.6)),
4087                    |icon, delta| icon.opacity(delta),
4088                )
4089                .into_any_element()
4090        } else {
4091            selected_agent.into_any_element()
4092        };
4093
4094        let show_history_menu = self.has_history_for_selected_agent(cx);
4095        let has_v2_flag = cx.has_flag::<AgentV2FeatureFlag>();
4096        let is_empty_state = !self
4097            .active_agent_thread(cx)
4098            .is_some_and(|thread| !thread.read(cx).is_draft());
4099
4100        let is_in_history_or_config = matches!(
4101            &self.active_view,
4102            ActiveView::History { .. } | ActiveView::Configuration
4103        );
4104
4105        let is_text_thread = matches!(&self.active_view, ActiveView::TextThread { .. });
4106
4107        let is_full_screen = self.is_zoomed(window, cx);
4108
4109        let use_v2_empty_toolbar =
4110            has_v2_flag && is_empty_state && !is_in_history_or_config && !is_text_thread;
4111
4112        let base_container = h_flex()
4113            .id("agent-panel-toolbar")
4114            .h(Tab::container_height(cx))
4115            .max_w_full()
4116            .flex_none()
4117            .justify_between()
4118            .gap_2()
4119            .bg(cx.theme().colors().tab_bar_background)
4120            .border_b_1()
4121            .border_color(cx.theme().colors().border);
4122
4123        if use_v2_empty_toolbar {
4124            let (chevron_icon, icon_color, label_color) =
4125                if self.new_thread_menu_handle.is_deployed() {
4126                    (IconName::ChevronUp, Color::Accent, Color::Accent)
4127                } else {
4128                    (IconName::ChevronDown, Color::Muted, Color::Default)
4129                };
4130
4131            let agent_icon = if let Some(icon_path) = selected_agent_custom_icon_for_button {
4132                Icon::from_external_svg(icon_path)
4133                    .size(IconSize::Small)
4134                    .color(icon_color)
4135            } else {
4136                let icon_name = selected_agent_builtin_icon.unwrap_or(IconName::ZedAgent);
4137                Icon::new(icon_name).size(IconSize::Small).color(icon_color)
4138            };
4139
4140            let agent_selector_button = Button::new("agent-selector-trigger", selected_agent_label)
4141                .start_icon(agent_icon)
4142                .color(label_color)
4143                .end_icon(
4144                    Icon::new(chevron_icon)
4145                        .color(icon_color)
4146                        .size(IconSize::XSmall),
4147                );
4148
4149            let agent_selector_menu = PopoverMenu::new("new_thread_menu")
4150                .trigger_with_tooltip(agent_selector_button, {
4151                    move |_window, cx| {
4152                        Tooltip::for_action_in(
4153                            "New Thread…",
4154                            &ToggleNewThreadMenu,
4155                            &focus_handle,
4156                            cx,
4157                        )
4158                    }
4159                })
4160                .menu({
4161                    let builder = new_thread_menu_builder.clone();
4162                    move |window, cx| builder(window, cx)
4163                })
4164                .with_handle(self.new_thread_menu_handle.clone())
4165                .anchor(Corner::TopLeft)
4166                .offset(gpui::Point {
4167                    x: px(1.0),
4168                    y: px(1.0),
4169                });
4170
4171            base_container
4172                .child(
4173                    h_flex()
4174                        .size_full()
4175                        .gap(DynamicSpacing::Base04.rems(cx))
4176                        .pl(DynamicSpacing::Base04.rems(cx))
4177                        .child(agent_selector_menu)
4178                        .when(
4179                            has_visible_worktrees && self.project_has_git_repository(cx),
4180                            |this| this.child(self.render_start_thread_in_selector(cx)),
4181                        ),
4182                )
4183                .child(
4184                    h_flex()
4185                        .h_full()
4186                        .flex_none()
4187                        .gap_1()
4188                        .pl_1()
4189                        .pr_1()
4190                        .when(show_history_menu && !has_v2_flag, |this| {
4191                            this.child(self.render_recent_entries_menu(
4192                                IconName::MenuAltTemp,
4193                                Corner::TopRight,
4194                                cx,
4195                            ))
4196                        })
4197                        .when(is_full_screen, |this| {
4198                            this.child(
4199                                IconButton::new("disable-full-screen", IconName::Minimize)
4200                                    .icon_size(IconSize::Small)
4201                                    .tooltip(move |_, cx| {
4202                                        Tooltip::for_action("Disable Full Screen", &ToggleZoom, cx)
4203                                    })
4204                                    .on_click({
4205                                        cx.listener(move |_, _, window, cx| {
4206                                            window.dispatch_action(ToggleZoom.boxed_clone(), cx);
4207                                        })
4208                                    }),
4209                            )
4210                        })
4211                        .child(self.render_panel_options_menu(window, cx)),
4212                )
4213                .into_any_element()
4214        } else {
4215            let new_thread_menu = PopoverMenu::new("new_thread_menu")
4216                .trigger_with_tooltip(
4217                    IconButton::new("new_thread_menu_btn", IconName::Plus)
4218                        .icon_size(IconSize::Small),
4219                    {
4220                        move |_window, cx| {
4221                            Tooltip::for_action_in(
4222                                "New Thread\u{2026}",
4223                                &ToggleNewThreadMenu,
4224                                &focus_handle,
4225                                cx,
4226                            )
4227                        }
4228                    },
4229                )
4230                .anchor(Corner::TopRight)
4231                .with_handle(self.new_thread_menu_handle.clone())
4232                .menu(move |window, cx| new_thread_menu_builder(window, cx));
4233
4234            base_container
4235                .child(
4236                    h_flex()
4237                        .size_full()
4238                        .gap(DynamicSpacing::Base04.rems(cx))
4239                        .pl(DynamicSpacing::Base04.rems(cx))
4240                        .child(match &self.active_view {
4241                            ActiveView::History { .. } | ActiveView::Configuration => {
4242                                self.render_toolbar_back_button(cx).into_any_element()
4243                            }
4244                            _ => selected_agent.into_any_element(),
4245                        })
4246                        .child(self.render_title_view(window, cx)),
4247                )
4248                .child(
4249                    h_flex()
4250                        .h_full()
4251                        .flex_none()
4252                        .gap_1()
4253                        .pl_1()
4254                        .pr_1()
4255                        .child(new_thread_menu)
4256                        .when(show_history_menu && !has_v2_flag, |this| {
4257                            this.child(self.render_recent_entries_menu(
4258                                IconName::MenuAltTemp,
4259                                Corner::TopRight,
4260                                cx,
4261                            ))
4262                        })
4263                        .when(is_full_screen, |this| {
4264                            this.child(
4265                                IconButton::new("disable-full-screen", IconName::Minimize)
4266                                    .icon_size(IconSize::Small)
4267                                    .tooltip(move |_, cx| {
4268                                        Tooltip::for_action("Disable Full Screen", &ToggleZoom, cx)
4269                                    })
4270                                    .on_click({
4271                                        cx.listener(move |_, _, window, cx| {
4272                                            window.dispatch_action(ToggleZoom.boxed_clone(), cx);
4273                                        })
4274                                    }),
4275                            )
4276                        })
4277                        .child(self.render_panel_options_menu(window, cx)),
4278                )
4279                .into_any_element()
4280        }
4281    }
4282
4283    fn render_worktree_creation_status(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
4284        let status = self.worktree_creation_status.as_ref()?;
4285        match status {
4286            WorktreeCreationStatus::Creating => Some(
4287                h_flex()
4288                    .absolute()
4289                    .bottom_12()
4290                    .w_full()
4291                    .p_2()
4292                    .gap_1()
4293                    .justify_center()
4294                    .bg(cx.theme().colors().editor_background)
4295                    .child(
4296                        Icon::new(IconName::LoadCircle)
4297                            .size(IconSize::Small)
4298                            .color(Color::Muted)
4299                            .with_rotate_animation(3),
4300                    )
4301                    .child(
4302                        Label::new("Creating Worktree…")
4303                            .color(Color::Muted)
4304                            .size(LabelSize::Small),
4305                    )
4306                    .into_any_element(),
4307            ),
4308            WorktreeCreationStatus::Error(message) => Some(
4309                Callout::new()
4310                    .icon(IconName::Warning)
4311                    .severity(Severity::Warning)
4312                    .title(message.clone())
4313                    .into_any_element(),
4314            ),
4315        }
4316    }
4317
4318    fn should_render_trial_end_upsell(&self, cx: &mut Context<Self>) -> bool {
4319        if TrialEndUpsell::dismissed(cx) {
4320            return false;
4321        }
4322
4323        match &self.active_view {
4324            ActiveView::TextThread { .. } => {
4325                if LanguageModelRegistry::global(cx)
4326                    .read(cx)
4327                    .default_model()
4328                    .is_some_and(|model| {
4329                        model.provider.id() != language_model::ZED_CLOUD_PROVIDER_ID
4330                    })
4331                {
4332                    return false;
4333                }
4334            }
4335            ActiveView::Uninitialized
4336            | ActiveView::AgentThread { .. }
4337            | ActiveView::History { .. }
4338            | ActiveView::Configuration => return false,
4339        }
4340
4341        let plan = self.user_store.read(cx).plan();
4342        let has_previous_trial = self.user_store.read(cx).trial_started_at().is_some();
4343
4344        plan.is_some_and(|plan| plan == Plan::ZedFree) && has_previous_trial
4345    }
4346
4347    fn should_render_onboarding(&self, cx: &mut Context<Self>) -> bool {
4348        if self.on_boarding_upsell_dismissed.load(Ordering::Acquire) {
4349            return false;
4350        }
4351
4352        let user_store = self.user_store.read(cx);
4353
4354        if user_store.plan().is_some_and(|plan| plan == Plan::ZedPro)
4355            && user_store
4356                .subscription_period()
4357                .and_then(|period| period.0.checked_add_days(chrono::Days::new(1)))
4358                .is_some_and(|date| date < chrono::Utc::now())
4359        {
4360            OnboardingUpsell::set_dismissed(true, cx);
4361            self.on_boarding_upsell_dismissed
4362                .store(true, Ordering::Release);
4363            return false;
4364        }
4365
4366        let has_configured_non_zed_providers = LanguageModelRegistry::read_global(cx)
4367            .visible_providers()
4368            .iter()
4369            .any(|provider| {
4370                provider.is_authenticated(cx)
4371                    && provider.id() != language_model::ZED_CLOUD_PROVIDER_ID
4372            });
4373
4374        match &self.active_view {
4375            ActiveView::Uninitialized | ActiveView::History { .. } | ActiveView::Configuration => {
4376                false
4377            }
4378            ActiveView::AgentThread {
4379                conversation_view, ..
4380            } if conversation_view.read(cx).as_native_thread(cx).is_none() => false,
4381            ActiveView::AgentThread { conversation_view } => {
4382                let history_is_empty = conversation_view
4383                    .read(cx)
4384                    .history()
4385                    .is_none_or(|h| h.read(cx).is_empty());
4386                history_is_empty || !has_configured_non_zed_providers
4387            }
4388            ActiveView::TextThread { .. } => {
4389                let history_is_empty = self.text_thread_history.read(cx).is_empty();
4390                history_is_empty || !has_configured_non_zed_providers
4391            }
4392        }
4393    }
4394
4395    fn render_onboarding(
4396        &self,
4397        _window: &mut Window,
4398        cx: &mut Context<Self>,
4399    ) -> Option<impl IntoElement> {
4400        if !self.should_render_onboarding(cx) {
4401            return None;
4402        }
4403
4404        let text_thread_view = matches!(&self.active_view, ActiveView::TextThread { .. });
4405
4406        Some(
4407            div()
4408                .when(text_thread_view, |this| {
4409                    this.bg(cx.theme().colors().editor_background)
4410                })
4411                .child(self.onboarding.clone()),
4412        )
4413    }
4414
4415    fn render_trial_end_upsell(
4416        &self,
4417        _window: &mut Window,
4418        cx: &mut Context<Self>,
4419    ) -> Option<impl IntoElement> {
4420        if !self.should_render_trial_end_upsell(cx) {
4421            return None;
4422        }
4423
4424        Some(
4425            v_flex()
4426                .absolute()
4427                .inset_0()
4428                .size_full()
4429                .bg(cx.theme().colors().panel_background)
4430                .opacity(0.85)
4431                .block_mouse_except_scroll()
4432                .child(EndTrialUpsell::new(Arc::new({
4433                    let this = cx.entity();
4434                    move |_, cx| {
4435                        this.update(cx, |_this, cx| {
4436                            TrialEndUpsell::set_dismissed(true, cx);
4437                            cx.notify();
4438                        });
4439                    }
4440                }))),
4441        )
4442    }
4443
4444    fn emit_configuration_error_telemetry_if_needed(
4445        &mut self,
4446        configuration_error: Option<&ConfigurationError>,
4447    ) {
4448        let error_kind = configuration_error.map(|err| match err {
4449            ConfigurationError::NoProvider => "no_provider",
4450            ConfigurationError::ModelNotFound => "model_not_found",
4451            ConfigurationError::ProviderNotAuthenticated(_) => "provider_not_authenticated",
4452        });
4453
4454        let error_kind_string = error_kind.map(String::from);
4455
4456        if self.last_configuration_error_telemetry == error_kind_string {
4457            return;
4458        }
4459
4460        self.last_configuration_error_telemetry = error_kind_string;
4461
4462        if let Some(kind) = error_kind {
4463            let message = configuration_error
4464                .map(|err| err.to_string())
4465                .unwrap_or_default();
4466
4467            telemetry::event!("Agent Panel Error Shown", kind = kind, message = message,);
4468        }
4469    }
4470
4471    fn render_configuration_error(
4472        &self,
4473        border_bottom: bool,
4474        configuration_error: &ConfigurationError,
4475        focus_handle: &FocusHandle,
4476        cx: &mut App,
4477    ) -> impl IntoElement {
4478        let zed_provider_configured = AgentSettings::get_global(cx)
4479            .default_model
4480            .as_ref()
4481            .is_some_and(|selection| selection.provider.0.as_str() == "zed.dev");
4482
4483        let callout = if zed_provider_configured {
4484            Callout::new()
4485                .icon(IconName::Warning)
4486                .severity(Severity::Warning)
4487                .when(border_bottom, |this| {
4488                    this.border_position(ui::BorderPosition::Bottom)
4489                })
4490                .title("Sign in to continue using Zed as your LLM provider.")
4491                .actions_slot(
4492                    Button::new("sign_in", "Sign In")
4493                        .style(ButtonStyle::Tinted(ui::TintColor::Warning))
4494                        .label_size(LabelSize::Small)
4495                        .on_click({
4496                            let workspace = self.workspace.clone();
4497                            move |_, _, cx| {
4498                                let Ok(client) =
4499                                    workspace.update(cx, |workspace, _| workspace.client().clone())
4500                                else {
4501                                    return;
4502                                };
4503
4504                                cx.spawn(async move |cx| {
4505                                    client.sign_in_with_optional_connect(true, cx).await
4506                                })
4507                                .detach_and_log_err(cx);
4508                            }
4509                        }),
4510                )
4511        } else {
4512            Callout::new()
4513                .icon(IconName::Warning)
4514                .severity(Severity::Warning)
4515                .when(border_bottom, |this| {
4516                    this.border_position(ui::BorderPosition::Bottom)
4517                })
4518                .title(configuration_error.to_string())
4519                .actions_slot(
4520                    Button::new("settings", "Configure")
4521                        .style(ButtonStyle::Tinted(ui::TintColor::Warning))
4522                        .label_size(LabelSize::Small)
4523                        .key_binding(
4524                            KeyBinding::for_action_in(&OpenSettings, focus_handle, cx)
4525                                .map(|kb| kb.size(rems_from_px(12.))),
4526                        )
4527                        .on_click(|_event, window, cx| {
4528                            window.dispatch_action(OpenSettings.boxed_clone(), cx)
4529                        }),
4530                )
4531        };
4532
4533        match configuration_error {
4534            ConfigurationError::ModelNotFound
4535            | ConfigurationError::ProviderNotAuthenticated(_)
4536            | ConfigurationError::NoProvider => callout.into_any_element(),
4537        }
4538    }
4539
4540    fn render_text_thread(
4541        &self,
4542        text_thread_editor: &Entity<TextThreadEditor>,
4543        buffer_search_bar: &Entity<BufferSearchBar>,
4544        window: &mut Window,
4545        cx: &mut Context<Self>,
4546    ) -> Div {
4547        let mut registrar = buffer_search::DivRegistrar::new(
4548            |this, _, _cx| match &this.active_view {
4549                ActiveView::TextThread {
4550                    buffer_search_bar, ..
4551                } => Some(buffer_search_bar.clone()),
4552                _ => None,
4553            },
4554            cx,
4555        );
4556        BufferSearchBar::register(&mut registrar);
4557        registrar
4558            .into_div()
4559            .size_full()
4560            .relative()
4561            .map(|parent| {
4562                buffer_search_bar.update(cx, |buffer_search_bar, cx| {
4563                    if buffer_search_bar.is_dismissed() {
4564                        return parent;
4565                    }
4566                    parent.child(
4567                        div()
4568                            .p(DynamicSpacing::Base08.rems(cx))
4569                            .border_b_1()
4570                            .border_color(cx.theme().colors().border_variant)
4571                            .bg(cx.theme().colors().editor_background)
4572                            .child(buffer_search_bar.render(window, cx)),
4573                    )
4574                })
4575            })
4576            .child(text_thread_editor.clone())
4577            .child(self.render_drag_target(cx))
4578    }
4579
4580    fn render_drag_target(&self, cx: &Context<Self>) -> Div {
4581        let is_local = self.project.read(cx).is_local();
4582        div()
4583            .invisible()
4584            .absolute()
4585            .top_0()
4586            .right_0()
4587            .bottom_0()
4588            .left_0()
4589            .bg(cx.theme().colors().drop_target_background)
4590            .drag_over::<DraggedTab>(|this, _, _, _| this.visible())
4591            .drag_over::<DraggedSelection>(|this, _, _, _| this.visible())
4592            .when(is_local, |this| {
4593                this.drag_over::<ExternalPaths>(|this, _, _, _| this.visible())
4594            })
4595            .on_drop(cx.listener(move |this, tab: &DraggedTab, window, cx| {
4596                let item = tab.pane.read(cx).item_for_index(tab.ix);
4597                let project_paths = item
4598                    .and_then(|item| item.project_path(cx))
4599                    .into_iter()
4600                    .collect::<Vec<_>>();
4601                this.handle_drop(project_paths, vec![], window, cx);
4602            }))
4603            .on_drop(
4604                cx.listener(move |this, selection: &DraggedSelection, window, cx| {
4605                    let project_paths = selection
4606                        .items()
4607                        .filter_map(|item| this.project.read(cx).path_for_entry(item.entry_id, cx))
4608                        .collect::<Vec<_>>();
4609                    this.handle_drop(project_paths, vec![], window, cx);
4610                }),
4611            )
4612            .on_drop(cx.listener(move |this, paths: &ExternalPaths, window, cx| {
4613                let tasks = paths
4614                    .paths()
4615                    .iter()
4616                    .map(|path| {
4617                        Workspace::project_path_for_path(this.project.clone(), path, false, cx)
4618                    })
4619                    .collect::<Vec<_>>();
4620                cx.spawn_in(window, async move |this, cx| {
4621                    let mut paths = vec![];
4622                    let mut added_worktrees = vec![];
4623                    let opened_paths = futures::future::join_all(tasks).await;
4624                    for entry in opened_paths {
4625                        if let Some((worktree, project_path)) = entry.log_err() {
4626                            added_worktrees.push(worktree);
4627                            paths.push(project_path);
4628                        }
4629                    }
4630                    this.update_in(cx, |this, window, cx| {
4631                        this.handle_drop(paths, added_worktrees, window, cx);
4632                    })
4633                    .ok();
4634                })
4635                .detach();
4636            }))
4637    }
4638
4639    fn handle_drop(
4640        &mut self,
4641        paths: Vec<ProjectPath>,
4642        added_worktrees: Vec<Entity<Worktree>>,
4643        window: &mut Window,
4644        cx: &mut Context<Self>,
4645    ) {
4646        match &self.active_view {
4647            ActiveView::AgentThread { conversation_view } => {
4648                conversation_view.update(cx, |conversation_view, cx| {
4649                    conversation_view.insert_dragged_files(paths, added_worktrees, window, cx);
4650                });
4651            }
4652            ActiveView::TextThread {
4653                text_thread_editor, ..
4654            } => {
4655                text_thread_editor.update(cx, |text_thread_editor, cx| {
4656                    TextThreadEditor::insert_dragged_files(
4657                        text_thread_editor,
4658                        paths,
4659                        added_worktrees,
4660                        window,
4661                        cx,
4662                    );
4663                });
4664            }
4665            ActiveView::Uninitialized | ActiveView::History { .. } | ActiveView::Configuration => {}
4666        }
4667    }
4668
4669    fn render_workspace_trust_message(&self, cx: &Context<Self>) -> Option<impl IntoElement> {
4670        if !self.show_trust_workspace_message {
4671            return None;
4672        }
4673
4674        let description = "To protect your system, third-party code—like MCP servers—won't run until you mark this workspace as safe.";
4675
4676        Some(
4677            Callout::new()
4678                .icon(IconName::Warning)
4679                .severity(Severity::Warning)
4680                .border_position(ui::BorderPosition::Bottom)
4681                .title("You're in Restricted Mode")
4682                .description(description)
4683                .actions_slot(
4684                    Button::new("open-trust-modal", "Configure Project Trust")
4685                        .label_size(LabelSize::Small)
4686                        .style(ButtonStyle::Outlined)
4687                        .on_click({
4688                            cx.listener(move |this, _, window, cx| {
4689                                this.workspace
4690                                    .update(cx, |workspace, cx| {
4691                                        workspace
4692                                            .show_worktree_trust_security_modal(true, window, cx)
4693                                    })
4694                                    .log_err();
4695                            })
4696                        }),
4697                ),
4698        )
4699    }
4700
4701    fn key_context(&self) -> KeyContext {
4702        let mut key_context = KeyContext::new_with_defaults();
4703        key_context.add("AgentPanel");
4704        match &self.active_view {
4705            ActiveView::AgentThread { .. } => key_context.add("acp_thread"),
4706            ActiveView::TextThread { .. } => key_context.add("text_thread"),
4707            ActiveView::Uninitialized | ActiveView::History { .. } | ActiveView::Configuration => {}
4708        }
4709        key_context
4710    }
4711}
4712
4713impl Render for AgentPanel {
4714    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
4715        // WARNING: Changes to this element hierarchy can have
4716        // non-obvious implications to the layout of children.
4717        //
4718        // If you need to change it, please confirm:
4719        // - The message editor expands (cmd-option-esc) correctly
4720        // - When expanded, the buttons at the bottom of the panel are displayed correctly
4721        // - Font size works as expected and can be changed with cmd-+/cmd-
4722        // - Scrolling in all views works as expected
4723        // - Files can be dropped into the panel
4724        let content = v_flex()
4725            .relative()
4726            .size_full()
4727            .justify_between()
4728            .key_context(self.key_context())
4729            .on_action(cx.listener(|this, action: &NewThread, window, cx| {
4730                this.new_thread(action, window, cx);
4731            }))
4732            .on_action(cx.listener(|this, _: &OpenHistory, window, cx| {
4733                this.open_history(window, cx);
4734            }))
4735            .on_action(cx.listener(|this, _: &OpenSettings, window, cx| {
4736                this.open_configuration(window, cx);
4737            }))
4738            .on_action(cx.listener(Self::open_active_thread_as_markdown))
4739            .on_action(cx.listener(Self::deploy_rules_library))
4740            .on_action(cx.listener(Self::go_back))
4741            .on_action(cx.listener(Self::toggle_navigation_menu))
4742            .on_action(cx.listener(Self::toggle_options_menu))
4743            .on_action(cx.listener(Self::increase_font_size))
4744            .on_action(cx.listener(Self::decrease_font_size))
4745            .on_action(cx.listener(Self::reset_font_size))
4746            .on_action(cx.listener(Self::toggle_zoom))
4747            .on_action(cx.listener(|this, _: &ReauthenticateAgent, window, cx| {
4748                if let Some(conversation_view) = this.active_conversation_view() {
4749                    conversation_view.update(cx, |conversation_view, cx| {
4750                        conversation_view.reauthenticate(window, cx)
4751                    })
4752                }
4753            }))
4754            .child(self.render_toolbar(window, cx))
4755            .children(self.render_workspace_trust_message(cx))
4756            .children(self.render_onboarding(window, cx))
4757            .map(|parent| {
4758                // Emit configuration error telemetry before entering the match to avoid borrow conflicts
4759                if matches!(&self.active_view, ActiveView::TextThread { .. }) {
4760                    let model_registry = LanguageModelRegistry::read_global(cx);
4761                    let configuration_error =
4762                        model_registry.configuration_error(model_registry.default_model(), cx);
4763                    self.emit_configuration_error_telemetry_if_needed(configuration_error.as_ref());
4764                }
4765
4766                match &self.active_view {
4767                    ActiveView::Uninitialized => parent,
4768                    ActiveView::AgentThread {
4769                        conversation_view, ..
4770                    } => parent
4771                        .child(conversation_view.clone())
4772                        .child(self.render_drag_target(cx)),
4773                    ActiveView::History { history: kind } => match kind {
4774                        History::AgentThreads { view } => parent.child(view.clone()),
4775                        History::TextThreads => parent.child(self.text_thread_history.clone()),
4776                    },
4777                    ActiveView::TextThread {
4778                        text_thread_editor,
4779                        buffer_search_bar,
4780                        ..
4781                    } => {
4782                        let model_registry = LanguageModelRegistry::read_global(cx);
4783                        let configuration_error =
4784                            model_registry.configuration_error(model_registry.default_model(), cx);
4785
4786                        parent
4787                            .map(|this| {
4788                                if !self.should_render_onboarding(cx)
4789                                    && let Some(err) = configuration_error.as_ref()
4790                                {
4791                                    this.child(self.render_configuration_error(
4792                                        true,
4793                                        err,
4794                                        &self.focus_handle(cx),
4795                                        cx,
4796                                    ))
4797                                } else {
4798                                    this
4799                                }
4800                            })
4801                            .child(self.render_text_thread(
4802                                text_thread_editor,
4803                                buffer_search_bar,
4804                                window,
4805                                cx,
4806                            ))
4807                    }
4808                    ActiveView::Configuration => parent.children(self.configuration.clone()),
4809                }
4810            })
4811            .children(self.render_worktree_creation_status(cx))
4812            .children(self.render_trial_end_upsell(window, cx));
4813
4814        match self.active_view.which_font_size_used() {
4815            WhichFontSize::AgentFont => {
4816                WithRemSize::new(ThemeSettings::get_global(cx).agent_ui_font_size(cx))
4817                    .size_full()
4818                    .child(content)
4819                    .into_any()
4820            }
4821            _ => content.into_any(),
4822        }
4823    }
4824}
4825
4826struct PromptLibraryInlineAssist {
4827    workspace: WeakEntity<Workspace>,
4828}
4829
4830impl PromptLibraryInlineAssist {
4831    pub fn new(workspace: WeakEntity<Workspace>) -> Self {
4832        Self { workspace }
4833    }
4834}
4835
4836impl rules_library::InlineAssistDelegate for PromptLibraryInlineAssist {
4837    fn assist(
4838        &self,
4839        prompt_editor: &Entity<Editor>,
4840        initial_prompt: Option<String>,
4841        window: &mut Window,
4842        cx: &mut Context<RulesLibrary>,
4843    ) {
4844        InlineAssistant::update_global(cx, |assistant, cx| {
4845            let Some(workspace) = self.workspace.upgrade() else {
4846                return;
4847            };
4848            let Some(panel) = workspace.read(cx).panel::<AgentPanel>(cx) else {
4849                return;
4850            };
4851            let history = panel
4852                .read(cx)
4853                .connection_store()
4854                .read(cx)
4855                .entry(&crate::Agent::NativeAgent)
4856                .and_then(|s| s.read(cx).history())
4857                .map(|h| h.downgrade());
4858            let project = workspace.read(cx).project().downgrade();
4859            let panel = panel.read(cx);
4860            let thread_store = panel.thread_store().clone();
4861            assistant.assist(
4862                prompt_editor,
4863                self.workspace.clone(),
4864                project,
4865                thread_store,
4866                None,
4867                history,
4868                initial_prompt,
4869                window,
4870                cx,
4871            );
4872        })
4873    }
4874
4875    fn focus_agent_panel(
4876        &self,
4877        workspace: &mut Workspace,
4878        window: &mut Window,
4879        cx: &mut Context<Workspace>,
4880    ) -> bool {
4881        workspace.focus_panel::<AgentPanel>(window, cx).is_some()
4882    }
4883}
4884
4885pub struct ConcreteAssistantPanelDelegate;
4886
4887impl AgentPanelDelegate for ConcreteAssistantPanelDelegate {
4888    fn active_text_thread_editor(
4889        &self,
4890        workspace: &mut Workspace,
4891        _window: &mut Window,
4892        cx: &mut Context<Workspace>,
4893    ) -> Option<Entity<TextThreadEditor>> {
4894        let panel = workspace.panel::<AgentPanel>(cx)?;
4895        panel.read(cx).active_text_thread_editor()
4896    }
4897
4898    fn open_local_text_thread(
4899        &self,
4900        workspace: &mut Workspace,
4901        path: Arc<Path>,
4902        window: &mut Window,
4903        cx: &mut Context<Workspace>,
4904    ) -> Task<Result<()>> {
4905        let Some(panel) = workspace.panel::<AgentPanel>(cx) else {
4906            return Task::ready(Err(anyhow!("Agent panel not found")));
4907        };
4908
4909        panel.update(cx, |panel, cx| {
4910            panel.open_saved_text_thread(path, window, cx)
4911        })
4912    }
4913
4914    fn open_remote_text_thread(
4915        &self,
4916        _workspace: &mut Workspace,
4917        _text_thread_id: assistant_text_thread::TextThreadId,
4918        _window: &mut Window,
4919        _cx: &mut Context<Workspace>,
4920    ) -> Task<Result<Entity<TextThreadEditor>>> {
4921        Task::ready(Err(anyhow!("opening remote context not implemented")))
4922    }
4923
4924    fn quote_selection(
4925        &self,
4926        workspace: &mut Workspace,
4927        selection_ranges: Vec<Range<Anchor>>,
4928        buffer: Entity<MultiBuffer>,
4929        window: &mut Window,
4930        cx: &mut Context<Workspace>,
4931    ) {
4932        let Some(panel) = workspace.panel::<AgentPanel>(cx) else {
4933            return;
4934        };
4935
4936        if !panel.focus_handle(cx).contains_focused(window, cx) {
4937            workspace.toggle_panel_focus::<AgentPanel>(window, cx);
4938        }
4939
4940        panel.update(cx, |_, cx| {
4941            // Wait to create a new context until the workspace is no longer
4942            // being updated.
4943            cx.defer_in(window, move |panel, window, cx| {
4944                if let Some(conversation_view) = panel.active_conversation_view() {
4945                    conversation_view.update(cx, |conversation_view, cx| {
4946                        conversation_view.insert_selections(window, cx);
4947                    });
4948                } else if let Some(text_thread_editor) = panel.active_text_thread_editor() {
4949                    let snapshot = buffer.read(cx).snapshot(cx);
4950                    let selection_ranges = selection_ranges
4951                        .into_iter()
4952                        .map(|range| range.to_point(&snapshot))
4953                        .collect::<Vec<_>>();
4954
4955                    text_thread_editor.update(cx, |text_thread_editor, cx| {
4956                        text_thread_editor.quote_ranges(selection_ranges, snapshot, window, cx)
4957                    });
4958                }
4959            });
4960        });
4961    }
4962
4963    fn quote_terminal_text(
4964        &self,
4965        workspace: &mut Workspace,
4966        text: String,
4967        window: &mut Window,
4968        cx: &mut Context<Workspace>,
4969    ) {
4970        let Some(panel) = workspace.panel::<AgentPanel>(cx) else {
4971            return;
4972        };
4973
4974        if !panel.focus_handle(cx).contains_focused(window, cx) {
4975            workspace.toggle_panel_focus::<AgentPanel>(window, cx);
4976        }
4977
4978        panel.update(cx, |_, cx| {
4979            // Wait to create a new context until the workspace is no longer
4980            // being updated.
4981            cx.defer_in(window, move |panel, window, cx| {
4982                if let Some(conversation_view) = panel.active_conversation_view() {
4983                    conversation_view.update(cx, |conversation_view, cx| {
4984                        conversation_view.insert_terminal_text(text, window, cx);
4985                    });
4986                } else if let Some(text_thread_editor) = panel.active_text_thread_editor() {
4987                    text_thread_editor.update(cx, |text_thread_editor, cx| {
4988                        text_thread_editor.quote_terminal_text(text, window, cx)
4989                    });
4990                }
4991            });
4992        });
4993    }
4994}
4995
4996struct OnboardingUpsell;
4997
4998impl Dismissable for OnboardingUpsell {
4999    const KEY: &'static str = "dismissed-trial-upsell";
5000}
5001
5002struct TrialEndUpsell;
5003
5004impl Dismissable for TrialEndUpsell {
5005    const KEY: &'static str = "dismissed-trial-end-upsell";
5006}
5007
5008/// Test-only helper methods
5009#[cfg(any(test, feature = "test-support"))]
5010impl AgentPanel {
5011    pub fn test_new(
5012        workspace: &Workspace,
5013        text_thread_store: Entity<assistant_text_thread::TextThreadStore>,
5014        window: &mut Window,
5015        cx: &mut Context<Self>,
5016    ) -> Self {
5017        Self::new(workspace, text_thread_store, None, window, cx)
5018    }
5019
5020    /// Opens an external thread using an arbitrary AgentServer.
5021    ///
5022    /// This is a test-only helper that allows visual tests and integration tests
5023    /// to inject a stub server without modifying production code paths.
5024    /// Not compiled into production builds.
5025    pub fn open_external_thread_with_server(
5026        &mut self,
5027        server: Rc<dyn AgentServer>,
5028        window: &mut Window,
5029        cx: &mut Context<Self>,
5030    ) {
5031        let workspace = self.workspace.clone();
5032        let project = self.project.clone();
5033
5034        let ext_agent = Agent::Custom {
5035            id: server.agent_id(),
5036        };
5037
5038        self.create_agent_thread(
5039            server, None, None, None, None, workspace, project, ext_agent, true, window, cx,
5040        );
5041    }
5042
5043    /// Returns the currently active thread view, if any.
5044    ///
5045    /// This is a test-only accessor that exposes the private `active_thread_view()`
5046    /// method for test assertions. Not compiled into production builds.
5047    pub fn active_thread_view_for_tests(&self) -> Option<&Entity<ConversationView>> {
5048        self.active_conversation_view()
5049    }
5050
5051    /// Sets the start_thread_in value directly, bypassing validation.
5052    ///
5053    /// This is a test-only helper for visual tests that need to show specific
5054    /// start_thread_in states without requiring a real git repository.
5055    pub fn set_start_thread_in_for_tests(&mut self, target: StartThreadIn, cx: &mut Context<Self>) {
5056        self.start_thread_in = target;
5057        cx.notify();
5058    }
5059
5060    /// Returns the current worktree creation status.
5061    ///
5062    /// This is a test-only helper for visual tests.
5063    pub fn worktree_creation_status_for_tests(&self) -> Option<&WorktreeCreationStatus> {
5064        self.worktree_creation_status.as_ref()
5065    }
5066
5067    /// Sets the worktree creation status directly.
5068    ///
5069    /// This is a test-only helper for visual tests that need to show the
5070    /// "Creating worktree…" spinner or error banners.
5071    pub fn set_worktree_creation_status_for_tests(
5072        &mut self,
5073        status: Option<WorktreeCreationStatus>,
5074        cx: &mut Context<Self>,
5075    ) {
5076        self.worktree_creation_status = status;
5077        cx.notify();
5078    }
5079
5080    /// Opens the history view.
5081    ///
5082    /// This is a test-only helper that exposes the private `open_history()`
5083    /// method for visual tests.
5084    pub fn open_history_for_tests(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5085        self.open_history(window, cx);
5086    }
5087
5088    /// Opens the start_thread_in selector popover menu.
5089    ///
5090    /// This is a test-only helper for visual tests.
5091    pub fn open_start_thread_in_menu_for_tests(
5092        &mut self,
5093        window: &mut Window,
5094        cx: &mut Context<Self>,
5095    ) {
5096        self.start_thread_in_menu_handle.show(window, cx);
5097    }
5098
5099    /// Dismisses the start_thread_in dropdown menu.
5100    ///
5101    /// This is a test-only helper for visual tests.
5102    pub fn close_start_thread_in_menu_for_tests(&mut self, cx: &mut Context<Self>) {
5103        self.start_thread_in_menu_handle.hide(cx);
5104    }
5105}
5106
5107#[cfg(test)]
5108mod tests {
5109    use super::*;
5110    use crate::conversation_view::tests::{StubAgentServer, init_test};
5111    use crate::test_support::{
5112        active_session_id, open_thread_with_connection, open_thread_with_custom_connection,
5113        send_message,
5114    };
5115    use acp_thread::{StubAgentConnection, ThreadStatus};
5116    use agent_servers::CODEX_ID;
5117    use assistant_text_thread::TextThreadStore;
5118    use feature_flags::FeatureFlagAppExt;
5119    use fs::FakeFs;
5120    use gpui::{TestAppContext, VisualTestContext};
5121    use project::Project;
5122    use serde_json::json;
5123    use std::time::Instant;
5124    use workspace::MultiWorkspace;
5125
5126    #[gpui::test]
5127    async fn test_active_thread_serialize_and_load_round_trip(cx: &mut TestAppContext) {
5128        init_test(cx);
5129        cx.update(|cx| {
5130            cx.update_flags(true, vec!["agent-v2".to_string()]);
5131            agent::ThreadStore::init_global(cx);
5132            language_model::LanguageModelRegistry::test(cx);
5133        });
5134
5135        // --- Create a MultiWorkspace window with two workspaces ---
5136        let fs = FakeFs::new(cx.executor());
5137        let project_a = Project::test(fs.clone(), [], cx).await;
5138        let project_b = Project::test(fs, [], cx).await;
5139
5140        let multi_workspace =
5141            cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
5142
5143        let workspace_a = multi_workspace
5144            .read_with(cx, |multi_workspace, _cx| {
5145                multi_workspace.workspace().clone()
5146            })
5147            .unwrap();
5148
5149        let workspace_b = multi_workspace
5150            .update(cx, |multi_workspace, window, cx| {
5151                multi_workspace.test_add_workspace(project_b.clone(), window, cx)
5152            })
5153            .unwrap();
5154
5155        workspace_a.update(cx, |workspace, _cx| {
5156            workspace.set_random_database_id();
5157        });
5158        workspace_b.update(cx, |workspace, _cx| {
5159            workspace.set_random_database_id();
5160        });
5161
5162        let cx = &mut VisualTestContext::from_window(multi_workspace.into(), cx);
5163
5164        // --- Set up workspace A: with an active thread ---
5165        let panel_a = workspace_a.update_in(cx, |workspace, window, cx| {
5166            let text_thread_store = cx.new(|cx| TextThreadStore::fake(project_a.clone(), cx));
5167            cx.new(|cx| AgentPanel::new(workspace, text_thread_store, None, window, cx))
5168        });
5169
5170        panel_a.update_in(cx, |panel, window, cx| {
5171            panel.open_external_thread_with_server(
5172                Rc::new(StubAgentServer::default_response()),
5173                window,
5174                cx,
5175            );
5176        });
5177
5178        cx.run_until_parked();
5179
5180        panel_a.read_with(cx, |panel, cx| {
5181            assert!(
5182                panel.active_agent_thread(cx).is_some(),
5183                "workspace A should have an active thread after connection"
5184            );
5185        });
5186
5187        let agent_type_a = panel_a.read_with(cx, |panel, _cx| panel.selected_agent_type.clone());
5188
5189        // --- Set up workspace B: ClaudeCode, no active thread ---
5190        let panel_b = workspace_b.update_in(cx, |workspace, window, cx| {
5191            let text_thread_store = cx.new(|cx| TextThreadStore::fake(project_b.clone(), cx));
5192            cx.new(|cx| AgentPanel::new(workspace, text_thread_store, None, window, cx))
5193        });
5194
5195        panel_b.update(cx, |panel, _cx| {
5196            panel.selected_agent_type = AgentType::Custom {
5197                id: "claude-acp".into(),
5198            };
5199        });
5200
5201        // --- Serialize both panels ---
5202        panel_a.update(cx, |panel, cx| panel.serialize(cx));
5203        panel_b.update(cx, |panel, cx| panel.serialize(cx));
5204        cx.run_until_parked();
5205
5206        // --- Load fresh panels for each workspace and verify independent state ---
5207        let prompt_builder = Arc::new(prompt_store::PromptBuilder::new(None).unwrap());
5208
5209        let async_cx = cx.update(|window, cx| window.to_async(cx));
5210        let loaded_a = AgentPanel::load(workspace_a.downgrade(), prompt_builder.clone(), async_cx)
5211            .await
5212            .expect("panel A load should succeed");
5213        cx.run_until_parked();
5214
5215        let async_cx = cx.update(|window, cx| window.to_async(cx));
5216        let loaded_b = AgentPanel::load(workspace_b.downgrade(), prompt_builder.clone(), async_cx)
5217            .await
5218            .expect("panel B load should succeed");
5219        cx.run_until_parked();
5220
5221        // Workspace A should restore its thread and agent type
5222        loaded_a.read_with(cx, |panel, _cx| {
5223            assert_eq!(
5224                panel.selected_agent_type, agent_type_a,
5225                "workspace A agent type should be restored"
5226            );
5227            assert!(
5228                panel.active_conversation_view().is_some(),
5229                "workspace A should have its active thread restored"
5230            );
5231        });
5232
5233        // Workspace B should restore its own agent type, with no thread
5234        loaded_b.read_with(cx, |panel, _cx| {
5235            assert_eq!(
5236                panel.selected_agent_type,
5237                AgentType::Custom {
5238                    id: "claude-acp".into()
5239                },
5240                "workspace B agent type should be restored"
5241            );
5242            assert!(
5243                panel.active_conversation_view().is_none(),
5244                "workspace B should have no active thread"
5245            );
5246        });
5247    }
5248
5249    // Simple regression test
5250    #[gpui::test]
5251    async fn test_new_text_thread_action_handler(cx: &mut TestAppContext) {
5252        init_test(cx);
5253
5254        let fs = FakeFs::new(cx.executor());
5255
5256        cx.update(|cx| {
5257            cx.update_flags(true, vec!["agent-v2".to_string()]);
5258            agent::ThreadStore::init_global(cx);
5259            language_model::LanguageModelRegistry::test(cx);
5260            let slash_command_registry =
5261                assistant_slash_command::SlashCommandRegistry::default_global(cx);
5262            slash_command_registry
5263                .register_command(assistant_slash_commands::DefaultSlashCommand, false);
5264            <dyn fs::Fs>::set_global(fs.clone(), cx);
5265        });
5266
5267        let project = Project::test(fs.clone(), [], cx).await;
5268
5269        let multi_workspace =
5270            cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
5271
5272        let workspace_a = multi_workspace
5273            .read_with(cx, |multi_workspace, _cx| {
5274                multi_workspace.workspace().clone()
5275            })
5276            .unwrap();
5277
5278        let cx = &mut VisualTestContext::from_window(multi_workspace.into(), cx);
5279
5280        workspace_a.update_in(cx, |workspace, window, cx| {
5281            let text_thread_store = cx.new(|cx| TextThreadStore::fake(project.clone(), cx));
5282            let panel =
5283                cx.new(|cx| AgentPanel::new(workspace, text_thread_store, None, window, cx));
5284            workspace.add_panel(panel, window, cx);
5285        });
5286
5287        cx.run_until_parked();
5288
5289        workspace_a.update_in(cx, |_, window, cx| {
5290            window.dispatch_action(NewTextThread.boxed_clone(), cx);
5291        });
5292
5293        cx.run_until_parked();
5294    }
5295
5296    /// Extracts the text from a Text content block, panicking if it's not Text.
5297    fn expect_text_block(block: &acp::ContentBlock) -> &str {
5298        match block {
5299            acp::ContentBlock::Text(t) => t.text.as_str(),
5300            other => panic!("expected Text block, got {:?}", other),
5301        }
5302    }
5303
5304    /// Extracts the (text_content, uri) from a Resource content block, panicking
5305    /// if it's not a TextResourceContents resource.
5306    fn expect_resource_block(block: &acp::ContentBlock) -> (&str, &str) {
5307        match block {
5308            acp::ContentBlock::Resource(r) => match &r.resource {
5309                acp::EmbeddedResourceResource::TextResourceContents(t) => {
5310                    (t.text.as_str(), t.uri.as_str())
5311                }
5312                other => panic!("expected TextResourceContents, got {:?}", other),
5313            },
5314            other => panic!("expected Resource block, got {:?}", other),
5315        }
5316    }
5317
5318    #[test]
5319    fn test_build_conflict_resolution_prompt_single_conflict() {
5320        let conflicts = vec![ConflictContent {
5321            file_path: "src/main.rs".to_string(),
5322            conflict_text: "<<<<<<< HEAD\nlet x = 1;\n=======\nlet x = 2;\n>>>>>>> feature"
5323                .to_string(),
5324            ours_branch_name: "HEAD".to_string(),
5325            theirs_branch_name: "feature".to_string(),
5326        }];
5327
5328        let blocks = build_conflict_resolution_prompt(&conflicts);
5329        // 2 Text blocks + 1 ResourceLink + 1 Resource for the conflict
5330        assert_eq!(
5331            blocks.len(),
5332            4,
5333            "expected 2 text + 1 resource link + 1 resource block"
5334        );
5335
5336        let intro_text = expect_text_block(&blocks[0]);
5337        assert!(
5338            intro_text.contains("Please resolve the following merge conflict in"),
5339            "prompt should include single-conflict intro text"
5340        );
5341
5342        match &blocks[1] {
5343            acp::ContentBlock::ResourceLink(link) => {
5344                assert!(
5345                    link.uri.contains("file://"),
5346                    "resource link URI should use file scheme"
5347                );
5348                assert!(
5349                    link.uri.contains("main.rs"),
5350                    "resource link URI should reference file path"
5351                );
5352            }
5353            other => panic!("expected ResourceLink block, got {:?}", other),
5354        }
5355
5356        let body_text = expect_text_block(&blocks[2]);
5357        assert!(
5358            body_text.contains("`HEAD` (ours)"),
5359            "prompt should mention ours branch"
5360        );
5361        assert!(
5362            body_text.contains("`feature` (theirs)"),
5363            "prompt should mention theirs branch"
5364        );
5365        assert!(
5366            body_text.contains("editing the file directly"),
5367            "prompt should instruct the agent to edit the file"
5368        );
5369
5370        let (resource_text, resource_uri) = expect_resource_block(&blocks[3]);
5371        assert!(
5372            resource_text.contains("<<<<<<< HEAD"),
5373            "resource should contain the conflict text"
5374        );
5375        assert!(
5376            resource_uri.contains("merge-conflict"),
5377            "resource URI should use the merge-conflict scheme"
5378        );
5379        assert!(
5380            resource_uri.contains("main.rs"),
5381            "resource URI should reference the file path"
5382        );
5383    }
5384
5385    #[test]
5386    fn test_build_conflict_resolution_prompt_multiple_conflicts_same_file() {
5387        let conflicts = vec![
5388            ConflictContent {
5389                file_path: "src/lib.rs".to_string(),
5390                conflict_text: "<<<<<<< main\nfn a() {}\n=======\nfn a_v2() {}\n>>>>>>> dev"
5391                    .to_string(),
5392                ours_branch_name: "main".to_string(),
5393                theirs_branch_name: "dev".to_string(),
5394            },
5395            ConflictContent {
5396                file_path: "src/lib.rs".to_string(),
5397                conflict_text: "<<<<<<< main\nfn b() {}\n=======\nfn b_v2() {}\n>>>>>>> dev"
5398                    .to_string(),
5399                ours_branch_name: "main".to_string(),
5400                theirs_branch_name: "dev".to_string(),
5401            },
5402        ];
5403
5404        let blocks = build_conflict_resolution_prompt(&conflicts);
5405        // 1 Text instruction + 2 Resource blocks
5406        assert_eq!(blocks.len(), 3, "expected 1 text + 2 resource blocks");
5407
5408        let text = expect_text_block(&blocks[0]);
5409        assert!(
5410            text.contains("all 2 merge conflicts"),
5411            "prompt should mention the total count"
5412        );
5413        assert!(
5414            text.contains("`main` (ours)"),
5415            "prompt should mention ours branch"
5416        );
5417        assert!(
5418            text.contains("`dev` (theirs)"),
5419            "prompt should mention theirs branch"
5420        );
5421        // Single file, so "file" not "files"
5422        assert!(
5423            text.contains("file directly"),
5424            "single file should use singular 'file'"
5425        );
5426
5427        let (resource_a, _) = expect_resource_block(&blocks[1]);
5428        let (resource_b, _) = expect_resource_block(&blocks[2]);
5429        assert!(
5430            resource_a.contains("fn a()"),
5431            "first resource should contain first conflict"
5432        );
5433        assert!(
5434            resource_b.contains("fn b()"),
5435            "second resource should contain second conflict"
5436        );
5437    }
5438
5439    #[test]
5440    fn test_build_conflict_resolution_prompt_multiple_conflicts_different_files() {
5441        let conflicts = vec![
5442            ConflictContent {
5443                file_path: "src/a.rs".to_string(),
5444                conflict_text: "<<<<<<< main\nA\n=======\nB\n>>>>>>> dev".to_string(),
5445                ours_branch_name: "main".to_string(),
5446                theirs_branch_name: "dev".to_string(),
5447            },
5448            ConflictContent {
5449                file_path: "src/b.rs".to_string(),
5450                conflict_text: "<<<<<<< main\nC\n=======\nD\n>>>>>>> dev".to_string(),
5451                ours_branch_name: "main".to_string(),
5452                theirs_branch_name: "dev".to_string(),
5453            },
5454        ];
5455
5456        let blocks = build_conflict_resolution_prompt(&conflicts);
5457        // 1 Text instruction + 2 Resource blocks
5458        assert_eq!(blocks.len(), 3, "expected 1 text + 2 resource blocks");
5459
5460        let text = expect_text_block(&blocks[0]);
5461        assert!(
5462            text.contains("files directly"),
5463            "multiple files should use plural 'files'"
5464        );
5465
5466        let (_, uri_a) = expect_resource_block(&blocks[1]);
5467        let (_, uri_b) = expect_resource_block(&blocks[2]);
5468        assert!(
5469            uri_a.contains("a.rs"),
5470            "first resource URI should reference a.rs"
5471        );
5472        assert!(
5473            uri_b.contains("b.rs"),
5474            "second resource URI should reference b.rs"
5475        );
5476    }
5477
5478    #[test]
5479    fn test_build_conflicted_files_resolution_prompt_file_paths_only() {
5480        let file_paths = vec![
5481            "src/main.rs".to_string(),
5482            "src/lib.rs".to_string(),
5483            "tests/integration.rs".to_string(),
5484        ];
5485
5486        let blocks = build_conflicted_files_resolution_prompt(&file_paths);
5487        // 1 instruction Text block + (ResourceLink + newline Text) per file
5488        assert_eq!(
5489            blocks.len(),
5490            1 + (file_paths.len() * 2),
5491            "expected instruction text plus resource links and separators"
5492        );
5493
5494        let text = expect_text_block(&blocks[0]);
5495        assert!(
5496            text.contains("unresolved merge conflicts"),
5497            "prompt should describe the task"
5498        );
5499        assert!(
5500            text.contains("conflict markers"),
5501            "prompt should mention conflict markers"
5502        );
5503
5504        for (index, path) in file_paths.iter().enumerate() {
5505            let link_index = 1 + (index * 2);
5506            let newline_index = link_index + 1;
5507
5508            match &blocks[link_index] {
5509                acp::ContentBlock::ResourceLink(link) => {
5510                    assert!(
5511                        link.uri.contains("file://"),
5512                        "resource link URI should use file scheme"
5513                    );
5514                    assert!(
5515                        link.uri.contains(path),
5516                        "resource link URI should reference file path: {path}"
5517                    );
5518                }
5519                other => panic!(
5520                    "expected ResourceLink block at index {}, got {:?}",
5521                    link_index, other
5522                ),
5523            }
5524
5525            let separator = expect_text_block(&blocks[newline_index]);
5526            assert_eq!(
5527                separator, "\n",
5528                "expected newline separator after each file"
5529            );
5530        }
5531    }
5532
5533    #[test]
5534    fn test_build_conflict_resolution_prompt_empty_conflicts() {
5535        let blocks = build_conflict_resolution_prompt(&[]);
5536        assert!(
5537            blocks.is_empty(),
5538            "empty conflicts should produce no blocks, got {} blocks",
5539            blocks.len()
5540        );
5541    }
5542
5543    #[test]
5544    fn test_build_conflicted_files_resolution_prompt_empty_paths() {
5545        let blocks = build_conflicted_files_resolution_prompt(&[]);
5546        assert!(
5547            blocks.is_empty(),
5548            "empty paths should produce no blocks, got {} blocks",
5549            blocks.len()
5550        );
5551    }
5552
5553    #[test]
5554    fn test_conflict_resource_block_structure() {
5555        let conflict = ConflictContent {
5556            file_path: "src/utils.rs".to_string(),
5557            conflict_text: "<<<<<<< HEAD\nold code\n=======\nnew code\n>>>>>>> branch".to_string(),
5558            ours_branch_name: "HEAD".to_string(),
5559            theirs_branch_name: "branch".to_string(),
5560        };
5561
5562        let block = conflict_resource_block(&conflict);
5563        let (text, uri) = expect_resource_block(&block);
5564
5565        assert_eq!(
5566            text, conflict.conflict_text,
5567            "resource text should be the raw conflict"
5568        );
5569        assert!(
5570            uri.starts_with("zed:///agent/merge-conflict"),
5571            "URI should use the zed merge-conflict scheme, got: {uri}"
5572        );
5573        assert!(uri.contains("utils.rs"), "URI should encode the file path");
5574    }
5575
5576    fn open_generating_thread_with_loadable_connection(
5577        panel: &Entity<AgentPanel>,
5578        connection: &StubAgentConnection,
5579        cx: &mut VisualTestContext,
5580    ) -> acp::SessionId {
5581        open_thread_with_custom_connection(panel, connection.clone(), cx);
5582        let session_id = active_session_id(panel, cx);
5583        send_message(panel, cx);
5584        cx.update(|_, cx| {
5585            connection.send_update(
5586                session_id.clone(),
5587                acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new("done".into())),
5588                cx,
5589            );
5590        });
5591        cx.run_until_parked();
5592        session_id
5593    }
5594
5595    fn open_idle_thread_with_non_loadable_connection(
5596        panel: &Entity<AgentPanel>,
5597        connection: &StubAgentConnection,
5598        cx: &mut VisualTestContext,
5599    ) -> acp::SessionId {
5600        open_thread_with_custom_connection(panel, connection.clone(), cx);
5601        let session_id = active_session_id(panel, cx);
5602
5603        connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
5604            acp::ContentChunk::new("done".into()),
5605        )]);
5606        send_message(panel, cx);
5607
5608        session_id
5609    }
5610
5611    async fn setup_panel(cx: &mut TestAppContext) -> (Entity<AgentPanel>, VisualTestContext) {
5612        init_test(cx);
5613        cx.update(|cx| {
5614            cx.update_flags(true, vec!["agent-v2".to_string()]);
5615            agent::ThreadStore::init_global(cx);
5616            language_model::LanguageModelRegistry::test(cx);
5617        });
5618
5619        let fs = FakeFs::new(cx.executor());
5620        let project = Project::test(fs.clone(), [], cx).await;
5621
5622        let multi_workspace =
5623            cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
5624
5625        let workspace = multi_workspace
5626            .read_with(cx, |mw, _cx| mw.workspace().clone())
5627            .unwrap();
5628
5629        let mut cx = VisualTestContext::from_window(multi_workspace.into(), cx);
5630
5631        let panel = workspace.update_in(&mut cx, |workspace, window, cx| {
5632            let text_thread_store = cx.new(|cx| TextThreadStore::fake(project.clone(), cx));
5633            cx.new(|cx| AgentPanel::new(workspace, text_thread_store, None, window, cx))
5634        });
5635
5636        (panel, cx)
5637    }
5638
5639    #[gpui::test]
5640    async fn test_running_thread_retained_when_navigating_away(cx: &mut TestAppContext) {
5641        let (panel, mut cx) = setup_panel(cx).await;
5642
5643        let connection_a = StubAgentConnection::new();
5644        open_thread_with_connection(&panel, connection_a.clone(), &mut cx);
5645        send_message(&panel, &mut cx);
5646
5647        let session_id_a = active_session_id(&panel, &cx);
5648
5649        // Send a chunk to keep thread A generating (don't end the turn).
5650        cx.update(|_, cx| {
5651            connection_a.send_update(
5652                session_id_a.clone(),
5653                acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new("chunk".into())),
5654                cx,
5655            );
5656        });
5657        cx.run_until_parked();
5658
5659        // Verify thread A is generating.
5660        panel.read_with(&cx, |panel, cx| {
5661            let thread = panel.active_agent_thread(cx).unwrap();
5662            assert_eq!(thread.read(cx).status(), ThreadStatus::Generating);
5663            assert!(panel.background_threads.is_empty());
5664        });
5665
5666        // Open a new thread B — thread A should be retained in background.
5667        let connection_b = StubAgentConnection::new();
5668        open_thread_with_connection(&panel, connection_b, &mut cx);
5669
5670        panel.read_with(&cx, |panel, _cx| {
5671            assert_eq!(
5672                panel.background_threads.len(),
5673                1,
5674                "Running thread A should be retained in background_views"
5675            );
5676            assert!(
5677                panel.background_threads.contains_key(&session_id_a),
5678                "Background view should be keyed by thread A's session ID"
5679            );
5680        });
5681    }
5682
5683    #[gpui::test]
5684    async fn test_idle_non_loadable_thread_retained_when_navigating_away(cx: &mut TestAppContext) {
5685        let (panel, mut cx) = setup_panel(cx).await;
5686
5687        let connection_a = StubAgentConnection::new();
5688        connection_a.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
5689            acp::ContentChunk::new("Response".into()),
5690        )]);
5691        open_thread_with_connection(&panel, connection_a, &mut cx);
5692        send_message(&panel, &mut cx);
5693
5694        let weak_view_a = panel.read_with(&cx, |panel, _cx| {
5695            panel.active_conversation_view().unwrap().downgrade()
5696        });
5697        let session_id_a = active_session_id(&panel, &cx);
5698
5699        // Thread A should be idle (auto-completed via set_next_prompt_updates).
5700        panel.read_with(&cx, |panel, cx| {
5701            let thread = panel.active_agent_thread(cx).unwrap();
5702            assert_eq!(thread.read(cx).status(), ThreadStatus::Idle);
5703        });
5704
5705        // Open a new thread B — thread A should be retained because it is not loadable.
5706        let connection_b = StubAgentConnection::new();
5707        open_thread_with_connection(&panel, connection_b, &mut cx);
5708
5709        panel.read_with(&cx, |panel, _cx| {
5710            assert_eq!(
5711                panel.background_threads.len(),
5712                1,
5713                "Idle non-loadable thread A should be retained in background_views"
5714            );
5715            assert!(
5716                panel.background_threads.contains_key(&session_id_a),
5717                "Background view should be keyed by thread A's session ID"
5718            );
5719        });
5720
5721        assert!(
5722            weak_view_a.upgrade().is_some(),
5723            "Idle non-loadable ConnectionView should still be retained"
5724        );
5725    }
5726
5727    #[gpui::test]
5728    async fn test_background_thread_promoted_via_load(cx: &mut TestAppContext) {
5729        let (panel, mut cx) = setup_panel(cx).await;
5730
5731        let connection_a = StubAgentConnection::new();
5732        open_thread_with_connection(&panel, connection_a.clone(), &mut cx);
5733        send_message(&panel, &mut cx);
5734
5735        let session_id_a = active_session_id(&panel, &cx);
5736
5737        // Keep thread A generating.
5738        cx.update(|_, cx| {
5739            connection_a.send_update(
5740                session_id_a.clone(),
5741                acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new("chunk".into())),
5742                cx,
5743            );
5744        });
5745        cx.run_until_parked();
5746
5747        // Open thread B — thread A goes to background.
5748        let connection_b = StubAgentConnection::new();
5749        open_thread_with_connection(&panel, connection_b, &mut cx);
5750
5751        let session_id_b = active_session_id(&panel, &cx);
5752
5753        panel.read_with(&cx, |panel, _cx| {
5754            assert_eq!(panel.background_threads.len(), 1);
5755            assert!(panel.background_threads.contains_key(&session_id_a));
5756        });
5757
5758        // Load thread A back via load_agent_thread — should promote from background.
5759        panel.update_in(&mut cx, |panel, window, cx| {
5760            panel.load_agent_thread(
5761                panel.selected_agent().expect("selected agent must be set"),
5762                session_id_a.clone(),
5763                None,
5764                None,
5765                true,
5766                window,
5767                cx,
5768            );
5769        });
5770
5771        // Thread A should now be the active view, promoted from background.
5772        let active_session = active_session_id(&panel, &cx);
5773        assert_eq!(
5774            active_session, session_id_a,
5775            "Thread A should be the active thread after promotion"
5776        );
5777
5778        panel.read_with(&cx, |panel, _cx| {
5779            assert!(
5780                !panel.background_threads.contains_key(&session_id_a),
5781                "Promoted thread A should no longer be in background_views"
5782            );
5783            assert!(
5784                panel.background_threads.contains_key(&session_id_b),
5785                "Thread B (idle, non-loadable) should remain retained in background_views"
5786            );
5787        });
5788    }
5789
5790    #[gpui::test]
5791    async fn test_cleanup_background_threads_keeps_five_most_recent_idle_loadable_threads(
5792        cx: &mut TestAppContext,
5793    ) {
5794        let (panel, mut cx) = setup_panel(cx).await;
5795        let connection = StubAgentConnection::new()
5796            .with_supports_load_session(true)
5797            .with_agent_id("loadable-stub".into())
5798            .with_telemetry_id("loadable-stub".into());
5799        let mut session_ids = Vec::new();
5800
5801        for _ in 0..7 {
5802            session_ids.push(open_generating_thread_with_loadable_connection(
5803                &panel,
5804                &connection,
5805                &mut cx,
5806            ));
5807        }
5808
5809        let base_time = Instant::now();
5810
5811        for session_id in session_ids.iter().take(6) {
5812            connection.end_turn(session_id.clone(), acp::StopReason::EndTurn);
5813        }
5814        cx.run_until_parked();
5815
5816        panel.update(&mut cx, |panel, cx| {
5817            for (index, session_id) in session_ids.iter().take(6).enumerate() {
5818                let conversation_view = panel
5819                    .background_threads
5820                    .get(session_id)
5821                    .expect("background thread should exist")
5822                    .clone();
5823                conversation_view.update(cx, |view, cx| {
5824                    view.set_updated_at(base_time + Duration::from_secs(index as u64), cx);
5825                });
5826            }
5827            panel.cleanup_background_threads(cx);
5828        });
5829
5830        panel.read_with(&cx, |panel, _cx| {
5831            assert_eq!(
5832                panel.background_threads.len(),
5833                5,
5834                "cleanup should keep at most five idle loadable background threads"
5835            );
5836            assert!(
5837                !panel.background_threads.contains_key(&session_ids[0]),
5838                "oldest idle loadable background thread should be removed"
5839            );
5840            for session_id in &session_ids[1..6] {
5841                assert!(
5842                    panel.background_threads.contains_key(session_id),
5843                    "more recent idle loadable background threads should be retained"
5844                );
5845            }
5846            assert!(
5847                !panel.background_threads.contains_key(&session_ids[6]),
5848                "the active thread should not also be stored as a background thread"
5849            );
5850        });
5851    }
5852
5853    #[gpui::test]
5854    async fn test_cleanup_background_threads_preserves_idle_non_loadable_threads(
5855        cx: &mut TestAppContext,
5856    ) {
5857        let (panel, mut cx) = setup_panel(cx).await;
5858
5859        let non_loadable_connection = StubAgentConnection::new();
5860        let non_loadable_session_id = open_idle_thread_with_non_loadable_connection(
5861            &panel,
5862            &non_loadable_connection,
5863            &mut cx,
5864        );
5865
5866        let loadable_connection = StubAgentConnection::new()
5867            .with_supports_load_session(true)
5868            .with_agent_id("loadable-stub".into())
5869            .with_telemetry_id("loadable-stub".into());
5870        let mut loadable_session_ids = Vec::new();
5871
5872        for _ in 0..7 {
5873            loadable_session_ids.push(open_generating_thread_with_loadable_connection(
5874                &panel,
5875                &loadable_connection,
5876                &mut cx,
5877            ));
5878        }
5879
5880        let base_time = Instant::now();
5881
5882        for session_id in loadable_session_ids.iter().take(6) {
5883            loadable_connection.end_turn(session_id.clone(), acp::StopReason::EndTurn);
5884        }
5885        cx.run_until_parked();
5886
5887        panel.update(&mut cx, |panel, cx| {
5888            for (index, session_id) in loadable_session_ids.iter().take(6).enumerate() {
5889                let conversation_view = panel
5890                    .background_threads
5891                    .get(session_id)
5892                    .expect("background thread should exist")
5893                    .clone();
5894                conversation_view.update(cx, |view, cx| {
5895                    view.set_updated_at(base_time + Duration::from_secs(index as u64), cx);
5896                });
5897            }
5898            panel.cleanup_background_threads(cx);
5899        });
5900
5901        panel.read_with(&cx, |panel, _cx| {
5902            assert_eq!(
5903                panel.background_threads.len(),
5904                6,
5905                "cleanup should keep the non-loadable idle thread in addition to five loadable ones"
5906            );
5907            assert!(
5908                panel
5909                    .background_threads
5910                    .contains_key(&non_loadable_session_id),
5911                "idle non-loadable background threads should not be cleanup candidates"
5912            );
5913            assert!(
5914                !panel
5915                    .background_threads
5916                    .contains_key(&loadable_session_ids[0]),
5917                "oldest idle loadable background thread should still be removed"
5918            );
5919            for session_id in &loadable_session_ids[1..6] {
5920                assert!(
5921                    panel.background_threads.contains_key(session_id),
5922                    "more recent idle loadable background threads should be retained"
5923                );
5924            }
5925            assert!(
5926                !panel
5927                    .background_threads
5928                    .contains_key(&loadable_session_ids[6]),
5929                "the active loadable thread should not also be stored as a background thread"
5930            );
5931        });
5932    }
5933
5934    #[gpui::test]
5935    async fn test_thread_target_local_project(cx: &mut TestAppContext) {
5936        init_test(cx);
5937        cx.update(|cx| {
5938            cx.update_flags(true, vec!["agent-v2".to_string()]);
5939            agent::ThreadStore::init_global(cx);
5940            language_model::LanguageModelRegistry::test(cx);
5941        });
5942
5943        let fs = FakeFs::new(cx.executor());
5944        fs.insert_tree(
5945            "/project",
5946            json!({
5947                ".git": {},
5948                "src": {
5949                    "main.rs": "fn main() {}"
5950                }
5951            }),
5952        )
5953        .await;
5954        fs.set_branch_name(Path::new("/project/.git"), Some("main"));
5955
5956        let project = Project::test(fs.clone(), [Path::new("/project")], cx).await;
5957
5958        let multi_workspace =
5959            cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
5960
5961        let workspace = multi_workspace
5962            .read_with(cx, |multi_workspace, _cx| {
5963                multi_workspace.workspace().clone()
5964            })
5965            .unwrap();
5966
5967        workspace.update(cx, |workspace, _cx| {
5968            workspace.set_random_database_id();
5969        });
5970
5971        let cx = &mut VisualTestContext::from_window(multi_workspace.into(), cx);
5972
5973        // Wait for the project to discover the git repository.
5974        cx.run_until_parked();
5975
5976        let panel = workspace.update_in(cx, |workspace, window, cx| {
5977            let text_thread_store = cx.new(|cx| TextThreadStore::fake(project.clone(), cx));
5978            let panel =
5979                cx.new(|cx| AgentPanel::new(workspace, text_thread_store, None, window, cx));
5980            workspace.add_panel(panel.clone(), window, cx);
5981            panel
5982        });
5983
5984        cx.run_until_parked();
5985
5986        // Default thread target should be LocalProject.
5987        panel.read_with(cx, |panel, _cx| {
5988            assert_eq!(
5989                *panel.start_thread_in(),
5990                StartThreadIn::LocalProject,
5991                "default thread target should be LocalProject"
5992            );
5993        });
5994
5995        // Start a new thread with the default LocalProject target.
5996        // Use StubAgentServer so the thread connects immediately in tests.
5997        panel.update_in(cx, |panel, window, cx| {
5998            panel.open_external_thread_with_server(
5999                Rc::new(StubAgentServer::default_response()),
6000                window,
6001                cx,
6002            );
6003        });
6004
6005        cx.run_until_parked();
6006
6007        // MultiWorkspace should still have exactly one workspace (no worktree created).
6008        multi_workspace
6009            .read_with(cx, |multi_workspace, _cx| {
6010                assert_eq!(
6011                    multi_workspace.workspaces().len(),
6012                    1,
6013                    "LocalProject should not create a new workspace"
6014                );
6015            })
6016            .unwrap();
6017
6018        // The thread should be active in the panel.
6019        panel.read_with(cx, |panel, cx| {
6020            assert!(
6021                panel.active_agent_thread(cx).is_some(),
6022                "a thread should be running in the current workspace"
6023            );
6024        });
6025
6026        // The thread target should still be LocalProject (unchanged).
6027        panel.read_with(cx, |panel, _cx| {
6028            assert_eq!(
6029                *panel.start_thread_in(),
6030                StartThreadIn::LocalProject,
6031                "thread target should remain LocalProject"
6032            );
6033        });
6034
6035        // No worktree creation status should be set.
6036        panel.read_with(cx, |panel, _cx| {
6037            assert!(
6038                panel.worktree_creation_status.is_none(),
6039                "no worktree creation should have occurred"
6040            );
6041        });
6042    }
6043
6044    #[gpui::test]
6045    async fn test_thread_target_serialization_round_trip(cx: &mut TestAppContext) {
6046        init_test(cx);
6047        cx.update(|cx| {
6048            cx.update_flags(true, vec!["agent-v2".to_string()]);
6049            agent::ThreadStore::init_global(cx);
6050            language_model::LanguageModelRegistry::test(cx);
6051        });
6052
6053        let fs = FakeFs::new(cx.executor());
6054        fs.insert_tree(
6055            "/project",
6056            json!({
6057                ".git": {},
6058                "src": {
6059                    "main.rs": "fn main() {}"
6060                }
6061            }),
6062        )
6063        .await;
6064        fs.set_branch_name(Path::new("/project/.git"), Some("main"));
6065
6066        let project = Project::test(fs.clone(), [Path::new("/project")], cx).await;
6067
6068        let multi_workspace =
6069            cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
6070
6071        let workspace = multi_workspace
6072            .read_with(cx, |multi_workspace, _cx| {
6073                multi_workspace.workspace().clone()
6074            })
6075            .unwrap();
6076
6077        workspace.update(cx, |workspace, _cx| {
6078            workspace.set_random_database_id();
6079        });
6080
6081        let cx = &mut VisualTestContext::from_window(multi_workspace.into(), cx);
6082
6083        // Wait for the project to discover the git repository.
6084        cx.run_until_parked();
6085
6086        let panel = workspace.update_in(cx, |workspace, window, cx| {
6087            let text_thread_store = cx.new(|cx| TextThreadStore::fake(project.clone(), cx));
6088            let panel =
6089                cx.new(|cx| AgentPanel::new(workspace, text_thread_store, None, window, cx));
6090            workspace.add_panel(panel.clone(), window, cx);
6091            panel
6092        });
6093
6094        cx.run_until_parked();
6095
6096        // Default should be LocalProject.
6097        panel.read_with(cx, |panel, _cx| {
6098            assert_eq!(*panel.start_thread_in(), StartThreadIn::LocalProject);
6099        });
6100
6101        // Change thread target to NewWorktree.
6102        panel.update_in(cx, |panel, window, cx| {
6103            panel.set_start_thread_in(&StartThreadIn::NewWorktree, window, cx);
6104        });
6105
6106        panel.read_with(cx, |panel, _cx| {
6107            assert_eq!(
6108                *panel.start_thread_in(),
6109                StartThreadIn::NewWorktree,
6110                "thread target should be NewWorktree after set_thread_target"
6111            );
6112        });
6113
6114        // Let serialization complete.
6115        cx.run_until_parked();
6116
6117        // Load a fresh panel from the serialized data.
6118        let prompt_builder = Arc::new(prompt_store::PromptBuilder::new(None).unwrap());
6119        let async_cx = cx.update(|window, cx| window.to_async(cx));
6120        let loaded_panel =
6121            AgentPanel::load(workspace.downgrade(), prompt_builder.clone(), async_cx)
6122                .await
6123                .expect("panel load should succeed");
6124        cx.run_until_parked();
6125
6126        loaded_panel.read_with(cx, |panel, _cx| {
6127            assert_eq!(
6128                *panel.start_thread_in(),
6129                StartThreadIn::NewWorktree,
6130                "thread target should survive serialization round-trip"
6131            );
6132        });
6133    }
6134
6135    #[gpui::test]
6136    async fn test_set_active_blocked_during_worktree_creation(cx: &mut TestAppContext) {
6137        init_test(cx);
6138
6139        let fs = FakeFs::new(cx.executor());
6140        cx.update(|cx| {
6141            cx.update_flags(true, vec!["agent-v2".to_string()]);
6142            agent::ThreadStore::init_global(cx);
6143            language_model::LanguageModelRegistry::test(cx);
6144            <dyn fs::Fs>::set_global(fs.clone(), cx);
6145        });
6146
6147        fs.insert_tree(
6148            "/project",
6149            json!({
6150                ".git": {},
6151                "src": {
6152                    "main.rs": "fn main() {}"
6153                }
6154            }),
6155        )
6156        .await;
6157
6158        let project = Project::test(fs.clone(), [Path::new("/project")], cx).await;
6159
6160        let multi_workspace =
6161            cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
6162
6163        let workspace = multi_workspace
6164            .read_with(cx, |multi_workspace, _cx| {
6165                multi_workspace.workspace().clone()
6166            })
6167            .unwrap();
6168
6169        let cx = &mut VisualTestContext::from_window(multi_workspace.into(), cx);
6170
6171        let panel = workspace.update_in(cx, |workspace, window, cx| {
6172            let text_thread_store = cx.new(|cx| TextThreadStore::fake(project.clone(), cx));
6173            let panel =
6174                cx.new(|cx| AgentPanel::new(workspace, text_thread_store, None, window, cx));
6175            workspace.add_panel(panel.clone(), window, cx);
6176            panel
6177        });
6178
6179        cx.run_until_parked();
6180
6181        // Simulate worktree creation in progress and reset to Uninitialized
6182        panel.update_in(cx, |panel, window, cx| {
6183            panel.worktree_creation_status = Some(WorktreeCreationStatus::Creating);
6184            panel.active_view = ActiveView::Uninitialized;
6185            Panel::set_active(panel, true, window, cx);
6186            assert!(
6187                matches!(panel.active_view, ActiveView::Uninitialized),
6188                "set_active should not create a thread while worktree is being created"
6189            );
6190        });
6191
6192        // Clear the creation status and use open_external_thread_with_server
6193        // (which bypasses new_agent_thread) to verify the panel can transition
6194        // out of Uninitialized. We can't call set_active directly because
6195        // new_agent_thread requires full agent server infrastructure.
6196        panel.update_in(cx, |panel, window, cx| {
6197            panel.worktree_creation_status = None;
6198            panel.active_view = ActiveView::Uninitialized;
6199            panel.open_external_thread_with_server(
6200                Rc::new(StubAgentServer::default_response()),
6201                window,
6202                cx,
6203            );
6204        });
6205
6206        cx.run_until_parked();
6207
6208        panel.read_with(cx, |panel, _cx| {
6209            assert!(
6210                !matches!(panel.active_view, ActiveView::Uninitialized),
6211                "panel should transition out of Uninitialized once worktree creation is cleared"
6212            );
6213        });
6214    }
6215
6216    #[test]
6217    fn test_deserialize_agent_type_variants() {
6218        assert_eq!(
6219            serde_json::from_str::<AgentType>(r#""NativeAgent""#).unwrap(),
6220            AgentType::NativeAgent,
6221        );
6222        assert_eq!(
6223            serde_json::from_str::<AgentType>(r#""TextThread""#).unwrap(),
6224            AgentType::TextThread,
6225        );
6226        assert_eq!(
6227            serde_json::from_str::<AgentType>(r#"{"Custom":{"name":"my-agent"}}"#).unwrap(),
6228            AgentType::Custom {
6229                id: "my-agent".into(),
6230            },
6231        );
6232    }
6233
6234    #[gpui::test]
6235    async fn test_worktree_creation_preserves_selected_agent(cx: &mut TestAppContext) {
6236        init_test(cx);
6237
6238        let app_state = cx.update(|cx| {
6239            cx.update_flags(true, vec!["agent-v2".to_string()]);
6240            agent::ThreadStore::init_global(cx);
6241            language_model::LanguageModelRegistry::test(cx);
6242
6243            let app_state = workspace::AppState::test(cx);
6244            workspace::init(app_state.clone(), cx);
6245            app_state
6246        });
6247
6248        let fs = app_state.fs.as_fake();
6249        fs.insert_tree(
6250            "/project",
6251            json!({
6252                ".git": {},
6253                "src": {
6254                    "main.rs": "fn main() {}"
6255                }
6256            }),
6257        )
6258        .await;
6259        fs.set_branch_name(Path::new("/project/.git"), Some("main"));
6260
6261        let project = Project::test(app_state.fs.clone(), [Path::new("/project")], cx).await;
6262
6263        let multi_workspace =
6264            cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
6265
6266        let workspace = multi_workspace
6267            .read_with(cx, |multi_workspace, _cx| {
6268                multi_workspace.workspace().clone()
6269            })
6270            .unwrap();
6271
6272        workspace.update(cx, |workspace, _cx| {
6273            workspace.set_random_database_id();
6274        });
6275
6276        // Register a callback so new workspaces also get an AgentPanel.
6277        cx.update(|cx| {
6278            cx.observe_new(
6279                |workspace: &mut Workspace,
6280                 window: Option<&mut Window>,
6281                 cx: &mut Context<Workspace>| {
6282                    if let Some(window) = window {
6283                        let project = workspace.project().clone();
6284                        let text_thread_store =
6285                            cx.new(|cx| TextThreadStore::fake(project.clone(), cx));
6286                        let panel = cx.new(|cx| {
6287                            AgentPanel::new(workspace, text_thread_store, None, window, cx)
6288                        });
6289                        workspace.add_panel(panel, window, cx);
6290                    }
6291                },
6292            )
6293            .detach();
6294        });
6295
6296        let cx = &mut VisualTestContext::from_window(multi_workspace.into(), cx);
6297
6298        // Wait for the project to discover the git repository.
6299        cx.run_until_parked();
6300
6301        let panel = workspace.update_in(cx, |workspace, window, cx| {
6302            let text_thread_store = cx.new(|cx| TextThreadStore::fake(project.clone(), cx));
6303            let panel =
6304                cx.new(|cx| AgentPanel::new(workspace, text_thread_store, None, window, cx));
6305            workspace.add_panel(panel.clone(), window, cx);
6306            panel
6307        });
6308
6309        cx.run_until_parked();
6310
6311        // Open a thread (needed so there's an active thread view).
6312        panel.update_in(cx, |panel, window, cx| {
6313            panel.open_external_thread_with_server(
6314                Rc::new(StubAgentServer::default_response()),
6315                window,
6316                cx,
6317            );
6318        });
6319
6320        cx.run_until_parked();
6321
6322        // Set the selected agent to Codex (a custom agent) and start_thread_in
6323        // to NewWorktree. We do this AFTER opening the thread because
6324        // open_external_thread_with_server overrides selected_agent_type.
6325        panel.update_in(cx, |panel, window, cx| {
6326            panel.selected_agent_type = AgentType::Custom {
6327                id: CODEX_ID.into(),
6328            };
6329            panel.set_start_thread_in(&StartThreadIn::NewWorktree, window, cx);
6330        });
6331
6332        // Verify the panel has the Codex agent selected.
6333        panel.read_with(cx, |panel, _cx| {
6334            assert_eq!(
6335                panel.selected_agent_type,
6336                AgentType::Custom {
6337                    id: CODEX_ID.into()
6338                },
6339            );
6340        });
6341
6342        // Directly call handle_worktree_creation_requested, which is what
6343        // handle_first_send_requested does when start_thread_in == NewWorktree.
6344        let content = vec![acp::ContentBlock::Text(acp::TextContent::new(
6345            "Hello from test",
6346        ))];
6347        panel.update_in(cx, |panel, window, cx| {
6348            panel.handle_worktree_creation_requested(content, window, cx);
6349        });
6350
6351        // Let the async worktree creation + workspace setup complete.
6352        cx.run_until_parked();
6353
6354        // Find the new workspace's AgentPanel and verify it used the Codex agent.
6355        let found_codex = multi_workspace
6356            .read_with(cx, |multi_workspace, cx| {
6357                // There should be more than one workspace now (the original + the new worktree).
6358                assert!(
6359                    multi_workspace.workspaces().len() > 1,
6360                    "expected a new workspace to have been created, found {}",
6361                    multi_workspace.workspaces().len(),
6362                );
6363
6364                // Check the newest workspace's panel for the correct agent.
6365                let new_workspace = multi_workspace
6366                    .workspaces()
6367                    .iter()
6368                    .find(|ws| ws.entity_id() != workspace.entity_id())
6369                    .expect("should find the new workspace");
6370                let new_panel = new_workspace
6371                    .read(cx)
6372                    .panel::<AgentPanel>(cx)
6373                    .expect("new workspace should have an AgentPanel");
6374
6375                new_panel.read(cx).selected_agent_type.clone()
6376            })
6377            .unwrap();
6378
6379        assert_eq!(
6380            found_codex,
6381            AgentType::Custom {
6382                id: CODEX_ID.into()
6383            },
6384            "the new worktree workspace should use the same agent (Codex) that was selected in the original panel",
6385        );
6386    }
6387
6388    #[gpui::test]
6389    async fn test_work_dirs_update_when_worktrees_change(cx: &mut TestAppContext) {
6390        use crate::thread_metadata_store::ThreadMetadataStore;
6391
6392        init_test(cx);
6393        cx.update(|cx| {
6394            cx.update_flags(true, vec!["agent-v2".to_string()]);
6395            agent::ThreadStore::init_global(cx);
6396            language_model::LanguageModelRegistry::test(cx);
6397        });
6398
6399        // Set up a project with one worktree.
6400        let fs = FakeFs::new(cx.executor());
6401        fs.insert_tree("/project_a", json!({ "file.txt": "" }))
6402            .await;
6403        let project = Project::test(fs.clone(), [Path::new("/project_a")], cx).await;
6404
6405        let multi_workspace =
6406            cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
6407        let workspace = multi_workspace
6408            .read_with(cx, |mw, _cx| mw.workspace().clone())
6409            .unwrap();
6410        let mut cx = VisualTestContext::from_window(multi_workspace.into(), cx);
6411
6412        let panel = workspace.update_in(&mut cx, |workspace, window, cx| {
6413            let text_thread_store = cx.new(|cx| TextThreadStore::fake(project.clone(), cx));
6414            cx.new(|cx| AgentPanel::new(workspace, text_thread_store, None, window, cx))
6415        });
6416
6417        // Open thread A and send a message. With empty next_prompt_updates it
6418        // stays generating, so opening B will move A to background_threads.
6419        let connection_a = StubAgentConnection::new().with_agent_id("agent-a".into());
6420        open_thread_with_custom_connection(&panel, connection_a.clone(), &mut cx);
6421        send_message(&panel, &mut cx);
6422        let session_id_a = active_session_id(&panel, &cx);
6423
6424        // Open thread C — thread A (generating) moves to background.
6425        // Thread C completes immediately (idle), then opening B moves C to background too.
6426        let connection_c = StubAgentConnection::new().with_agent_id("agent-c".into());
6427        connection_c.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
6428            acp::ContentChunk::new("done".into()),
6429        )]);
6430        open_thread_with_custom_connection(&panel, connection_c.clone(), &mut cx);
6431        send_message(&panel, &mut cx);
6432        let session_id_c = active_session_id(&panel, &cx);
6433
6434        // Snapshot thread C's initial work_dirs before adding worktrees.
6435        let initial_c_paths = panel.read_with(&cx, |panel, cx| {
6436            let thread = panel.active_agent_thread(cx).unwrap();
6437            thread.read(cx).work_dirs().cloned().unwrap()
6438        });
6439
6440        // Open thread B — thread C (idle, non-loadable) is retained in background.
6441        let connection_b = StubAgentConnection::new().with_agent_id("agent-b".into());
6442        open_thread_with_custom_connection(&panel, connection_b.clone(), &mut cx);
6443        send_message(&panel, &mut cx);
6444        let session_id_b = active_session_id(&panel, &cx);
6445
6446        let metadata_store = cx.update(|_, cx| ThreadMetadataStore::global(cx));
6447
6448        panel.read_with(&cx, |panel, _cx| {
6449            assert!(
6450                panel.background_threads.contains_key(&session_id_a),
6451                "Thread A should be in background_threads"
6452            );
6453            assert!(
6454                panel.background_threads.contains_key(&session_id_c),
6455                "Thread C should be in background_threads"
6456            );
6457        });
6458
6459        // Verify initial work_dirs for thread B contain only /project_a.
6460        let initial_b_paths = panel.read_with(&cx, |panel, cx| {
6461            let thread = panel.active_agent_thread(cx).unwrap();
6462            thread.read(cx).work_dirs().cloned().unwrap()
6463        });
6464        assert_eq!(
6465            initial_b_paths.ordered_paths().collect::<Vec<_>>(),
6466            vec![&PathBuf::from("/project_a")],
6467            "Thread B should initially have only /project_a"
6468        );
6469
6470        // Now add a second worktree to the project.
6471        fs.insert_tree("/project_b", json!({ "other.txt": "" }))
6472            .await;
6473        let (new_tree, _) = project
6474            .update(&mut cx, |project, cx| {
6475                project.find_or_create_worktree("/project_b", true, cx)
6476            })
6477            .await
6478            .unwrap();
6479        cx.read(|cx| new_tree.read(cx).as_local().unwrap().scan_complete())
6480            .await;
6481        cx.run_until_parked();
6482
6483        // Verify thread B's (active) work_dirs now include both worktrees.
6484        let updated_b_paths = panel.read_with(&cx, |panel, cx| {
6485            let thread = panel.active_agent_thread(cx).unwrap();
6486            thread.read(cx).work_dirs().cloned().unwrap()
6487        });
6488        let mut b_paths_sorted = updated_b_paths.ordered_paths().cloned().collect::<Vec<_>>();
6489        b_paths_sorted.sort();
6490        assert_eq!(
6491            b_paths_sorted,
6492            vec![PathBuf::from("/project_a"), PathBuf::from("/project_b")],
6493            "Thread B work_dirs should include both worktrees after adding /project_b"
6494        );
6495
6496        // Verify thread A's (background) work_dirs are also updated.
6497        let updated_a_paths = panel.read_with(&cx, |panel, cx| {
6498            let bg_view = panel.background_threads.get(&session_id_a).unwrap();
6499            let root_thread = bg_view.read(cx).root_thread(cx).unwrap();
6500            root_thread
6501                .read(cx)
6502                .thread
6503                .read(cx)
6504                .work_dirs()
6505                .cloned()
6506                .unwrap()
6507        });
6508        let mut a_paths_sorted = updated_a_paths.ordered_paths().cloned().collect::<Vec<_>>();
6509        a_paths_sorted.sort();
6510        assert_eq!(
6511            a_paths_sorted,
6512            vec![PathBuf::from("/project_a"), PathBuf::from("/project_b")],
6513            "Thread A work_dirs should include both worktrees after adding /project_b"
6514        );
6515
6516        // Verify thread C  was NOT updated.
6517        let unchanged_c_paths = panel.read_with(&cx, |panel, cx| {
6518            let bg_view = panel.background_threads.get(&session_id_c).unwrap();
6519            let root_thread = bg_view.read(cx).root_thread(cx).unwrap();
6520            root_thread
6521                .read(cx)
6522                .thread
6523                .read(cx)
6524                .work_dirs()
6525                .cloned()
6526                .unwrap()
6527        });
6528        assert_eq!(
6529            unchanged_c_paths, initial_c_paths,
6530            "Thread C (idle background) work_dirs should not change when worktrees change"
6531        );
6532
6533        // Verify the metadata store reflects the new paths for running threads only.
6534        cx.run_until_parked();
6535        for (label, session_id) in [("thread B", &session_id_b), ("thread A", &session_id_a)] {
6536            let metadata_paths = metadata_store.read_with(&cx, |store, _cx| {
6537                let metadata = store
6538                    .entry(session_id)
6539                    .unwrap_or_else(|| panic!("{label} thread metadata should exist"));
6540                metadata.folder_paths.clone()
6541            });
6542            let mut sorted = metadata_paths.ordered_paths().cloned().collect::<Vec<_>>();
6543            sorted.sort();
6544            assert_eq!(
6545                sorted,
6546                vec![PathBuf::from("/project_a"), PathBuf::from("/project_b")],
6547                "{label} thread metadata folder_paths should include both worktrees"
6548            );
6549        }
6550
6551        // Now remove a worktree and verify work_dirs shrink.
6552        let worktree_b_id = new_tree.read_with(&cx, |tree, _| tree.id());
6553        project.update(&mut cx, |project, cx| {
6554            project.remove_worktree(worktree_b_id, cx);
6555        });
6556        cx.run_until_parked();
6557
6558        let after_remove_b = panel.read_with(&cx, |panel, cx| {
6559            let thread = panel.active_agent_thread(cx).unwrap();
6560            thread.read(cx).work_dirs().cloned().unwrap()
6561        });
6562        assert_eq!(
6563            after_remove_b.ordered_paths().collect::<Vec<_>>(),
6564            vec![&PathBuf::from("/project_a")],
6565            "Thread B work_dirs should revert to only /project_a after removing /project_b"
6566        );
6567
6568        let after_remove_a = panel.read_with(&cx, |panel, cx| {
6569            let bg_view = panel.background_threads.get(&session_id_a).unwrap();
6570            let root_thread = bg_view.read(cx).root_thread(cx).unwrap();
6571            root_thread
6572                .read(cx)
6573                .thread
6574                .read(cx)
6575                .work_dirs()
6576                .cloned()
6577                .unwrap()
6578        });
6579        assert_eq!(
6580            after_remove_a.ordered_paths().collect::<Vec<_>>(),
6581            vec![&PathBuf::from("/project_a")],
6582            "Thread A work_dirs should revert to only /project_a after removing /project_b"
6583        );
6584    }
6585}