agent_panel.rs

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