6328 lines · 239.4 KB · Rust
RawDownload
use std::{    ops::Range,    path::{Path, PathBuf},    rc::Rc,    sync::{        Arc,        atomic::{AtomicBool, Ordering},    },    time::Duration,}; use acp_thread::{AcpThread, MentionUri, ThreadStatus};use agent::{ContextServerRegistry, SharedThread, ThreadStore};use agent_client_protocol as acp;use agent_servers::AgentServer;use collections::HashSet;use db::kvp::{Dismissable, KEY_VALUE_STORE};use itertools::Itertools;use project::{    AgentId,    agent_server_store::{CLAUDE_AGENT_ID, CODEX_ID, GEMINI_ID},};use serde::{Deserialize, Serialize};use settings::{LanguageModelProviderSetting, LanguageModelSelection}; use feature_flags::{AgentV2FeatureFlag, FeatureFlagAppExt as _};use zed_actions::agent::{    ConflictContent, OpenClaudeAgentOnboardingModal, ReauthenticateAgent,    ResolveConflictedFilesWithAgent, ResolveConflictsWithAgent, ReviewBranchDiff,}; use crate::ui::{AcpOnboardingModal, ClaudeCodeOnboardingModal, HoldForDefault};use crate::{    AddContextServer, AgentDiffPane, ConversationView, CopyThreadToClipboard, CycleStartThreadIn,    Follow, InlineAssistant, LoadThreadFromClipboard, NewTextThread, NewThread,    OpenActiveThreadAsMarkdown, OpenAgentDiff, OpenHistory, ResetTrialEndUpsell, ResetTrialUpsell,    StartThreadIn, ToggleNavigationMenu, ToggleNewThreadMenu, ToggleOptionsMenu,    agent_configuration::{AgentConfiguration, AssistantConfigurationEvent},    conversation_view::{AcpThreadViewEvent, ThreadView},    slash_command::SlashCommandCompletionProvider,    text_thread_editor::{AgentPanelDelegate, TextThreadEditor, make_lsp_adapter_delegate},    ui::EndTrialUpsell,};use crate::{    Agent, AgentInitialContent, ExternalSourcePrompt, NewExternalAgentThread,    NewNativeAgentThreadFromSummary,};use crate::{    ExpandMessageEditor, ThreadHistoryView,    text_thread_history::{TextThreadHistory, TextThreadHistoryEvent},};use crate::{ManageProfiles, ThreadHistoryViewEvent};use crate::{ThreadHistory, agent_connection_store::AgentConnectionStore};use agent_settings::AgentSettings;use ai_onboarding::AgentPanelOnboarding;use anyhow::{Context as _, Result, anyhow};use assistant_slash_command::SlashCommandWorkingSet;use assistant_text_thread::{TextThread, TextThreadEvent, TextThreadSummary};use client::UserStore;use cloud_api_types::Plan;use collections::HashMap;use editor::{Anchor, AnchorRangeExt as _, Editor, EditorEvent, MultiBuffer};use extension::ExtensionEvents;use extension_host::ExtensionStore;use fs::Fs;use git::repository::validate_worktree_directory;use gpui::{    Action, Animation, AnimationExt, AnyElement, AnyView, App, AsyncWindowContext, ClipboardItem,    Corner, DismissEvent, DragMoveEvent, Entity, EventEmitter, ExternalPaths, FocusHandle,    Focusable, KeyContext, MouseButton, Pixels, Subscription, Task, UpdateGlobal, WeakEntity,    deferred, prelude::*, pulsating_between,};use language::LanguageRegistry;use language_model::{ConfigurationError, LanguageModelRegistry};use project::project_settings::ProjectSettings;use project::{Project, ProjectPath, Worktree};use prompt_store::{PromptBuilder, PromptStore, UserPromptId};use rules_library::{RulesLibrary, open_rules_library};use search::{BufferSearchBar, buffer_search};use settings::{Settings, update_settings_file};use theme::ThemeSettings;use ui::{    Button, Callout, ContextMenu, ContextMenuEntry, DocumentationSide, Indicator, KeyBinding,    PopoverMenu, PopoverMenuHandle, SpinnerLabel, Tab, Tooltip, prelude::*, utils::WithRemSize,};use util::{ResultExt as _, debug_panic};use workspace::{    CollaboratorId, DraggedSelection, DraggedSidebar, DraggedTab, FocusWorkspaceSidebar,    MultiWorkspace, OpenResult, PathList, SIDEBAR_RESIZE_HANDLE_SIZE, SerializedPathList,    ToggleWorkspaceSidebar, ToggleZoom, ToolbarItemView, Workspace, WorkspaceId,    dock::{DockPosition, Panel, PanelEvent},    multi_workspace_enabled,};use zed_actions::{    DecreaseBufferFontSize, IncreaseBufferFontSize, ResetBufferFontSize,    agent::{OpenAcpOnboardingModal, OpenSettings, ResetAgentZoom, ResetOnboarding},    assistant::{OpenRulesLibrary, Toggle, ToggleFocus},}; const AGENT_PANEL_KEY: &str = "agent_panel";const RECENTLY_UPDATED_MENU_LIMIT: usize = 6;const DEFAULT_THREAD_TITLE: &str = "New Thread"; #[derive(Default)]struct SidebarsByWindow(    collections::HashMap<gpui::WindowId, gpui::WeakEntity<crate::sidebar::Sidebar>>,); impl gpui::Global for SidebarsByWindow {} pub(crate) fn sidebar_is_open(window: &Window, cx: &App) -> bool {    if !multi_workspace_enabled(cx) {        return false;    }    let window_id = window.window_handle().window_id();    cx.try_global::<SidebarsByWindow>()        .and_then(|sidebars| sidebars.0.get(&window_id)?.upgrade())        .is_some_and(|sidebar| sidebar.read(cx).is_open())} fn find_or_create_sidebar_for_window(    window: &mut Window,    cx: &mut App,) -> Option<Entity<crate::sidebar::Sidebar>> {    let window_id = window.window_handle().window_id();    let multi_workspace = window.root::<MultiWorkspace>().flatten()?;     if !cx.has_global::<SidebarsByWindow>() {        cx.set_global(SidebarsByWindow::default());    }     cx.global_mut::<SidebarsByWindow>()        .0        .retain(|_, weak| weak.upgrade().is_some());     let existing = cx        .global::<SidebarsByWindow>()        .0        .get(&window_id)        .and_then(|weak| weak.upgrade());     if let Some(sidebar) = existing {        return Some(sidebar);    }     let sidebar = cx.new(|cx| crate::sidebar::Sidebar::new(multi_workspace, window, cx));    cx.global_mut::<SidebarsByWindow>()        .0        .insert(window_id, sidebar.downgrade());    Some(sidebar)} fn read_serialized_panel(workspace_id: workspace::WorkspaceId) -> Option<SerializedAgentPanel> {    let scope = KEY_VALUE_STORE.scoped(AGENT_PANEL_KEY);    let key = i64::from(workspace_id).to_string();    scope        .read(&key)        .log_err()        .flatten()        .and_then(|json| serde_json::from_str::<SerializedAgentPanel>(&json).log_err())} async fn save_serialized_panel(    workspace_id: workspace::WorkspaceId,    panel: SerializedAgentPanel,) -> Result<()> {    let scope = KEY_VALUE_STORE.scoped(AGENT_PANEL_KEY);    let key = i64::from(workspace_id).to_string();    scope.write(key, serde_json::to_string(&panel)?).await?;    Ok(())} /// Migration: reads the original single-panel format stored under the/// `"agent_panel"` KVP key before per-workspace keying was introduced.fn read_legacy_serialized_panel() -> Option<SerializedAgentPanel> {    KEY_VALUE_STORE        .read_kvp(AGENT_PANEL_KEY)        .log_err()        .flatten()        .and_then(|json| serde_json::from_str::<SerializedAgentPanel>(&json).log_err())} #[derive(Serialize, Deserialize, Debug)]struct SerializedAgentPanel {    width: Option<Pixels>,    selected_agent: Option<AgentType>,    #[serde(default)]    last_active_thread: Option<SerializedActiveThread>,    #[serde(default)]    start_thread_in: Option<StartThreadIn>,} #[derive(Serialize, Deserialize, Debug)]struct SerializedActiveThread {    session_id: String,    agent_type: AgentType,    title: Option<String>,    work_dirs: Option<SerializedPathList>,} pub fn init(cx: &mut App) {    cx.observe_new(        |workspace: &mut Workspace, _window, _cx: &mut Context<Workspace>| {            workspace                .register_action(|workspace, action: &NewThread, window, cx| {                    if let Some(panel) = workspace.panel::<AgentPanel>(cx) {                        panel.update(cx, |panel, cx| panel.new_thread(action, window, cx));                        workspace.focus_panel::<AgentPanel>(window, cx);                    }                })                .register_action(                    |workspace, action: &NewNativeAgentThreadFromSummary, window, cx| {                        if let Some(panel) = workspace.panel::<AgentPanel>(cx) {                            panel.update(cx, |panel, cx| {                                panel.new_native_agent_thread_from_summary(action, window, cx)                            });                            workspace.focus_panel::<AgentPanel>(window, cx);                        }                    },                )                .register_action(|workspace, _: &ExpandMessageEditor, window, cx| {                    if let Some(panel) = workspace.panel::<AgentPanel>(cx) {                        workspace.focus_panel::<AgentPanel>(window, cx);                        panel.update(cx, |panel, cx| panel.expand_message_editor(window, cx));                    }                })                .register_action(|workspace, _: &OpenHistory, window, cx| {                    if let Some(panel) = workspace.panel::<AgentPanel>(cx) {                        workspace.focus_panel::<AgentPanel>(window, cx);                        panel.update(cx, |panel, cx| panel.open_history(window, cx));                    }                })                .register_action(|workspace, _: &OpenSettings, window, cx| {                    if let Some(panel) = workspace.panel::<AgentPanel>(cx) {                        workspace.focus_panel::<AgentPanel>(window, cx);                        panel.update(cx, |panel, cx| panel.open_configuration(window, cx));                    }                })                .register_action(|workspace, _: &NewTextThread, window, cx| {                    if let Some(panel) = workspace.panel::<AgentPanel>(cx) {                        workspace.focus_panel::<AgentPanel>(window, cx);                        panel.update(cx, |panel, cx| {                            panel.new_text_thread(window, cx);                        });                    }                })                .register_action(|workspace, action: &NewExternalAgentThread, window, cx| {                    if let Some(panel) = workspace.panel::<AgentPanel>(cx) {                        workspace.focus_panel::<AgentPanel>(window, cx);                        panel.update(cx, |panel, cx| {                            panel.external_thread(                                action.agent.clone(),                                None,                                None,                                None,                                None,                                true,                                window,                                cx,                            )                        });                    }                })                .register_action(|workspace, action: &OpenRulesLibrary, window, cx| {                    if let Some(panel) = workspace.panel::<AgentPanel>(cx) {                        workspace.focus_panel::<AgentPanel>(window, cx);                        panel.update(cx, |panel, cx| {                            panel.deploy_rules_library(action, window, cx)                        });                    }                })                .register_action(|workspace, _: &Follow, window, cx| {                    workspace.follow(CollaboratorId::Agent, window, cx);                })                .register_action(|workspace, _: &OpenAgentDiff, window, cx| {                    let thread = workspace                        .panel::<AgentPanel>(cx)                        .and_then(|panel| panel.read(cx).active_conversation().cloned())                        .and_then(|conversation| {                            conversation                                .read(cx)                                .active_thread()                                .map(|r| r.read(cx).thread.clone())                        });                     if let Some(thread) = thread {                        AgentDiffPane::deploy_in_workspace(thread, workspace, window, cx);                    }                })                .register_action(|workspace, _: &ToggleNavigationMenu, window, cx| {                    if let Some(panel) = workspace.panel::<AgentPanel>(cx) {                        workspace.focus_panel::<AgentPanel>(window, cx);                        panel.update(cx, |panel, cx| {                            panel.toggle_navigation_menu(&ToggleNavigationMenu, window, cx);                        });                    }                })                .register_action(|workspace, _: &ToggleOptionsMenu, window, cx| {                    if let Some(panel) = workspace.panel::<AgentPanel>(cx) {                        workspace.focus_panel::<AgentPanel>(window, cx);                        panel.update(cx, |panel, cx| {                            panel.toggle_options_menu(&ToggleOptionsMenu, window, cx);                        });                    }                })                .register_action(|workspace, _: &ToggleNewThreadMenu, window, cx| {                    if let Some(panel) = workspace.panel::<AgentPanel>(cx) {                        workspace.focus_panel::<AgentPanel>(window, cx);                        panel.update(cx, |panel, cx| {                            panel.toggle_new_thread_menu(&ToggleNewThreadMenu, window, cx);                        });                    }                })                .register_action(|workspace, _: &OpenAcpOnboardingModal, window, cx| {                    AcpOnboardingModal::toggle(workspace, window, cx)                })                .register_action(                    |workspace, _: &OpenClaudeAgentOnboardingModal, window, cx| {                        ClaudeCodeOnboardingModal::toggle(workspace, window, cx)                    },                )                .register_action(|_workspace, _: &ResetOnboarding, window, cx| {                    window.dispatch_action(workspace::RestoreBanner.boxed_clone(), cx);                    window.refresh();                })                .register_action(|workspace, _: &ResetTrialUpsell, _window, cx| {                    if let Some(panel) = workspace.panel::<AgentPanel>(cx) {                        panel.update(cx, |panel, _| {                            panel                                .on_boarding_upsell_dismissed                                .store(false, Ordering::Release);                        });                    }                    OnboardingUpsell::set_dismissed(false, cx);                })                .register_action(|_workspace, _: &ResetTrialEndUpsell, _window, cx| {                    TrialEndUpsell::set_dismissed(false, cx);                })                .register_action(|workspace, _: &ResetAgentZoom, window, cx| {                    if let Some(panel) = workspace.panel::<AgentPanel>(cx) {                        panel.update(cx, |panel, cx| {                            panel.reset_agent_zoom(window, cx);                        });                    }                })                .register_action(|workspace, _: &CopyThreadToClipboard, window, cx| {                    if let Some(panel) = workspace.panel::<AgentPanel>(cx) {                        panel.update(cx, |panel, cx| {                            panel.copy_thread_to_clipboard(window, cx);                        });                    }                })                .register_action(|workspace, _: &LoadThreadFromClipboard, window, cx| {                    if let Some(panel) = workspace.panel::<AgentPanel>(cx) {                        workspace.focus_panel::<AgentPanel>(window, cx);                        panel.update(cx, |panel, cx| {                            panel.load_thread_from_clipboard(window, cx);                        });                    }                })                .register_action(|workspace, action: &ReviewBranchDiff, window, cx| {                    let Some(panel) = workspace.panel::<AgentPanel>(cx) else {                        return;                    };                     let mention_uri = MentionUri::GitDiff {                        base_ref: action.base_ref.to_string(),                    };                    let diff_uri = mention_uri.to_uri().to_string();                     let content_blocks = vec![                        acp::ContentBlock::Text(acp::TextContent::new(                            "Please review this branch diff carefully. Point out any issues, \                             potential bugs, or improvement opportunities you find.\n\n"                                .to_string(),                        )),                        acp::ContentBlock::Resource(acp::EmbeddedResource::new(                            acp::EmbeddedResourceResource::TextResourceContents(                                acp::TextResourceContents::new(                                    action.diff_text.to_string(),                                    diff_uri,                                ),                            ),                        )),                    ];                     workspace.focus_panel::<AgentPanel>(window, cx);                     panel.update(cx, |panel, cx| {                        panel.external_thread(                            None,                            None,                            None,                            None,                            Some(AgentInitialContent::ContentBlock {                                blocks: content_blocks,                                auto_submit: true,                            }),                            true,                            window,                            cx,                        );                    });                })                .register_action(                    |workspace, action: &ResolveConflictsWithAgent, window, cx| {                        let Some(panel) = workspace.panel::<AgentPanel>(cx) else {                            return;                        };                         let content_blocks = build_conflict_resolution_prompt(&action.conflicts);                         workspace.focus_panel::<AgentPanel>(window, cx);                         panel.update(cx, |panel, cx| {                            panel.external_thread(                                None,                                None,                                None,                                None,                                Some(AgentInitialContent::ContentBlock {                                    blocks: content_blocks,                                    auto_submit: true,                                }),                                true,                                window,                                cx,                            );                        });                    },                )                .register_action(                    |workspace, action: &ResolveConflictedFilesWithAgent, window, cx| {                        let Some(panel) = workspace.panel::<AgentPanel>(cx) else {                            return;                        };                         let content_blocks =                            build_conflicted_files_resolution_prompt(&action.conflicted_file_paths);                         workspace.focus_panel::<AgentPanel>(window, cx);                         panel.update(cx, |panel, cx| {                            panel.external_thread(                                None,                                None,                                None,                                None,                                Some(AgentInitialContent::ContentBlock {                                    blocks: content_blocks,                                    auto_submit: true,                                }),                                true,                                window,                                cx,                            );                        });                    },                )                .register_action(|workspace, action: &StartThreadIn, _window, cx| {                    if let Some(panel) = workspace.panel::<AgentPanel>(cx) {                        panel.update(cx, |panel, cx| {                            panel.set_start_thread_in(action, cx);                        });                    }                })                .register_action(|workspace, _: &CycleStartThreadIn, _window, cx| {                    if let Some(panel) = workspace.panel::<AgentPanel>(cx) {                        panel.update(cx, |panel, cx| {                            panel.cycle_start_thread_in(cx);                        });                    }                })                .register_action(|workspace, _: &ToggleWorkspaceSidebar, window, cx| {                    if !multi_workspace_enabled(cx) {                        return;                    }                    if let Some(panel) = workspace.panel::<AgentPanel>(cx) {                        if let Some(sidebar) = panel.read(cx).sidebar.clone() {                            let was_open = sidebar.read(cx).is_open();                            sidebar.update(cx, |sidebar, cx| {                                sidebar.toggle(window, cx);                            });                            // When closing the sidebar, restore focus to the active pane                            // to avoid "zombie focus" on the now-hidden sidebar elements                            if was_open {                                let active_pane = workspace.active_pane().clone();                                let pane_focus = active_pane.read(cx).focus_handle(cx);                                window.focus(&pane_focus, cx);                            }                        }                    }                })                .register_action(|workspace, _: &FocusWorkspaceSidebar, window, cx| {                    if !multi_workspace_enabled(cx) {                        return;                    }                    if let Some(panel) = workspace.panel::<AgentPanel>(cx) {                        if let Some(sidebar) = panel.read(cx).sidebar.clone() {                            sidebar.update(cx, |sidebar, cx| {

Lines 1–500 of 6328.

Keyboard shortcuts

General

Show keyboard shortcuts
?
Focus the current search
/

Issues and pull requests

Open filters
f

Issues, pull requests and Inbox

Select next item
j↓
Select previous item
k↑
Open selected item
Enter
Dismiss filters or clear selection
Esc

Repository code

Go to file
t