798 lines · 28.1 KB · Rust
RawDownload
mod agent_configuration;pub(crate) mod agent_connection_store;mod agent_diff;mod agent_model_selector;mod agent_panel;mod agent_registry_ui;mod branch_names;mod buffer_codegen;mod completion_provider;mod config_options;mod context;mod context_server_configuration;pub(crate) mod conversation_view;mod entry_view_state;mod external_source_prompt;mod favorite_models;mod inline_assistant;mod inline_prompt_editor;mod language_model_selector;mod mention_set;mod message_editor;mod mode_selector;mod model_selector;mod model_selector_popover;mod profile_selector;pub mod sidebar;mod slash_command;mod slash_command_picker;mod terminal_codegen;mod terminal_inline_assistant;#[cfg(any(test, feature = "test-support"))]pub mod test_support;mod text_thread_editor;mod text_thread_history;mod thread_history;mod thread_history_view;mod thread_metadata_store;mod threads_archive_view;mod ui; use std::rc::Rc;use std::sync::Arc; use agent_client_protocol as acp;use agent_settings::{AgentProfileId, AgentSettings};use assistant_slash_command::SlashCommandRegistry;use client::Client;use command_palette_hooks::CommandPaletteFilter;use feature_flags::{AgentV2FeatureFlag, FeatureFlagAppExt as _};use fs::Fs;use gpui::{Action, App, Context, Entity, SharedString, Window, actions};use language::{    LanguageRegistry,    language_settings::{AllLanguageSettings, EditPredictionProvider},};use language_model::{    ConfiguredModel, LanguageModelId, LanguageModelProviderId, LanguageModelRegistry,};use project::{AgentId, DisableAiSettings};use prompt_store::PromptBuilder;use schemars::JsonSchema;use serde::{Deserialize, Serialize};use settings::{LanguageModelSelection, Settings as _, SettingsStore};use std::any::TypeId;use workspace::Workspace; use crate::agent_configuration::{ConfigureContextServerModal, ManageProfilesModal};pub use crate::agent_panel::{    AgentPanel, AgentPanelEvent, ConcreteAssistantPanelDelegate, WorktreeCreationStatus,};use crate::agent_registry_ui::AgentRegistryPage;pub use crate::inline_assistant::InlineAssistant;pub use agent_diff::{AgentDiffPane, AgentDiffToolbar};pub(crate) use conversation_view::ConversationView;pub use external_source_prompt::ExternalSourcePrompt;pub(crate) use mode_selector::ModeSelector;pub(crate) use model_selector::ModelSelector;pub(crate) use model_selector_popover::ModelSelectorPopover;pub use text_thread_editor::{AgentPanelDelegate, TextThreadEditor};pub(crate) use thread_history::ThreadHistory;pub(crate) use thread_history_view::*;use zed_actions; actions!(    agent,    [        /// Creates a new text-based conversation thread.        NewTextThread,        /// Toggles the menu to create new agent threads.        ToggleNewThreadMenu,        /// Cycles through the options for where new threads start (current project or new worktree).        CycleStartThreadIn,        /// Toggles the navigation menu for switching between threads and views.        ToggleNavigationMenu,        /// Toggles the options menu for agent settings and preferences.        ToggleOptionsMenu,        /// Toggles the profile or mode selector for switching between agent profiles.        ToggleProfileSelector,        /// Cycles through available session modes.        CycleModeSelector,        /// Cycles through favorited models in the ACP model selector.        CycleFavoriteModels,        /// Expands the message editor to full size.        ExpandMessageEditor,        /// Removes all thread history.        RemoveHistory,        /// Opens the conversation history view.        OpenHistory,        /// Adds a context server to the configuration.        AddContextServer,        /// Removes the currently selected thread.        RemoveSelectedThread,        /// Starts a chat conversation with follow-up enabled.        ChatWithFollow,        /// Cycles to the next inline assist suggestion.        CycleNextInlineAssist,        /// Cycles to the previous inline assist suggestion.        CyclePreviousInlineAssist,        /// Moves focus up in the interface.        FocusUp,        /// Moves focus down in the interface.        FocusDown,        /// Moves focus left in the interface.        FocusLeft,        /// Moves focus right in the interface.        FocusRight,        /// Opens the active thread as a markdown file.        OpenActiveThreadAsMarkdown,        /// Opens the agent diff view to review changes.        OpenAgentDiff,        /// Copies the current thread to the clipboard as JSON for debugging.        CopyThreadToClipboard,        /// Loads a thread from the clipboard JSON for debugging.        LoadThreadFromClipboard,        /// Keeps the current suggestion or change.        Keep,        /// Rejects the current suggestion or change.        Reject,        /// Rejects all suggestions or changes.        RejectAll,        /// Undoes the most recent reject operation, restoring the rejected changes.        UndoLastReject,        /// Keeps all suggestions or changes.        KeepAll,        /// Allow this operation only this time.        AllowOnce,        /// Allow this operation and remember the choice.        AllowAlways,        /// Reject this operation only this time.        RejectOnce,        /// Follows the agent's suggestions.        Follow,        /// Resets the trial upsell notification.        ResetTrialUpsell,        /// Resets the trial end upsell notification.        ResetTrialEndUpsell,        /// Opens the "Add Context" menu in the message editor.        OpenAddContextMenu,        /// Continues the current thread.        ContinueThread,        /// Interrupts the current generation and sends the message immediately.        SendImmediately,        /// Sends the next queued message immediately.        SendNextQueuedMessage,        /// Removes the first message from the queue (the next one to be sent).        RemoveFirstQueuedMessage,        /// Edits the first message in the queue (the next one to be sent).        EditFirstQueuedMessage,        /// Clears all messages from the queue.        ClearMessageQueue,        /// Opens the permission granularity dropdown for the current tool call.        OpenPermissionDropdown,        /// Toggles thinking mode for models that support extended thinking.        ToggleThinkingMode,        /// Cycles through available thinking effort levels for the current model.        CycleThinkingEffort,        /// Toggles the thinking effort selector menu open or closed.        ToggleThinkingEffortMenu,        /// Toggles fast mode for models that support it.        ToggleFastMode,    ]); /// Action to authorize a tool call with a specific permission option./// This is used by the permission granularity dropdown to authorize tool calls.#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]#[action(namespace = agent)]#[serde(deny_unknown_fields)]pub struct AuthorizeToolCall {    /// The tool call ID to authorize.    pub tool_call_id: String,    /// The permission option ID to use.    pub option_id: String,    /// The kind of permission option (serialized as string).    pub option_kind: String,} /// Creates a new conversation thread, optionally based on an existing thread.#[derive(Default, Clone, PartialEq, Deserialize, JsonSchema, Action)]#[action(namespace = agent)]#[serde(deny_unknown_fields)]pub struct NewThread; /// Creates a new external agent conversation thread.#[derive(Default, Clone, PartialEq, Deserialize, JsonSchema, Action)]#[action(namespace = agent)]#[serde(deny_unknown_fields)]pub struct NewExternalAgentThread {    /// Which agent to use for the conversation.    agent: Option<Agent>,} #[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]#[action(namespace = agent)]#[serde(deny_unknown_fields)]pub struct NewNativeAgentThreadFromSummary {    from_session_id: agent_client_protocol::SessionId,} // TODO unify this with AgentType#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, JsonSchema)]#[serde(rename_all = "snake_case")]pub enum Agent {    NativeAgent,    Custom {        #[serde(rename = "name")]        id: AgentId,    },} // Custom impl handles legacy variant names from before the built-in agents were moved to// the registry: "claude_code" -> Custom { name: "claude-acp" }, "codex" -> Custom { name:// "codex-acp" }, "gemini" -> Custom { name: "gemini" }.// Can be removed at some point in the future and go back to #[derive(Deserialize)].impl<'de> serde::Deserialize<'de> for Agent {    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>    where        D: serde::Deserializer<'de>,    {        use project::agent_server_store::{CLAUDE_AGENT_ID, CODEX_ID, GEMINI_ID};         let value = serde_json::Value::deserialize(deserializer)?;         if let Some(s) = value.as_str() {            return match s {                "native_agent" => Ok(Self::NativeAgent),                "claude_code" | "claude_agent" => Ok(Self::Custom {                    id: CLAUDE_AGENT_ID.into(),                }),                "codex" => Ok(Self::Custom {                    id: CODEX_ID.into(),                }),                "gemini" => Ok(Self::Custom {                    id: GEMINI_ID.into(),                }),                other => Err(serde::de::Error::unknown_variant(                    other,                    &[                        "native_agent",                        "custom",                        "claude_agent",                        "claude_code",                        "codex",                        "gemini",                    ],                )),            };        }         if let Some(obj) = value.as_object() {            if let Some(inner) = obj.get("custom") {                #[derive(serde::Deserialize)]                struct CustomFields {                    name: SharedString,                }                let fields: CustomFields =                    serde_json::from_value(inner.clone()).map_err(serde::de::Error::custom)?;                return Ok(Self::Custom {                    id: AgentId::new(fields.name),                });            }        }         Err(serde::de::Error::custom(            "expected a string variant or {\"custom\": {\"name\": ...}}",        ))    }} impl Agent {    pub fn server(        &self,        fs: Arc<dyn fs::Fs>,        thread_store: Entity<agent::ThreadStore>,    ) -> Rc<dyn agent_servers::AgentServer> {        match self {            Self::NativeAgent => Rc::new(agent::NativeAgentServer::new(fs, thread_store)),            Self::Custom { id: name } => {                Rc::new(agent_servers::CustomAgentServer::new(name.clone()))            }        }    }} /// Sets where new threads will run.#[derive(    Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema, Action,)]#[action(namespace = agent)]#[serde(rename_all = "snake_case", tag = "kind")]pub enum StartThreadIn {    #[default]    LocalProject,    NewWorktree,} /// Content to initialize new external agent with.pub enum AgentInitialContent {    ThreadSummary {        session_id: acp::SessionId,        title: Option<SharedString>,    },    ContentBlock {        blocks: Vec<agent_client_protocol::ContentBlock>,        auto_submit: bool,    },    FromExternalSource(ExternalSourcePrompt),} impl From<ExternalSourcePrompt> for AgentInitialContent {    fn from(prompt: ExternalSourcePrompt) -> Self {        Self::FromExternalSource(prompt)    }} /// Opens the profile management interface for configuring agent tools and settings.#[derive(PartialEq, Clone, Default, Debug, Deserialize, JsonSchema, Action)]#[action(namespace = agent)]#[serde(deny_unknown_fields)]pub struct ManageProfiles {    #[serde(default)]    pub customize_tools: Option<AgentProfileId>,} impl ManageProfiles {    pub fn customize_tools(profile_id: AgentProfileId) -> Self {        Self {            customize_tools: Some(profile_id),        }    }} #[derive(Clone)]pub(crate) enum ModelUsageContext {    InlineAssistant,} impl ModelUsageContext {    pub fn configured_model(&self, cx: &App) -> Option<ConfiguredModel> {        match self {            Self::InlineAssistant => {                LanguageModelRegistry::read_global(cx).inline_assistant_model()            }        }    }} /// Initializes the `agent` crate.pub fn init(    fs: Arc<dyn Fs>,    client: Arc<Client>,    prompt_builder: Arc<PromptBuilder>,    language_registry: Arc<LanguageRegistry>,    is_eval: bool,    cx: &mut App,) {    agent::ThreadStore::init_global(cx);    assistant_text_thread::init(client, cx);    rules_library::init(cx);    if !is_eval {        // Initializing the language model from the user settings messes with the eval, so we only initialize them when        // we're not running inside of the eval.        init_language_model_settings(cx);    }    assistant_slash_command::init(cx);    agent_panel::init(cx);    context_server_configuration::init(language_registry.clone(), fs.clone(), cx);    TextThreadEditor::init(cx);    thread_metadata_store::init(cx);     register_slash_commands(cx);    inline_assistant::init(fs.clone(), prompt_builder.clone(), cx);    terminal_inline_assistant::init(fs.clone(), prompt_builder, cx);    cx.observe_new(move |workspace, window, cx| {        ConfigureContextServerModal::register(workspace, language_registry.clone(), window, cx)    })    .detach();    cx.observe_new(|workspace: &mut Workspace, _window, _cx| {        workspace.register_action(            move |workspace: &mut Workspace,                  _: &zed_actions::AcpRegistry,                  window: &mut Window,                  cx: &mut Context<Workspace>| {                let existing = workspace                    .active_pane()                    .read(cx)                    .items()                    .find_map(|item| item.downcast::<AgentRegistryPage>());                 if let Some(existing) = existing {                    existing.update(cx, |_, cx| {                        project::AgentRegistryStore::global(cx)                            .update(cx, |store, cx| store.refresh(cx));                    });                    workspace.activate_item(&existing, true, true, window, cx);                } else {                    let registry_page = AgentRegistryPage::new(workspace, window, cx);                    workspace.add_item_to_active_pane(                        Box::new(registry_page),                        None,                        true,                        window,                        cx,                    );                }            },        );    })    .detach();    cx.observe_new(ManageProfilesModal::register).detach();     // Update command palette filter based on AI settings    update_command_palette_filter(cx);     // Watch for settings changes    cx.observe_global::<SettingsStore>(|app_cx| {        // When settings change, update the command palette filter        update_command_palette_filter(app_cx);    })    .detach();     cx.on_flags_ready(|_, cx| {        update_command_palette_filter(cx);    })    .detach();} fn update_command_palette_filter(cx: &mut App) {    let disable_ai = DisableAiSettings::get_global(cx).disable_ai;    let agent_enabled = AgentSettings::get_global(cx).enabled;    let agent_v2_enabled = cx.has_flag::<AgentV2FeatureFlag>();    let edit_prediction_provider = AllLanguageSettings::get_global(cx)        .edit_predictions        .provider;     CommandPaletteFilter::update_global(cx, |filter, _| {        use editor::actions::{            AcceptEditPrediction, AcceptNextLineEditPrediction, AcceptNextWordEditPrediction,            NextEditPrediction, PreviousEditPrediction, ShowEditPrediction, ToggleEditPrediction,        };        let edit_prediction_actions = [            TypeId::of::<AcceptEditPrediction>(),            TypeId::of::<AcceptNextWordEditPrediction>(),            TypeId::of::<AcceptNextLineEditPrediction>(),            TypeId::of::<AcceptEditPrediction>(),            TypeId::of::<ShowEditPrediction>(),            TypeId::of::<NextEditPrediction>(),            TypeId::of::<PreviousEditPrediction>(),            TypeId::of::<ToggleEditPrediction>(),        ];         if disable_ai {            filter.hide_namespace("agent");            filter.hide_namespace("agents");            filter.hide_namespace("assistant");            filter.hide_namespace("copilot");            filter.hide_namespace("zed_predict_onboarding");            filter.hide_namespace("edit_prediction");             filter.hide_action_types(&edit_prediction_actions);            filter.hide_action_types(&[TypeId::of::<zed_actions::OpenZedPredictOnboarding>()]);        } else {            if agent_enabled {                filter.show_namespace("agent");                filter.show_namespace("agents");                filter.show_namespace("assistant");            } else {                filter.hide_namespace("agent");                filter.hide_namespace("agents");                filter.hide_namespace("assistant");            }             match edit_prediction_provider {                EditPredictionProvider::None => {                    filter.hide_namespace("edit_prediction");                    filter.hide_namespace("copilot");                    filter.hide_action_types(&edit_prediction_actions);                }                EditPredictionProvider::Copilot => {                    filter.show_namespace("edit_prediction");

Lines 1–500 of 798.