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