Skip to content

armgit / zed

Public Imported from GitHub
0

Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.

Refactor agent settings UI code (#60274)

Bennet Bo Fenner4ff55d09e5cc
diff --git a/crates/acp_thread/src/connection.rs b/crates/acp_thread/src/connection.rs
index eaf51978b5d..5f0cf69890d 100644
--- a/crates/acp_thread/src/connection.rs
+++ b/crates/acp_thread/src/connection.rs
@@ -4,7 +4,7 @@ use anyhow::Result;
use chrono::{DateTime, Utc};
use collections::{HashMap, HashSet, IndexMap};
use gpui::{Entity, SharedString, Task};
-use language_model::{DisabledReason, LanguageModelProviderId};
+use language_model::DisabledReason;
use project::{AgentId, Project};
use serde::{Deserialize, Serialize};
use std::{any::Any, error::Error, fmt, path::PathBuf, rc::Rc};
@@ -421,26 +421,17 @@ impl dyn AgentSessionList {
#[derive(Debug)]
pub struct AuthRequired {
pub description: Option<String>,
- pub provider_id: Option<LanguageModelProviderId>,
}
impl AuthRequired {
pub fn new() -> Self {
- Self {
- description: None,
- provider_id: None,
- }
+ Self { description: None }
}
pub fn with_description(mut self, description: String) -> Self {
self.description = Some(description);
self
}
-
- pub fn with_language_model_provider(mut self, provider_id: LanguageModelProviderId) -> Self {
- self.provider_id = Some(provider_id);
- self
- }
}
impl Error for AuthRequired {}
diff --git a/crates/agent_ui/src/conversation_view.rs b/crates/agent_ui/src/conversation_view.rs
index 350d9c2f912..65632e9406b 100644
--- a/crates/agent_ui/src/conversation_view.rs
+++ b/crates/agent_ui/src/conversation_view.rs
@@ -28,14 +28,14 @@ use file_icons::FileIcons;
use fs::Fs;
use futures::FutureExt as _;
use gpui::{
- Action, Animation, AnimationExt, AnyView, App, ClickEvent, ClipboardItem, CursorStyle,
- ElementId, Empty, Entity, EventEmitter, FocusHandle, Focusable, Hsla, ListOffset, ListState,
- ObjectFit, PlatformDisplay, ScrollHandle, SharedString, StyledText, Subscription, Task,
- TextRun, TextStyle, WeakEntity, Window, WindowHandle, div, ease_in_out, img, linear_color_stop,
+ Action, Animation, AnimationExt, App, ClickEvent, ClipboardItem, CursorStyle, ElementId, Empty,
+ Entity, EventEmitter, FocusHandle, Focusable, Hsla, ListOffset, ListState, ObjectFit,
+ PlatformDisplay, ScrollHandle, SharedString, StyledText, Subscription, Task, TextRun,
+ TextStyle, WeakEntity, Window, WindowHandle, div, ease_in_out, img, linear_color_stop,
linear_gradient, list, pulsating_between,
};
use language::{Buffer, Language, Rope};
-use language_model::{LanguageModelCompletionError, LanguageModelRegistry};
+use language_model::LanguageModelCompletionError;
use markdown::{
CodeBlockRenderer, CopyButtonVisibility, Markdown, MarkdownElement, MarkdownFont, MarkdownStyle,
};
@@ -758,9 +758,7 @@ enum AuthState {
Ok,
Unauthenticated {
description: Option<Entity<Markdown>>,
- configuration_view: Option<AnyView>,
pending_auth_method: Option<acp::AuthMethodId>,
- _subscription: Option<Subscription>,
},
}
@@ -1160,14 +1158,7 @@ impl ConversationView {
Err(e) => match e.downcast::<acp_thread::AuthRequired>() {
Ok(err) => {
cx.update(|window, cx| {
- Self::handle_auth_required(
- this,
- err,
- agent.agent_id(),
- connection,
- window,
- cx,
- )
+ Self::handle_auth_required(this, err, connection, window, cx)
})
.log_err();
return;
@@ -1449,55 +1440,17 @@ impl ConversationView {
fn handle_auth_required(
this: WeakEntity<Self>,
err: AuthRequired,
- agent_id: AgentId,
connection: Rc<dyn AgentConnection>,
window: &mut Window,
cx: &mut App,
) {
- let (configuration_view, subscription) = if let Some(provider_id) = &err.provider_id {
- let registry = LanguageModelRegistry::global(cx);
-
- let sub = window.subscribe(&registry, cx, {
- let provider_id = provider_id.clone();
- let this = this.clone();
- move |_, ev, window, cx| {
- if let language_model::Event::ProviderStateChanged(updated_provider_id) = &ev
- && &provider_id == updated_provider_id
- && LanguageModelRegistry::global(cx)
- .read(cx)
- .provider(&provider_id)
- .map_or(false, |provider| provider.is_authenticated(cx))
- {
- this.update(cx, |this, cx| {
- this.reset(window, cx);
- })
- .ok();
- }
- }
- });
-
- let view = registry.read(cx).provider(&provider_id).map(|provider| {
- provider.configuration_view(
- language_model::ConfigurationViewTargetAgent::Other(agent_id.0),
- window,
- cx,
- )
- });
-
- (view, Some(sub))
- } else {
- (None, None)
- };
-
this.update(cx, |this, cx| {
let description = err
.description
.map(|desc| cx.new(|cx| Markdown::new(desc.into(), None, None, cx)));
let auth_state = AuthState::Unauthenticated {
pending_auth_method: None,
- configuration_view,
description,
- _subscription: subscription,
};
if let Some(connected) = this.as_connected_mut() {
connected.auth_state = auth_state;
@@ -1963,7 +1916,6 @@ impl ConversationView {
let connection = connected.connection.clone();
let AuthState::Unauthenticated {
- configuration_view,
pending_auth_method,
..
} = &mut connected.auth_state
@@ -1974,7 +1926,6 @@ impl ConversationView {
let agent_telemetry_id = connection.telemetry_id();
if let Some(login_task) = connection.terminal_auth_task(&method, cx) {
- configuration_view.take();
pending_auth_method.replace(method.clone());
let project = self.project.clone();
@@ -2043,7 +1994,6 @@ impl ConversationView {
return;
}
- configuration_view.take();
pending_auth_method.replace(method.clone());
let authenticate = connection.authenticate(method, cx);
@@ -2292,7 +2242,6 @@ impl ConversationView {
&self,
connection: &Rc<dyn AgentConnection>,
description: Option<&Entity<Markdown>>,
- configuration_view: Option<&AnyView>,
pending_auth_method: Option<&acp::AuthMethodId>,
window: &mut Window,
cx: &Context<Self>,
@@ -2305,10 +2254,8 @@ impl ConversationView {
.agent_display_name(&self.agent.agent_id())
.unwrap_or_else(|| self.agent.agent_id().0);
- let show_fallback_description = auth_methods.len() > 1
- && configuration_view.is_none()
- && description.is_none()
- && pending_auth_method.is_none();
+ let show_fallback_description =
+ auth_methods.len() > 1 && description.is_none() && pending_auth_method.is_none();
let auth_buttons = || {
h_flex().justify_end().flex_wrap().gap_1().children(
@@ -2383,12 +2330,7 @@ impl ConversationView {
.color(Color::Muted),
)
} else {
- this.children(
- configuration_view
- .cloned()
- .map(|view| div().w_full().child(view)),
- )
- .children(description.map(|desc| {
+ this.children(description.map(|desc| {
self.render_markdown(
desc.clone(),
MarkdownStyle::themed(MarkdownFont::Agent, window, cx),
@@ -3245,7 +3187,6 @@ impl ConversationView {
}
pub(crate) fn reauthenticate(&mut self, window: &mut Window, cx: &mut Context<Self>) {
- let agent_id = self.agent.agent_id();
self.cancel_request_elicitations(cx);
if let Some(active) = self.root_thread_view() {
active.update(cx, |active, cx| active.clear_thread_error(cx));
@@ -3256,7 +3197,7 @@ impl ConversationView {
return;
};
window.defer(cx, |window, cx| {
- Self::handle_auth_required(this, AuthRequired::new(), agent_id, connection, window, cx);
+ Self::handle_auth_required(this, AuthRequired::new(), connection, window, cx);
})
}
@@ -3288,9 +3229,7 @@ impl ConversationView {
if let Some(connected) = this.as_connected_mut() {
connected.auth_state = AuthState::Unauthenticated {
description: None,
- configuration_view: None,
pending_auth_method: None,
- _subscription: None,
};
cx.emit(StateChange);
if let Some(view) = connected.active_view()
@@ -3431,9 +3370,7 @@ impl Render for ConversationView {
auth_state:
AuthState::Unauthenticated {
description,
- configuration_view,
pending_auth_method,
- _subscription,
},
..
}) => v_flex()
@@ -3443,7 +3380,6 @@ impl Render for ConversationView {
.child(self.render_auth_required_state(
connection,
description.as_ref(),
- configuration_view.as_ref(),
pending_auth_method.as_ref(),
window,
cx,
diff --git a/crates/agent_ui/src/conversation_view/thread_view.rs b/crates/agent_ui/src/conversation_view/thread_view.rs
index 858fc5e840e..0f3c18d2245 100644
--- a/crates/agent_ui/src/conversation_view/thread_view.rs
+++ b/crates/agent_ui/src/conversation_view/thread_view.rs
@@ -1490,13 +1490,11 @@ impl ThreadView {
let connection = self.thread.read(cx).connection().clone();
window.defer(cx, {
- let agent_id = self.agent_id.clone();
let server_view = self.server_view.clone();
move |window, cx| {
ConversationView::handle_auth_required(
server_view.clone(),
AuthRequired::new(),
- agent_id,
connection,
window,
cx,
@@ -10836,7 +10834,6 @@ impl ThreadView {
.on_click(cx.listener({
move |this, _, window, cx| {
let server_view = this.server_view.clone();
- let agent_name = this.agent_id.clone();
this.clear_thread_error(cx);
if let Some(message) = this.in_flight_prompt.take() {
@@ -10849,7 +10846,6 @@ impl ThreadView {
ConversationView::handle_auth_required(
server_view,
AuthRequired::new(),
- agent_name,
connection,
window,
cx,
diff --git a/crates/language_model/src/fake_provider.rs b/crates/language_model/src/fake_provider.rs
index f58130cccf4..a9cb4c5b5fb 100644
--- a/crates/language_model/src/fake_provider.rs
+++ b/crates/language_model/src/fake_provider.rs
@@ -1,12 +1,12 @@
use crate::{
- AuthenticateError, ConfigurationViewTargetAgent, LanguageModel, LanguageModelCompletionError,
- LanguageModelCompletionEvent, LanguageModelId, LanguageModelName, LanguageModelProvider,
- LanguageModelProviderId, LanguageModelProviderName, LanguageModelProviderState,
- LanguageModelRequest, LanguageModelToolChoice,
+ AuthenticateError, LanguageModel, LanguageModelCompletionError, LanguageModelCompletionEvent,
+ LanguageModelId, LanguageModelName, LanguageModelProvider, LanguageModelProviderId,
+ LanguageModelProviderName, LanguageModelProviderState, LanguageModelRequest,
+ LanguageModelToolChoice,
};
use anyhow::anyhow;
use futures::{FutureExt, channel::mpsc, future::BoxFuture, stream::BoxStream, stream::StreamExt};
-use gpui::{AnyView, App, AsyncApp, Entity, Task, Window};
+use gpui::{App, AsyncApp, Entity, Task};
use http_client::Result;
use parking_lot::Mutex;
use std::sync::{
@@ -68,17 +68,8 @@ impl LanguageModelProvider for FakeLanguageModelProvider {
Task::ready(Ok(()))
}
- fn configuration_view(
- &self,
- _target_agent: ConfigurationViewTargetAgent,
- _window: &mut Window,
- _: &mut App,
- ) -> AnyView {
- unimplemented!()
- }
-
- fn reset_credentials(&self, _: &mut App) -> Task<Result<()>> {
- Task::ready(Ok(()))
+ fn settings_view(&self, _: &mut App) -> Option<crate::ProviderSettingsView> {
+ None
}
}
diff --git a/crates/language_model/src/language_model.rs b/crates/language_model/src/language_model.rs
index 7a8aa00f92d..2e060049d0b 100644
--- a/crates/language_model/src/language_model.rs
+++ b/crates/language_model/src/language_model.rs
@@ -15,6 +15,8 @@ use icons::IconName;
use parking_lot::Mutex;
use std::sync::Arc;
+pub type CreateProviderSettingsView = Arc<dyn Fn(&mut Window, &mut App) -> AnyView + 'static>;
+
pub use crate::api_key::{ApiKey, ApiKeyState};
pub use crate::registry::*;
pub use crate::request::{LanguageModelImageExt, gpui_size_to_image_size, image_size_to_gpui};
@@ -320,13 +322,11 @@ pub trait LanguageModelProvider: 'static {
}
fn is_authenticated(&self, cx: &App) -> bool;
fn authenticate(&self, cx: &mut App) -> Task<Result<(), AuthenticateError>>;
- fn configuration_view(
- &self,
- target_agent: ConfigurationViewTargetAgent,
- window: &mut Window,
- cx: &mut App,
- ) -> AnyView;
- fn reset_credentials(&self, cx: &mut App) -> Task<Result<()>>;
+ fn settings_view(&self, cx: &mut App) -> Option<ProviderSettingsView>;
+
+ fn set_api_key(&self, _key: Option<String>, _cx: &mut App) -> Task<Result<()>> {
+ Task::ready(Ok(()))
+ }
/// Copy shown when this provider rejects a request as unauthenticated
/// (HTTP 401). The default assumes API-key authentication; providers using
@@ -335,7 +335,7 @@ pub trait LanguageModelProvider: 'static {
fn authentication_error_message(&self) -> SharedString {
format!(
"The API key for {} is invalid or has expired. \
- Update your key via the Agent Panel settings to continue.",
+ Update your key in Settings > AI > LLM Providers to continue.",
self.name().0
)
.into()
@@ -348,58 +348,69 @@ pub trait LanguageModelProvider: 'static {
fn missing_credentials_error_message(&self) -> SharedString {
format!(
"No API key is configured for {}. \
- Add your key via the Agent Panel settings to continue.",
+ Add your key in Settings > AI > LLM Providers to continue.",
self.name().0
)
.into()
}
- /// Returns the provider's configuration UI together with how it prefers to
- /// be presented: [`ProviderConfigurationView::Inline`] for a compact control
- /// that can sit in a list row (e.g. a single API-key field), or
- /// [`ProviderConfigurationView::SubPage`] for a richer view that needs its
- /// own surface.
- ///
- /// The default reuses [`Self::configuration_view`] as a sub-page, so
- /// providers only override this when they have a compact inline form.
- fn configuration_view_v2(
- &self,
- target_agent: ConfigurationViewTargetAgent,
- window: &mut Window,
- cx: &mut App,
- ) -> ProviderConfigurationView {
- ProviderConfigurationView::SubPage(self.configuration_view(target_agent, window, cx))
- }
-
- fn inline_title(&self, _cx: &App) -> Option<SharedString> {
+ /// Copy shown the first time a user enables fast mode for a model from
+ /// this provider. Returning `None` skips the confirmation prompt and lets
+ /// the toggle apply silently.
+ fn fast_mode_confirmation(&self, _cx: &App) -> Option<FastModeConfirmation> {
None
}
+}
- fn inline_description(&self, _cx: &App) -> Option<InlineDescription> {
- None
- }
+/// A provider's settings UI, modeled as mutually exclusive presentation modes.
+#[derive(Clone)]
+pub enum ProviderSettingsView {
+ ApiKey(ApiKeyConfiguration),
+ Inline(InlineProviderSettings),
+ SubPage(SubPageProviderSettings),
+}
- fn api_key_configuration(&self, _cx: &App) -> Option<ApiKeyConfiguration> {
- None
- }
+#[derive(Clone)]
+pub struct InlineProviderSettings {
+ pub title: Option<SharedString>,
+ pub description: Option<InlineDescription>,
+ pub create_view: CreateProviderSettingsView,
+}
- fn set_api_key(&self, _key: String, _cx: &mut App) -> Task<Result<()>> {
- Task::ready(Ok(()))
+#[derive(Clone)]
+pub struct SubPageProviderSettings {
+ pub description: Option<InlineDescription>,
+ pub create_view: CreateProviderSettingsView,
+}
+
+impl SubPageProviderSettings {
+ pub fn new(create_view: impl Fn(&mut Window, &mut App) -> AnyView + 'static) -> Self {
+ Self {
+ description: None,
+ create_view: Arc::new(create_view),
+ }
}
- /// Copy shown the first time a user enables fast mode for a model from
- /// this provider. Returning `None` skips the confirmation prompt and lets
- /// the toggle apply silently.
- fn fast_mode_confirmation(&self, _cx: &App) -> Option<FastModeConfirmation> {
- None
+ pub fn description(mut self, description: InlineDescription) -> Self {
+ self.description = Some(description);
+ self
}
}
-/// How a provider's configuration UI prefers to be presented by the settings UI.
-#[derive(Clone)]
-pub enum ProviderConfigurationView {
- Inline { view: AnyView },
- SubPage(AnyView),
+impl ApiKeyConfiguration {
+ pub fn new(
+ has_key: bool,
+ is_from_env_var: bool,
+ env_var_name: SharedString,
+ api_key_url: SharedString,
+ ) -> Self {
+ Self {
+ has_key,
+ is_from_env_var,
+ env_var_name,
+ api_key_url,
+ }
+ }
}
/// A live snapshot of a single-API-key provider's credential state, used by the
@@ -430,13 +441,6 @@ pub struct FastModeConfirmation {
pub message: SharedString,
}
-#[derive(Default, Clone, PartialEq, Eq)]
-pub enum ConfigurationViewTargetAgent {
- #[default]
- ZedAgent,
- Other(SharedString),
-}
-
pub trait LanguageModelProviderState: 'static {
type ObservableEntity;
diff --git a/crates/language_models/src/provider/anthropic.rs b/crates/language_models/src/provider/anthropic.rs
index 1841a9619d2..19ba2b45678 100644
--- a/crates/language_models/src/provider/anthropic.rs
+++ b/crates/language_models/src/provider/anthropic.rs
@@ -5,21 +5,19 @@ use anyhow::Result;
use collections::BTreeMap;
use credentials_provider::CredentialsProvider;
use futures::{FutureExt, StreamExt, future::BoxFuture, stream::BoxStream};
-use gpui::{AnyView, App, AsyncApp, Context, Entity, Task, TaskExt};
+use gpui::{App, AppContext, AsyncApp, Context, Entity, SharedString, Task};
use http_client::{CustomHeaders, HttpClient};
use language_model::{
ANTHROPIC_PROVIDER_ID, ANTHROPIC_PROVIDER_NAME, ApiKeyConfiguration, ApiKeyState,
- AuthenticateError, ConfigurationViewTargetAgent, EnvVar, FastModeConfirmation, IconOrSvg,
- LanguageModel, LanguageModelCompletionError, LanguageModelCompletionEvent, LanguageModelId,
- LanguageModelName, LanguageModelProvider, LanguageModelProviderId, LanguageModelProviderName,
- LanguageModelProviderState, LanguageModelRequest, LanguageModelToolChoice, RateLimiter,
- env_var,
+ AuthenticateError, EnvVar, FastModeConfirmation, IconOrSvg, LanguageModel,
+ LanguageModelCompletionError, LanguageModelCompletionEvent, LanguageModelId, LanguageModelName,
+ LanguageModelProvider, LanguageModelProviderId, LanguageModelProviderName,
+ LanguageModelProviderState, LanguageModelRequest, LanguageModelToolChoice,
+ ProviderSettingsView, RateLimiter, env_var,
};
use settings::{Settings, SettingsStore};
use std::sync::{Arc, LazyLock};
-use ui::{ButtonLink, ConfiguredApiCard, List, ListBulletItem, prelude::*};
-use ui_input::InputField;
-use util::ResultExt;
+use ui::IconName;
pub use anthropic::completion::{AnthropicEventMapper, AnthropicPromptCacheMode, into_anthropic};
pub use settings::AnthropicAvailableModel as AvailableModel;
@@ -275,34 +273,19 @@ impl LanguageModelProvider for AnthropicLanguageModelProvider {
self.state.update(cx, |state, cx| state.authenticate(cx))
}
- fn configuration_view(
- &self,
- target_agent: ConfigurationViewTargetAgent,
- window: &mut Window,
- cx: &mut App,
- ) -> AnyView {
- cx.new(|cx| ConfigurationView::new(self.state.clone(), target_agent, window, cx))
- .into()
- }
-
- fn reset_credentials(&self, cx: &mut App) -> Task<Result<()>> {
- self.state
- .update(cx, |state, cx| state.set_api_key(None, cx))
- }
-
- fn api_key_configuration(&self, cx: &App) -> Option<ApiKeyConfiguration> {
+ fn settings_view(&self, cx: &mut App) -> Option<ProviderSettingsView> {
let state = self.state.read(cx);
- Some(ApiKeyConfiguration {
- has_key: state.api_key_state.has_key(),
- is_from_env_var: state.api_key_state.is_from_env_var(),
- env_var_name: state.api_key_state.env_var_name().clone(),
- api_key_url: "https://console.anthropic.com/settings/keys".into(),
- })
+ Some(ProviderSettingsView::ApiKey(ApiKeyConfiguration::new(
+ state.api_key_state.has_key(),
+ state.api_key_state.is_from_env_var(),
+ state.api_key_state.env_var_name().clone(),
+ "https://console.anthropic.com/settings/keys".into(),
+ )))
}
- fn set_api_key(&self, key: String, cx: &mut App) -> Task<Result<()>> {
+ fn set_api_key(&self, api_key: Option<String>, cx: &mut App) -> Task<Result<()>> {
self.state
- .update(cx, |state, cx| state.set_api_key(Some(key), cx))
+ .update(cx, |state, cx| state.set_api_key(api_key, cx))
}
fn fast_mode_confirmation(&self, _cx: &App) -> Option<FastModeConfirmation> {
@@ -564,144 +547,3 @@ impl LanguageModel for AnthropicModel {
async move { Ok(future.await?.boxed()) }.boxed()
}
}
-
-struct ConfigurationView {
- api_key_editor: Entity<InputField>,
- state: Entity<State>,
- load_credentials_task: Option<Task<()>>,
- target_agent: ConfigurationViewTargetAgent,
-}
-
-impl ConfigurationView {
- const PLACEHOLDER_TEXT: &'static str = "sk-ant-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
-
- fn new(
- state: Entity<State>,
- target_agent: ConfigurationViewTargetAgent,
- window: &mut Window,
- cx: &mut Context<Self>,
- ) -> Self {
- cx.observe(&state, |_, _, cx| {
- cx.notify();
- })
- .detach();
-
- let load_credentials_task = Some(cx.spawn({
- let state = state.clone();
- async move |this, cx| {
- let task = state.update(cx, |state, cx| state.authenticate(cx));
- // We don't log an error, because "not signed in" is also an error.
- let _ = task.await;
- this.update(cx, |this, cx| {
- this.load_credentials_task = None;
- cx.notify();
- })
- .log_err();
- }
- }));
-
- Self {
- api_key_editor: cx.new(|cx| InputField::new(window, cx, Self::PLACEHOLDER_TEXT)),
- state,
- load_credentials_task,
- target_agent,
- }
- }
-
- fn save_api_key(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
- let api_key = self.api_key_editor.read(cx).text(cx);
- if api_key.is_empty() {
- return;
- }
-
- // url changes can cause the editor to be displayed again
- self.api_key_editor
- .update(cx, |editor, cx| editor.set_text("", window, cx));
-
- let state = self.state.clone();
- cx.spawn_in(window, async move |_, cx| {
- state
- .update(cx, |state, cx| state.set_api_key(Some(api_key), cx))
- .await
- })
- .detach_and_log_err(cx);
- }
-
- fn reset_api_key(&mut self, window: &mut Window, cx: &mut Context<Self>) {
- self.api_key_editor
- .update(cx, |editor, cx| editor.set_text("", window, cx));
-
- let state = self.state.clone();
- cx.spawn_in(window, async move |_, cx| {
- state
- .update(cx, |state, cx| state.set_api_key(None, cx))
- .await
- })
- .detach_and_log_err(cx);
- }
-
- fn should_render_editor(&self, cx: &mut Context<Self>) -> bool {
- !self.state.read(cx).is_authenticated()
- }
-}
-
-impl Render for ConfigurationView {
- fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
- let env_var_set = self.state.read(cx).api_key_state.is_from_env_var();
- let configured_card_label = if env_var_set {
- format!("API key set in {API_KEY_ENV_VAR_NAME} environment variable")
- } else {
- let api_url = AnthropicLanguageModelProvider::api_url(cx);
- if api_url == ANTHROPIC_API_URL {
- "API key configured".to_string()
- } else {
- format!("API key configured for {}", api_url)
- }
- };
-
- if self.load_credentials_task.is_some() {
- div()
- .child(Label::new("Loading credentials..."))
- .into_any_element()
- } else if self.should_render_editor(cx) {
- v_flex()
- .size_full()
- .on_action(cx.listener(Self::save_api_key))
- .child(Label::new(format!("To use {}, you need to add an API key. Follow these steps:", match &self.target_agent {
- ConfigurationViewTargetAgent::ZedAgent => "Zed's agent with Anthropic".into(),
- ConfigurationViewTargetAgent::Other(agent) => agent.clone(),
- })))
- .child(
- List::new()
- .child(
- ListBulletItem::new("")
- .child(Label::new("Create one by visiting"))
- .child(ButtonLink::new("Anthropic's settings", "https://console.anthropic.com/settings/keys"))
- )
- .child(
- ListBulletItem::new("Paste your API key below and hit enter to start using the agent")
- )
- )
- .child(self.api_key_editor.clone())
- .child(
- Label::new(
- format!("You can also set the {API_KEY_ENV_VAR_NAME} environment variable and restart Zed."),
- )
- .size(LabelSize::Small)
- .color(Color::Muted)
- .mt_0p5(),
- )
- .into_any_element()
- } else {
- ConfiguredApiCard::new("anthropic-reset-key", configured_card_label)
- .disabled(env_var_set)
- .on_click(cx.listener(|this, _, window, cx| this.reset_api_key(window, cx)))
- .when(env_var_set, |this| {
- this.tooltip_label(format!(
- "To reset your API key, unset the {API_KEY_ENV_VAR_NAME} environment variable."
- ))
- })
- .into_any_element()
- }
- }
-}
diff --git a/crates/language_models/src/provider/anthropic_compatible.rs b/crates/language_models/src/provider/anthropic_compatible.rs
index b0790045324..8a3ddd85da4 100644
--- a/crates/language_models/src/provider/anthropic_compatible.rs
+++ b/crates/language_models/src/provider/anthropic_compatible.rs
@@ -3,13 +3,14 @@ use anthropic::{AnthropicError, AnthropicModelMode};
use anyhow::Result;
use credentials_provider::CredentialsProvider;
use futures::{FutureExt, StreamExt, future::BoxFuture, stream::BoxStream};
-use gpui::{AnyView, App, AppContext, AsyncApp, Entity, Task, Window};
+use gpui::{App, AppContext, AsyncApp, Entity, Task};
use http_client::{CustomHeaders, HttpClient};
use language_model::{
AuthenticateError, IconOrSvg, LanguageModel, LanguageModelCompletionError,
LanguageModelCompletionEvent, LanguageModelId, LanguageModelName, LanguageModelProvider,
LanguageModelProviderId, LanguageModelProviderName, LanguageModelProviderState,
- LanguageModelRequest, LanguageModelToolChoice, RateLimiter,
+ LanguageModelRequest, LanguageModelToolChoice, ProviderSettingsView, RateLimiter,
+ SubPageProviderSettings,
};
use settings::Settings;
use std::sync::Arc;
@@ -181,32 +182,27 @@ impl LanguageModelProvider for AnthropicCompatibleLanguageModelProvider {
self.state.update(cx, |state, cx| state.authenticate(cx))
}
- fn configuration_view(
- &self,
- _target_agent: language_model::ConfigurationViewTargetAgent,
- window: &mut Window,
- cx: &mut App,
- ) -> AnyView {
- cx.new(|cx| {
- ApiCompatibleProviderConfigurationView::new(
- self.state.clone(),
- "Anthropic",
- API_KEY_PLACEHOLDER,
- window,
- cx,
- )
- })
- .into()
- }
-
- fn set_api_key(&self, key: String, cx: &mut App) -> Task<Result<()>> {
- self.state
- .update(cx, |state, cx| state.set_api_key(Some(key), cx))
+ fn settings_view(&self, _cx: &mut App) -> Option<ProviderSettingsView> {
+ let state = self.state.clone();
+ Some(ProviderSettingsView::SubPage(SubPageProviderSettings::new(
+ move |window, cx| {
+ cx.new(|cx| {
+ ApiCompatibleProviderConfigurationView::new(
+ state.clone(),
+ "Anthropic",
+ API_KEY_PLACEHOLDER,
+ window,
+ cx,
+ )
+ })
+ .into()
+ },
+ )))
}
- fn reset_credentials(&self, cx: &mut App) -> Task<Result<()>> {
+ fn set_api_key(&self, api_key: Option<String>, cx: &mut App) -> Task<Result<()>> {
self.state
- .update(cx, |state, cx| state.set_api_key(None, cx))
+ .update(cx, |state, cx| state.set_api_key(api_key, cx))
}
}
diff --git a/crates/language_models/src/provider/bedrock.rs b/crates/language_models/src/provider/bedrock.rs
index 4d843009f76..ee673577c66 100644
--- a/crates/language_models/src/provider/bedrock.rs
+++ b/crates/language_models/src/provider/bedrock.rs
@@ -26,8 +26,7 @@ use collections::{BTreeMap, HashMap};
use credentials_provider::CredentialsProvider;
use futures::{FutureExt, Stream, StreamExt, future::BoxFuture, stream::BoxStream};
use gpui::{
- AnyView, App, AsyncApp, Context, Entity, FocusHandle, Subscription, Task, TaskExt, Window,
- actions,
+ App, AsyncApp, Context, Entity, FocusHandle, Subscription, Task, TaskExt, Window, actions,
};
use gpui_tokio::Tokio;
use http_client::HttpClient;
@@ -36,8 +35,8 @@ use language_model::{
LanguageModelCompletionError, LanguageModelCompletionEvent, LanguageModelId, LanguageModelName,
LanguageModelProvider, LanguageModelProviderId, LanguageModelProviderName,
LanguageModelProviderState, LanguageModelRequest, LanguageModelToolChoice,
- LanguageModelToolResultContent, LanguageModelToolUse, MessageContent, RateLimiter, Role,
- TokenUsage, env_var,
+ LanguageModelToolResultContent, LanguageModelToolUse, MessageContent, ProviderSettingsView,
+ RateLimiter, Role, SubPageProviderSettings, TokenUsage, env_var,
};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
@@ -461,12 +460,6 @@ impl LanguageModelProvider for BedrockLanguageModelProvider {
IconOrSvg::Icon(IconName::AiBedrock)
}
- fn inline_description(&self, _cx: &App) -> Option<InlineDescription> {
- Some(InlineDescription::Text(
- "To use Zed's agent with Bedrock, set a custom authentication strategy in your settings or use static credentials.".into(),
- ))
- }
-
fn default_model(&self, _cx: &App) -> Option<Arc<dyn LanguageModel>> {
Some(self.create_language_model(bedrock::Model::default()))
}
@@ -523,18 +516,17 @@ impl LanguageModelProvider for BedrockLanguageModelProvider {
self.state.update(cx, |state, cx| state.authenticate(cx))
}
- fn configuration_view(
- &self,
- _target_agent: language_model::ConfigurationViewTargetAgent,
- window: &mut Window,
- cx: &mut App,
- ) -> AnyView {
- cx.new(|cx| ConfigurationView::new(self.state.clone(), window, cx))
- .into()
- }
-
- fn reset_credentials(&self, cx: &mut App) -> Task<Result<()>> {
- self.state.update(cx, |state, cx| state.reset_auth(cx))
+ fn settings_view(&self, _cx: &mut App) -> Option<ProviderSettingsView> {
+ let state = self.state.clone();
+ Some(ProviderSettingsView::SubPage(
+ SubPageProviderSettings::new(move |window, cx| {
+ cx.new(|cx| ConfigurationView::new(state.clone(), window, cx))
+ .into()
+ })
+ .description(InlineDescription::Text(
+ "To use Zed's agent with Bedrock, set a custom authentication strategy in your settings or use static credentials.".into(),
+ )),
+ ))
}
}
diff --git a/crates/language_models/src/provider/cloud.rs b/crates/language_models/src/provider/cloud.rs
index 926f99eae1b..06131314eef 100644
--- a/crates/language_models/src/provider/cloud.rs
+++ b/crates/language_models/src/provider/cloud.rs
@@ -9,11 +9,11 @@ use cloud_api_types::Plan;
use futures::FutureExt;
use futures::StreamExt;
use futures::future::BoxFuture;
-use gpui::{AnyElement, AnyView, App, AppContext, Context, Entity, Subscription, Task, TaskExt};
+use gpui::{AnyElement, App, AppContext, Context, Entity, Subscription, Task, TaskExt};
use language_model::{
AuthenticateError, FastModeConfirmation, IconOrSvg, InlineDescription, LanguageModel,
LanguageModelProvider, LanguageModelProviderId, LanguageModelProviderName,
- LanguageModelProviderState, ProviderConfigurationView, ZED_CLOUD_PROVIDER_ID,
+ LanguageModelProviderState, ProviderSettingsView, ZED_CLOUD_PROVIDER_ID,
ZED_CLOUD_PROVIDER_NAME,
};
use language_models_cloud::{CloudLlmTokenProvider, CloudModelProvider};
@@ -360,37 +360,13 @@ impl LanguageModelProvider for CloudLanguageModelProvider {
})
}
- fn configuration_view(
- &self,
- _target_agent: language_model::ConfigurationViewTargetAgent,
- _: &mut Window,
- cx: &mut App,
- ) -> AnyView {
- cx.new(|_| ConfigurationView::new(self.state.clone(), false))
- .into()
- }
-
- fn configuration_view_v2(
- &self,
- _target_agent: language_model::ConfigurationViewTargetAgent,
- _window: &mut Window,
- cx: &mut App,
- ) -> ProviderConfigurationView {
- ProviderConfigurationView::Inline {
- view: cx
- .new(|_| ConfigurationView::new(self.state.clone(), true))
- .into(),
- }
- }
-
- fn inline_description(&self, cx: &App) -> Option<InlineDescription> {
+ fn settings_view(&self, cx: &mut App) -> Option<ProviderSettingsView> {
let state = self.state.read(cx);
let user_store = state.user_store.read(cx);
let is_zed_model_provider_enabled = user_store
.current_organization_configuration()
.map_or(true, |config| config.is_zed_model_provider_enabled);
-
- Some(InlineDescription::Text(
+ let description = InlineDescription::Text(
zed_ai_description(
!state.is_signed_out(cx),
user_store.plan(),
@@ -398,27 +374,34 @@ impl LanguageModelProvider for CloudLanguageModelProvider {
user_store.trial_started_at().is_none(),
)
.into(),
- ))
- }
+ );
- fn inline_title(&self, cx: &App) -> Option<SharedString> {
- let state = self.state.read(cx);
- if state.is_signed_out(cx) {
- return None;
- }
- let plan_name = match state.user_store.read(cx).plan()? {
- Plan::ZedPro => "Pro",
- Plan::ZedProTrial => "Pro Trial",
- Plan::ZedStudent => "Student",
- Plan::ZedBusiness => "Business",
- Plan::ZedVip => "VIP",
- Plan::ZedFree => return None,
+ let title = if state.is_signed_out(cx) {
+ None
+ } else {
+ match state.user_store.read(cx).plan() {
+ Some(Plan::ZedPro) => Some("Subscribed to Pro".into()),
+ Some(Plan::ZedProTrial) => Some("Subscribed to Pro Trial".into()),
+ Some(Plan::ZedStudent) => Some("Subscribed to Student".into()),
+ Some(Plan::ZedBusiness) => Some("Subscribed to Business".into()),
+ Some(Plan::ZedVip) => Some("Subscribed to VIP".into()),
+ Some(Plan::ZedFree) | None => None,
+ }
};
- Some(format!("Subscribed to {plan_name}").into())
- }
- fn reset_credentials(&self, _cx: &mut App) -> Task<Result<()>> {
- Task::ready(Ok(()))
+ Some(ProviderSettingsView::Inline(
+ language_model::InlineProviderSettings {
+ title,
+ description: Some(description),
+ create_view: Arc::new({
+ let state = self.state.clone();
+ move |_window, cx| {
+ cx.new(|_| ConfigurationView::new(state.clone(), true))
+ .into()
+ }
+ }),
+ },
+ ))
}
fn authentication_error_message(&self) -> SharedString {
diff --git a/crates/language_models/src/provider/copilot_chat.rs b/crates/language_models/src/provider/copilot_chat.rs
index 94bc00e72d5..db845e85796 100644
--- a/crates/language_models/src/provider/copilot_chat.rs
+++ b/crates/language_models/src/provider/copilot_chat.rs
@@ -16,7 +16,7 @@ use copilot_chat::{
use futures::future::BoxFuture;
use futures::stream::BoxStream;
use futures::{FutureExt, Stream, StreamExt};
-use gpui::{AnyView, App, AsyncApp, Entity, Subscription, Task};
+use gpui::{App, AsyncApp, Entity, Subscription, Task};
use http_client::StatusCode;
use language::language_settings::all_language_settings;
use language_model::{
@@ -25,7 +25,7 @@ use language_model::{
LanguageModelName, LanguageModelProvider, LanguageModelProviderId, LanguageModelProviderName,
LanguageModelProviderState, LanguageModelRequest, LanguageModelRequestMessage,
LanguageModelToolChoice, LanguageModelToolResultContent, LanguageModelToolSchemaFormat,
- LanguageModelToolUse, MessageContent, ProviderConfigurationView, RateLimiter, Role, StopReason,
+ LanguageModelToolUse, MessageContent, ProviderSettingsView, RateLimiter, Role, StopReason,
TokenUsage,
};
use settings::SettingsStore;
@@ -177,76 +177,42 @@ impl LanguageModelProvider for CopilotChatLanguageModelProvider {
Task::ready(Err(err.into()))
}
- fn configuration_view(
- &self,
- _target_agent: language_model::ConfigurationViewTargetAgent,
- _: &mut Window,
- cx: &mut App,
- ) -> AnyView {
- cx.new(|cx| {
- copilot_ui::ConfigurationView::new(
- |cx| {
- CopilotChat::global(cx)
- .map(|m| m.read(cx).is_authenticated())
- .unwrap_or(false)
- },
- copilot_ui::ConfigurationMode::Chat,
- cx,
- )
- })
- .into()
- }
-
- fn configuration_view_v2(
- &self,
- _target_agent: language_model::ConfigurationViewTargetAgent,
- _window: &mut Window,
- cx: &mut App,
- ) -> ProviderConfigurationView {
- // GitHub Copilot's control is just a sign-in/out button, so render it
- // inline rather than behind a sub-page. The explanatory copy is surfaced
- // via `inline_description` (the row's left column), so the view itself
- // renders compactly.
- ProviderConfigurationView::Inline {
- view: cx
- .new(|cx| {
- copilot_ui::ConfigurationView::new(
- |cx| {
- CopilotChat::global(cx)
- .map(|m| m.read(cx).is_authenticated())
- .unwrap_or(false)
- },
- copilot_ui::ConfigurationMode::Chat,
- cx,
- )
- .compact()
- })
- .into(),
- }
- }
-
- fn inline_title(&self, cx: &App) -> Option<SharedString> {
- if self.state.read(cx).is_authenticated(cx) {
+ fn settings_view(&self, cx: &mut App) -> Option<ProviderSettingsView> {
+ let is_authenticated = self.state.read(cx).is_authenticated(cx);
+ let title = if is_authenticated {
None
} else {
Some("Configure Copilot".into())
- }
- }
-
- fn inline_description(&self, cx: &App) -> Option<language_model::InlineDescription> {
- if self.state.read(cx).is_authenticated(cx) {
+ };
+ let description = if is_authenticated {
None
} else {
Some(language_model::InlineDescription::Text(
"Requires an active GitHub Copilot subscription.".into(),
))
- }
- }
+ };
- fn reset_credentials(&self, _cx: &mut App) -> Task<Result<()>> {
- Task::ready(Err(anyhow!(
- "Signing out of GitHub Copilot Chat is currently not supported."
- )))
+ Some(ProviderSettingsView::Inline(
+ language_model::InlineProviderSettings {
+ title,
+ description,
+ create_view: Arc::new(|_window, cx| {
+ cx.new(|cx| {
+ copilot_ui::ConfigurationView::new(
+ |cx| {
+ CopilotChat::global(cx)
+ .map(|m| m.read(cx).is_authenticated())
+ .unwrap_or(false)
+ },
+ copilot_ui::ConfigurationMode::Chat,
+ cx,
+ )
+ .compact()
+ })
+ .into()
+ }),
+ },
+ ))
}
}
diff --git a/crates/language_models/src/provider/deepseek.rs b/crates/language_models/src/provider/deepseek.rs
index 943b3861e3c..f448ae2be68 100644
--- a/crates/language_models/src/provider/deepseek.rs
+++ b/crates/language_models/src/provider/deepseek.rs
@@ -5,7 +5,7 @@ use deepseek::DEEPSEEK_API_URL;
use futures::Stream;
use futures::{FutureExt, StreamExt, future::BoxFuture, stream::BoxStream};
-use gpui::{AnyView, App, AsyncApp, Context, Entity, SharedString, Task, TaskExt, Window};
+use gpui::{App, AppContext, AsyncApp, Context, Entity, SharedString, Task};
use http_client::{CustomHeaders, HttpClient};
use language_model::{
ApiKeyConfiguration, ApiKeyState, AuthenticateError, EnvVar, IconOrSvg, LanguageModel,
@@ -13,16 +13,14 @@ use language_model::{
LanguageModelId, LanguageModelName, LanguageModelProvider, LanguageModelProviderId,
LanguageModelProviderName, LanguageModelProviderState, LanguageModelRequest,
LanguageModelToolChoice, LanguageModelToolResultContent, LanguageModelToolUse, MessageContent,
- RateLimiter, Role, StopReason, TokenUsage, env_var,
+ ProviderSettingsView, RateLimiter, Role, StopReason, TokenUsage, env_var,
};
pub use settings::DeepseekAvailableModel as AvailableModel;
use settings::{Settings, SettingsStore};
use std::pin::Pin;
use std::sync::{Arc, LazyLock};
-use ui::{ButtonLink, ConfiguredApiCard, List, ListBulletItem, prelude::*};
-use ui_input::InputField;
-use util::ResultExt;
+use ui::IconName;
use language_model::util::{fix_streamed_json, parse_tool_arguments};
@@ -197,34 +195,19 @@ impl LanguageModelProvider for DeepSeekLanguageModelProvider {
self.state.update(cx, |state, cx| state.authenticate(cx))
}
- fn configuration_view(
- &self,
- _target_agent: language_model::ConfigurationViewTargetAgent,
- window: &mut Window,
- cx: &mut App,
- ) -> AnyView {
- cx.new(|cx| ConfigurationView::new(self.state.clone(), window, cx))
- .into()
- }
-
- fn reset_credentials(&self, cx: &mut App) -> Task<Result<()>> {
- self.state
- .update(cx, |state, cx| state.set_api_key(None, cx))
- }
-
- fn api_key_configuration(&self, cx: &App) -> Option<ApiKeyConfiguration> {
+ fn settings_view(&self, cx: &mut App) -> Option<ProviderSettingsView> {
let state = self.state.read(cx);
- Some(ApiKeyConfiguration {
- has_key: state.api_key_state.has_key(),
- is_from_env_var: state.api_key_state.is_from_env_var(),
- env_var_name: state.api_key_state.env_var_name().clone(),
- api_key_url: "https://platform.deepseek.com/api_keys".into(),
- })
+ Some(ProviderSettingsView::ApiKey(ApiKeyConfiguration::new(
+ state.api_key_state.has_key(),
+ state.api_key_state.is_from_env_var(),
+ state.api_key_state.env_var_name().clone(),
+ "https://platform.deepseek.com/api_keys".into(),
+ )))
}
- fn set_api_key(&self, key: String, cx: &mut App) -> Task<Result<()>> {
+ fn set_api_key(&self, api_key: Option<String>, cx: &mut App) -> Task<Result<()>> {
self.state
- .update(cx, |state, cx| state.set_api_key(Some(key), cx))
+ .update(cx, |state, cx| state.set_api_key(api_key, cx))
}
}
@@ -652,129 +635,3 @@ impl DeepSeekEventMapper {
events
}
}
-
-struct ConfigurationView {
- api_key_editor: Entity<InputField>,
- state: Entity<State>,
- load_credentials_task: Option<Task<()>>,
-}
-
-impl ConfigurationView {
- fn new(state: Entity<State>, window: &mut Window, cx: &mut Context<Self>) -> Self {
- let api_key_editor =
- cx.new(|cx| InputField::new(window, cx, "sk-00000000000000000000000000000000"));
-
- cx.observe(&state, |_, _, cx| {
- cx.notify();
- })
- .detach();
-
- let load_credentials_task = Some(cx.spawn({
- let state = state.clone();
- async move |this, cx| {
- if let Some(task) = Some(state.update(cx, |state, cx| state.authenticate(cx))) {
- let _ = task.await;
- }
-
- this.update(cx, |this, cx| {
- this.load_credentials_task = None;
- cx.notify();
- })
- .log_err();
- }
- }));
-
- Self {
- api_key_editor,
- state,
- load_credentials_task,
- }
- }
-
- fn save_api_key(&mut self, _: &menu::Confirm, _window: &mut Window, cx: &mut Context<Self>) {
- let api_key = self.api_key_editor.read(cx).text(cx).trim().to_string();
- if api_key.is_empty() {
- return;
- }
-
- let state = self.state.clone();
- cx.spawn(async move |_, cx| {
- state
- .update(cx, |state, cx| state.set_api_key(Some(api_key), cx))
- .await
- })
- .detach_and_log_err(cx);
- }
-
- fn reset_api_key(&mut self, window: &mut Window, cx: &mut Context<Self>) {
- self.api_key_editor
- .update(cx, |editor, cx| editor.set_text("", window, cx));
-
- let state = self.state.clone();
- cx.spawn(async move |_, cx| {
- state
- .update(cx, |state, cx| state.set_api_key(None, cx))
- .await
- })
- .detach_and_log_err(cx);
- }
-
- fn should_render_editor(&self, cx: &mut Context<Self>) -> bool {
- !self.state.read(cx).is_authenticated()
- }
-}
-
-impl Render for ConfigurationView {
- fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
- let env_var_set = self.state.read(cx).api_key_state.is_from_env_var();
- let configured_card_label = if env_var_set {
- format!("API key set in {API_KEY_ENV_VAR_NAME} environment variable")
- } else {
- let api_url = DeepSeekLanguageModelProvider::api_url(cx);
- if api_url == DEEPSEEK_API_URL {
- "API key configured".to_string()
- } else {
- format!("API key configured for {}", api_url)
- }
- };
-
- if self.load_credentials_task.is_some() {
- div()
- .child(Label::new("Loading credentials..."))
- .into_any_element()
- } else if self.should_render_editor(cx) {
- v_flex()
- .size_full()
- .on_action(cx.listener(Self::save_api_key))
- .child(Label::new("To use DeepSeek in Zed, you need an API key:"))
- .child(
- List::new()
- .child(
- ListBulletItem::new("")
- .child(Label::new("Get your API key from the"))
- .child(ButtonLink::new(
- "DeepSeek console",
- "https://platform.deepseek.com/api_keys",
- )),
- )
- .child(ListBulletItem::new(
- "Paste your API key below and hit enter to start using the assistant",
- )),
- )
- .child(self.api_key_editor.clone())
- .child(
- Label::new(format!(
- "You can also set the {API_KEY_ENV_VAR_NAME} environment variable and restart Zed."
- ))
- .size(LabelSize::Small)
- .color(Color::Muted),
- )
- .into_any_element()
- } else {
- ConfiguredApiCard::new("deepseek-reset-key", configured_card_label)
- .disabled(env_var_set)
- .on_click(cx.listener(|this, _, window, cx| this.reset_api_key(window, cx)))
- .into_any_element()
- }
- }
-}
diff --git a/crates/language_models/src/provider/google.rs b/crates/language_models/src/provider/google.rs
index 8a289fd2e05..7906e8f301e 100644
--- a/crates/language_models/src/provider/google.rs
+++ b/crates/language_models/src/provider/google.rs
@@ -4,17 +4,17 @@ use credentials_provider::CredentialsProvider;
use futures::{FutureExt, StreamExt, future::BoxFuture};
use google_ai::GenerateContentResponse;
pub use google_ai::completion::{GoogleEventMapper, into_google};
-use gpui::{AnyView, App, AsyncApp, Context, Entity, SharedString, Task, TaskExt, Window};
+use gpui::{App, AppContext, AsyncApp, Context, Entity, SharedString, Task};
use http_client::{CustomHeaders, HttpClient};
use language_model::{
- ApiKeyConfiguration, AuthenticateError, ConfigurationViewTargetAgent, EnvVar,
- LanguageModelCompletionError, LanguageModelCompletionEvent, LanguageModelToolChoice,
- LanguageModelToolSchemaFormat,
+ ApiKeyConfiguration, AuthenticateError, EnvVar, LanguageModelCompletionError,
+ LanguageModelCompletionEvent, LanguageModelToolChoice, LanguageModelToolSchemaFormat,
};
use language_model::{
GOOGLE_PROVIDER_ID, GOOGLE_PROVIDER_NAME, IconOrSvg, LanguageModel, LanguageModelEffortLevel,
LanguageModelId, LanguageModelName, LanguageModelProvider, LanguageModelProviderId,
- LanguageModelProviderName, LanguageModelProviderState, LanguageModelRequest, RateLimiter,
+ LanguageModelProviderName, LanguageModelProviderState, LanguageModelRequest,
+ ProviderSettingsView, RateLimiter,
};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
@@ -22,9 +22,7 @@ pub use settings::GoogleAvailableModel as AvailableModel;
use settings::{Settings, SettingsStore};
use std::sync::{Arc, LazyLock};
use strum::IntoEnumIterator;
-use ui::{ButtonLink, ConfiguredApiCard, List, ListBulletItem, prelude::*};
-use ui_input::InputField;
-use util::ResultExt;
+use ui::IconName;
use language_model::ApiKeyState;
@@ -222,34 +220,19 @@ impl LanguageModelProvider for GoogleLanguageModelProvider {
self.state.update(cx, |state, cx| state.authenticate(cx))
}
- fn configuration_view(
- &self,
- target_agent: language_model::ConfigurationViewTargetAgent,
- window: &mut Window,
- cx: &mut App,
- ) -> AnyView {
- cx.new(|cx| ConfigurationView::new(self.state.clone(), target_agent, window, cx))
- .into()
- }
-
- fn reset_credentials(&self, cx: &mut App) -> Task<Result<()>> {
- self.state
- .update(cx, |state, cx| state.set_api_key(None, cx))
- }
-
- fn api_key_configuration(&self, cx: &App) -> Option<ApiKeyConfiguration> {
+ fn settings_view(&self, cx: &mut App) -> Option<ProviderSettingsView> {
let state = self.state.read(cx);
- Some(ApiKeyConfiguration {
- has_key: state.api_key_state.has_key(),
- is_from_env_var: state.api_key_state.is_from_env_var(),
- env_var_name: state.api_key_state.env_var_name().clone(),
- api_key_url: "https://aistudio.google.com/app/apikey".into(),
- })
+ Some(ProviderSettingsView::ApiKey(ApiKeyConfiguration::new(
+ state.api_key_state.has_key(),
+ state.api_key_state.is_from_env_var(),
+ state.api_key_state.env_var_name().clone(),
+ "https://aistudio.google.com/app/apikey".into(),
+ )))
}
- fn set_api_key(&self, key: String, cx: &mut App) -> Task<Result<()>> {
+ fn set_api_key(&self, api_key: Option<String>, cx: &mut App) -> Task<Result<()>> {
self.state
- .update(cx, |state, cx| state.set_api_key(Some(key), cx))
+ .update(cx, |state, cx| state.set_api_key(api_key, cx))
}
}
@@ -388,142 +371,3 @@ impl LanguageModel for GoogleLanguageModel {
async move { Ok(future.await?.boxed()) }.boxed()
}
}
-
-struct ConfigurationView {
- api_key_editor: Entity<InputField>,
- state: Entity<State>,
- target_agent: language_model::ConfigurationViewTargetAgent,
- load_credentials_task: Option<Task<()>>,
-}
-
-impl ConfigurationView {
- fn new(
- state: Entity<State>,
- target_agent: language_model::ConfigurationViewTargetAgent,
- window: &mut Window,
- cx: &mut Context<Self>,
- ) -> Self {
- cx.observe(&state, |_, _, cx| {
- cx.notify();
- })
- .detach();
-
- let load_credentials_task = Some(cx.spawn_in(window, {
- let state = state.clone();
- async move |this, cx| {
- if let Some(task) = Some(state.update(cx, |state, cx| state.authenticate(cx))) {
- // We don't log an error, because "not signed in" is also an error.
- let _ = task.await;
- }
- this.update(cx, |this, cx| {
- this.load_credentials_task = None;
- cx.notify();
- })
- .log_err();
- }
- }));
-
- Self {
- api_key_editor: cx.new(|cx| InputField::new(window, cx, "AIzaSy...")),
- target_agent,
- state,
- load_credentials_task,
- }
- }
-
- fn save_api_key(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
- let api_key = self.api_key_editor.read(cx).text(cx).trim().to_string();
- if api_key.is_empty() {
- return;
- }
-
- // url changes can cause the editor to be displayed again
- self.api_key_editor
- .update(cx, |editor, cx| editor.set_text("", window, cx));
-
- let state = self.state.clone();
- cx.spawn_in(window, async move |_, cx| {
- state
- .update(cx, |state, cx| state.set_api_key(Some(api_key), cx))
- .await
- })
- .detach_and_log_err(cx);
- }
-
- fn reset_api_key(&mut self, window: &mut Window, cx: &mut Context<Self>) {
- self.api_key_editor
- .update(cx, |editor, cx| editor.set_text("", window, cx));
-
- let state = self.state.clone();
- cx.spawn_in(window, async move |_, cx| {
- state
- .update(cx, |state, cx| state.set_api_key(None, cx))
- .await
- })
- .detach_and_log_err(cx);
- }
-
- fn should_render_editor(&self, cx: &mut Context<Self>) -> bool {
- !self.state.read(cx).is_authenticated()
- }
-}
-
-impl Render for ConfigurationView {
- fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
- let env_var_set = self.state.read(cx).api_key_state.is_from_env_var();
- let configured_card_label = if env_var_set {
- format!(
- "API key set in {} environment variable",
- API_KEY_ENV_VAR.name
- )
- } else {
- let api_url = GoogleLanguageModelProvider::api_url(cx);
- if api_url == google_ai::API_URL {
- "API key configured".to_string()
- } else {
- format!("API key configured for {}", api_url)
- }
- };
-
- if self.load_credentials_task.is_some() {
- div()
- .child(Label::new("Loading credentials..."))
- .into_any_element()
- } else if self.should_render_editor(cx) {
- v_flex()
- .size_full()
- .on_action(cx.listener(Self::save_api_key))
- .child(Label::new(format!("To use {}, you need to add an API key. Follow these steps:", match &self.target_agent {
- ConfigurationViewTargetAgent::ZedAgent => "Zed's agent with Google AI".into(),
- ConfigurationViewTargetAgent::Other(agent) => agent.clone(),
- })))
- .child(
- List::new()
- .child(
- ListBulletItem::new("")
- .child(Label::new("Create one by visiting"))
- .child(ButtonLink::new("Google AI's console", "https://aistudio.google.com/app/apikey"))
- )
- .child(
- ListBulletItem::new("Paste your API key below and hit enter to start using the agent")
- )
- )
- .child(self.api_key_editor.clone())
- .child(
- Label::new(
- format!("You can also set the {GEMINI_API_KEY_VAR_NAME} environment variable and restart Zed."),
- )
- .size(LabelSize::Small).color(Color::Muted),
- )
- .into_any_element()
- } else {
- ConfiguredApiCard::new("google-reset-key", configured_card_label)
- .disabled(env_var_set)
- .on_click(cx.listener(|this, _, window, cx| this.reset_api_key(window, cx)))
- .when(env_var_set, |this| {
- this.tooltip_label(format!("To reset your API key, make sure {GEMINI_API_KEY_VAR_NAME} and {GOOGLE_AI_API_KEY_VAR_NAME} environment variables are unset."))
- })
- .into_any_element()
- }
- }
-}
diff --git a/crates/language_models/src/provider/llama_cpp.rs b/crates/language_models/src/provider/llama_cpp.rs
index ed207d4b47b..19f0e9f2962 100644
--- a/crates/language_models/src/provider/llama_cpp.rs
+++ b/crates/language_models/src/provider/llama_cpp.rs
@@ -4,7 +4,7 @@ use credentials_provider::CredentialsProvider;
use fs::Fs;
use futures::Stream;
use futures::{FutureExt, StreamExt, future::BoxFuture, stream::BoxStream};
-use gpui::{AnyView, App, AsyncApp, Context, Entity, Task, TaskExt};
+use gpui::{App, AsyncApp, Context, Entity, Task, TaskExt};
use http_client::{CustomHeaders, HttpClient};
use language_model::util::parse_tool_arguments;
use language_model::{
@@ -12,8 +12,8 @@ use language_model::{
LanguageModelCompletionError, LanguageModelCompletionEvent, LanguageModelId, LanguageModelName,
LanguageModelProvider, LanguageModelProviderId, LanguageModelProviderName,
LanguageModelProviderState, LanguageModelRequest, LanguageModelToolChoice,
- LanguageModelToolResultContent, LanguageModelToolUse, MessageContent, RateLimiter, Role,
- StopReason, TokenUsage, env_var,
+ LanguageModelToolResultContent, LanguageModelToolUse, MessageContent, ProviderSettingsView,
+ RateLimiter, Role, StopReason, SubPageProviderSettings, TokenUsage, env_var,
};
use llama_cpp::{
LLAMA_CPP_API_URL, ModelEntry, Props, get_models, get_props, stream_chat_completion,
@@ -562,12 +562,6 @@ impl LanguageModelProvider for LlamaCppLanguageModelProvider {
None
}
- fn inline_description(&self, _cx: &App) -> Option<InlineDescription> {
- Some(InlineDescription::Text(
- "Run local models on your machine with LlamaCpp.".into(),
- ))
- }
-
fn provided_models(&self, cx: &App) -> Vec<Arc<dyn LanguageModel>> {
let settings = LlamaCppLanguageModelProvider::settings(cx);
let effective = compute_effective_models(&self.state.read(cx).fetched_models, settings);
@@ -603,20 +597,17 @@ impl LanguageModelProvider for LlamaCppLanguageModelProvider {
self.state.update(cx, |state, cx| state.authenticate(cx))
}
- fn configuration_view(
- &self,
- _target_agent: language_model::ConfigurationViewTargetAgent,
- window: &mut Window,
- cx: &mut App,
- ) -> AnyView {
+ fn settings_view(&self, _cx: &mut App) -> Option<ProviderSettingsView> {
let state = self.state.clone();
- cx.new(|cx| ConfigurationView::new(state, window, cx))
- .into()
- }
-
- fn reset_credentials(&self, cx: &mut App) -> Task<Result<()>> {
- self.state
- .update(cx, |state, cx| state.set_api_key(None, cx))
+ Some(ProviderSettingsView::SubPage(
+ SubPageProviderSettings::new(move |window, cx| {
+ cx.new(|cx| ConfigurationView::new(state.clone(), window, cx))
+ .into()
+ })
+ .description(InlineDescription::Text(
+ "Run local models on your machine with LlamaCpp.".into(),
+ )),
+ ))
}
}
diff --git a/crates/language_models/src/provider/lmstudio.rs b/crates/language_models/src/provider/lmstudio.rs
index 362db21070e..3f6e9fb46e2 100644
--- a/crates/language_models/src/provider/lmstudio.rs
+++ b/crates/language_models/src/provider/lmstudio.rs
@@ -3,7 +3,7 @@ use credentials_provider::CredentialsProvider;
use fs::Fs;
use futures::Stream;
use futures::{FutureExt, StreamExt, future::BoxFuture, stream::BoxStream};
-use gpui::{AnyView, App, AsyncApp, Context, Entity, Subscription, Task, TaskExt};
+use gpui::{App, AsyncApp, Context, Entity, Subscription, Task, TaskExt};
use http_client::{CustomHeaders, HttpClient};
use language_model::{
ApiKeyState, AuthenticateError, EnvVar, IconOrSvg, LanguageModel, LanguageModelCompletionError,
@@ -13,7 +13,7 @@ use language_model::{
use language_model::{
InlineDescription, LanguageModelId, LanguageModelName, LanguageModelProvider,
LanguageModelProviderId, LanguageModelProviderName, LanguageModelProviderState,
- LanguageModelRequest, RateLimiter, Role,
+ LanguageModelRequest, ProviderSettingsView, RateLimiter, Role, SubPageProviderSettings,
};
use lmstudio::{LMSTUDIO_API_URL, ModelType, get_models};
@@ -252,12 +252,6 @@ impl LanguageModelProvider for LmStudioLanguageModelProvider {
IconOrSvg::Icon(IconName::AiLmStudio)
}
- fn inline_description(&self, _cx: &App) -> Option<InlineDescription> {
- Some(InlineDescription::Text(
- "Run local LLMs like Llama, Phi, and Qwen with LM Studio.".into(),
- ))
- }
-
fn default_model(&self, _: &App) -> Option<Arc<dyn LanguageModel>> {
// We shouldn't try to select default model, because it might lead to a load call for an unloaded model.
// In a constrained environment where user might not have enough resources it'll be a bad UX to select something
@@ -318,19 +312,17 @@ impl LanguageModelProvider for LmStudioLanguageModelProvider {
self.state.update(cx, |state, cx| state.authenticate(cx))
}
- fn configuration_view(
- &self,
- _target_agent: language_model::ConfigurationViewTargetAgent,
- _window: &mut Window,
- cx: &mut App,
- ) -> AnyView {
- cx.new(|cx| ConfigurationView::new(self.state.clone(), _window, cx))
- .into()
- }
-
- fn reset_credentials(&self, cx: &mut App) -> Task<Result<()>> {
- self.state
- .update(cx, |state, cx| state.set_api_key(None, cx))
+ fn settings_view(&self, _cx: &mut App) -> Option<ProviderSettingsView> {
+ let state = self.state.clone();
+ Some(ProviderSettingsView::SubPage(
+ SubPageProviderSettings::new(move |window, cx| {
+ cx.new(|cx| ConfigurationView::new(state.clone(), window, cx))
+ .into()
+ })
+ .description(InlineDescription::Text(
+ "Run local LLMs like Llama, Phi, and Qwen with LM Studio.".into(),
+ )),
+ ))
}
}
diff --git a/crates/language_models/src/provider/mistral.rs b/crates/language_models/src/provider/mistral.rs
index de9f385c8e5..f12f33a6f35 100644
--- a/crates/language_models/src/provider/mistral.rs
+++ b/crates/language_models/src/provider/mistral.rs
@@ -3,15 +3,15 @@ use collections::{BTreeMap, HashMap};
use credentials_provider::CredentialsProvider;
use futures::{FutureExt, Stream, StreamExt, future::BoxFuture, stream::BoxStream};
-use gpui::{AnyView, App, AsyncApp, Context, Entity, Global, SharedString, Task, TaskExt, Window};
+use gpui::{App, AppContext, AsyncApp, Context, Entity, Global, SharedString, Task};
use http_client::{CustomHeaders, HttpClient};
use language_model::{
ApiKeyConfiguration, ApiKeyState, AuthenticateError, EnvVar, IconOrSvg, LanguageModel,
LanguageModelCompletionError, LanguageModelCompletionEvent, LanguageModelId, LanguageModelName,
LanguageModelProvider, LanguageModelProviderId, LanguageModelProviderName,
LanguageModelProviderState, LanguageModelRequest, LanguageModelToolChoice,
- LanguageModelToolResultContent, LanguageModelToolUse, MessageContent, RateLimiter, Role,
- StopReason, TokenUsage, env_var,
+ LanguageModelToolResultContent, LanguageModelToolUse, MessageContent, ProviderSettingsView,
+ RateLimiter, Role, StopReason, TokenUsage, env_var,
};
pub use mistral::{MISTRAL_API_URL, StreamResponse};
pub use settings::MistralAvailableModel as AvailableModel;
@@ -19,9 +19,7 @@ use settings::{Settings, SettingsStore};
use std::pin::Pin;
use std::sync::{Arc, LazyLock};
use strum::IntoEnumIterator;
-use ui::{ButtonLink, ConfiguredApiCard, List, ListBulletItem, prelude::*};
-use ui_input::InputField;
-use util::ResultExt;
+use ui::IconName;
use language_model::util::{fix_streamed_json, parse_tool_arguments};
@@ -222,34 +220,19 @@ impl LanguageModelProvider for MistralLanguageModelProvider {
self.state.update(cx, |state, cx| state.authenticate(cx))
}
- fn configuration_view(
- &self,
- _target_agent: language_model::ConfigurationViewTargetAgent,
- window: &mut Window,
- cx: &mut App,
- ) -> AnyView {
- cx.new(|cx| ConfigurationView::new(self.state.clone(), window, cx))
- .into()
- }
-
- fn reset_credentials(&self, cx: &mut App) -> Task<Result<()>> {
- self.state
- .update(cx, |state, cx| state.set_api_key(None, cx))
- }
-
- fn api_key_configuration(&self, cx: &App) -> Option<ApiKeyConfiguration> {
+ fn settings_view(&self, cx: &mut App) -> Option<ProviderSettingsView> {
let state = self.state.read(cx);
- Some(ApiKeyConfiguration {
- has_key: state.api_key_state.has_key(),
- is_from_env_var: state.api_key_state.is_from_env_var(),
- env_var_name: state.api_key_state.env_var_name().clone(),
- api_key_url: "https://console.mistral.ai/api-keys".into(),
- })
+ Some(ProviderSettingsView::ApiKey(ApiKeyConfiguration::new(
+ state.api_key_state.has_key(),
+ state.api_key_state.is_from_env_var(),
+ state.api_key_state.env_var_name().clone(),
+ "https://console.mistral.ai/api-keys".into(),
+ )))
}
- fn set_api_key(&self, key: String, cx: &mut App) -> Task<Result<()>> {
+ fn set_api_key(&self, api_key: Option<String>, cx: &mut App) -> Task<Result<()>> {
self.state
- .update(cx, |state, cx| state.set_api_key(Some(key), cx))
+ .update(cx, |state, cx| state.set_api_key(api_key, cx))
}
}
@@ -765,145 +748,6 @@ struct RawToolCall {
arguments: String,
}
-struct ConfigurationView {
- api_key_editor: Entity<InputField>,
- state: Entity<State>,
- load_credentials_task: Option<Task<()>>,
-}
-
-impl ConfigurationView {
- fn new(state: Entity<State>, window: &mut Window, cx: &mut Context<Self>) -> Self {
- let api_key_editor =
- cx.new(|cx| InputField::new(window, cx, "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"));
-
- cx.observe(&state, |_, _, cx| {
- cx.notify();
- })
- .detach();
-
- let load_credentials_task = Some(cx.spawn_in(window, {
- let state = state.clone();
- async move |this, cx| {
- if let Some(task) = Some(state.update(cx, |state, cx| state.authenticate(cx))) {
- // We don't log an error, because "not signed in" is also an error.
- let _ = task.await;
- }
-
- this.update(cx, |this, cx| {
- this.load_credentials_task = None;
- cx.notify();
- })
- .log_err();
- }
- }));
-
- Self {
- api_key_editor,
- state,
- load_credentials_task,
- }
- }
-
- fn save_api_key(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
- let api_key = self.api_key_editor.read(cx).text(cx).trim().to_string();
- if api_key.is_empty() {
- return;
- }
-
- // url changes can cause the editor to be displayed again
- self.api_key_editor
- .update(cx, |editor, cx| editor.set_text("", window, cx));
-
- let state = self.state.clone();
- cx.spawn_in(window, async move |_, cx| {
- state
- .update(cx, |state, cx| state.set_api_key(Some(api_key), cx))
- .await
- })
- .detach_and_log_err(cx);
- }
-
- fn reset_api_key(&mut self, window: &mut Window, cx: &mut Context<Self>) {
- self.api_key_editor
- .update(cx, |editor, cx| editor.set_text("", window, cx));
-
- let state = self.state.clone();
- cx.spawn_in(window, async move |_, cx| {
- state
- .update(cx, |state, cx| state.set_api_key(None, cx))
- .await
- })
- .detach_and_log_err(cx);
- }
-
- fn should_render_api_key_editor(&self, cx: &mut Context<Self>) -> bool {
- !self.state.read(cx).is_authenticated()
- }
-}
-
-impl Render for ConfigurationView {
- fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
- let env_var_set = self.state.read(cx).api_key_state.is_from_env_var();
- let configured_card_label = if env_var_set {
- format!("API key set in {API_KEY_ENV_VAR_NAME} environment variable")
- } else {
- let api_url = MistralLanguageModelProvider::api_url(cx);
- if api_url == MISTRAL_API_URL {
- "API key configured".to_string()
- } else {
- format!("API key configured for {}", api_url)
- }
- };
-
- if self.load_credentials_task.is_some() {
- div().child(Label::new("Loading credentials...")).into_any()
- } else if self.should_render_api_key_editor(cx) {
- v_flex()
- .size_full()
- .on_action(cx.listener(Self::save_api_key))
- .child(Label::new("To use Zed's agent with Mistral, you need to add an API key. Follow these steps:"))
- .child(
- List::new()
- .child(
- ListBulletItem::new("")
- .child(Label::new("Create one by visiting"))
- .child(ButtonLink::new("Mistral's console", "https://console.mistral.ai/api-keys"))
- )
- .child(
- ListBulletItem::new("Ensure your Mistral account has credits")
- )
- .child(
- ListBulletItem::new("Paste your API key below and hit enter to start using the assistant")
- ),
- )
- .child(self.api_key_editor.clone())
- .child(
- Label::new(
- format!("You can also set the {API_KEY_ENV_VAR_NAME} environment variable and restart Zed."),
- )
- .size(LabelSize::Small).color(Color::Muted),
- )
- .into_any()
- } else {
- v_flex()
- .size_full()
- .gap_1()
- .child(
- ConfiguredApiCard::new("mistral-reset-key", configured_card_label)
- .disabled(env_var_set)
- .on_click(cx.listener(|this, _, window, cx| this.reset_api_key(window, cx)))
- .when(env_var_set, |this| {
- this.tooltip_label(format!(
- "To reset your API key, \
- unset the {API_KEY_ENV_VAR_NAME} environment variable."
- ))
- }),
- )
- .into_any()
- }
- }
-}
-
#[cfg(test)]
mod tests {
use super::*;
diff --git a/crates/language_models/src/provider/ollama.rs b/crates/language_models/src/provider/ollama.rs
index 7bbc2ec18cd..f0166c6afb1 100644
--- a/crates/language_models/src/provider/ollama.rs
+++ b/crates/language_models/src/provider/ollama.rs
@@ -4,7 +4,7 @@ use credentials_provider::CredentialsProvider;
use fs::Fs;
use futures::{FutureExt, StreamExt, future::BoxFuture, stream::BoxStream};
use futures::{Stream, TryFutureExt, stream};
-use gpui::{AnyView, App, AsyncApp, Context, Entity, Task, TaskExt};
+use gpui::{App, AsyncApp, Context, Entity, Task, TaskExt};
use http_client::{CustomHeaders, HttpClient};
use language_model::{
ApiKeyState, AuthenticateError, DisabledReason, EnvVar, IconOrSvg, InlineDescription,
@@ -12,7 +12,8 @@ use language_model::{
LanguageModelName, LanguageModelProvider, LanguageModelProviderId, LanguageModelProviderName,
LanguageModelProviderState, LanguageModelRequest, LanguageModelRequestTool,
LanguageModelToolChoice, LanguageModelToolUse, LanguageModelToolUseId, MessageContent,
- RateLimiter, Role, StopReason, TokenUsage, env_var,
+ ProviderSettingsView, RateLimiter, Role, StopReason, SubPageProviderSettings, TokenUsage,
+ env_var,
};
use menu;
use ollama::{
@@ -276,12 +277,6 @@ impl LanguageModelProvider for OllamaLanguageModelProvider {
IconOrSvg::Icon(IconName::AiOllama)
}
- fn inline_description(&self, _cx: &App) -> Option<InlineDescription> {
- Some(InlineDescription::Text(
- "Run local models on your machine with Ollama.".into(),
- ))
- }
-
fn default_model(&self, _: &App) -> Option<Arc<dyn LanguageModel>> {
// We shouldn't try to select default model, because it might lead to a load call for an unloaded model.
// In a constrained environment where user might not have enough resources it'll be a bad UX to select something
@@ -341,20 +336,17 @@ impl LanguageModelProvider for OllamaLanguageModelProvider {
self.state.update(cx, |state, cx| state.authenticate(cx))
}
- fn configuration_view(
- &self,
- _target_agent: language_model::ConfigurationViewTargetAgent,
- window: &mut Window,
- cx: &mut App,
- ) -> AnyView {
+ fn settings_view(&self, _cx: &mut App) -> Option<ProviderSettingsView> {
let state = self.state.clone();
- cx.new(|cx| ConfigurationView::new(state, window, cx))
- .into()
- }
-
- fn reset_credentials(&self, cx: &mut App) -> Task<Result<()>> {
- self.state
- .update(cx, |state, cx| state.set_api_key(None, cx))
+ Some(ProviderSettingsView::SubPage(
+ SubPageProviderSettings::new(move |window, cx| {
+ cx.new(|cx| ConfigurationView::new(state.clone(), window, cx))
+ .into()
+ })
+ .description(InlineDescription::Text(
+ "Run local models on your machine with Ollama.".into(),
+ )),
+ ))
}
}
diff --git a/crates/language_models/src/provider/open_ai.rs b/crates/language_models/src/provider/open_ai.rs
index 87be0e2751b..c2c74a8553b 100644
--- a/crates/language_models/src/provider/open_ai.rs
+++ b/crates/language_models/src/provider/open_ai.rs
@@ -2,7 +2,7 @@ use anyhow::Result;
use collections::BTreeMap;
use credentials_provider::CredentialsProvider;
use futures::{FutureExt, StreamExt, future::BoxFuture};
-use gpui::{AnyView, App, AsyncApp, Context, Entity, SharedString, Task, TaskExt, Window};
+use gpui::{App, AppContext, AsyncApp, Context, Entity, SharedString, Task};
use http_client::{CustomHeaders, HttpClient};
use language_model::{
ApiKeyConfiguration, ApiKeyState, AuthenticateError, EnvVar, FastModeConfirmation, IconOrSvg,
@@ -10,20 +10,17 @@ use language_model::{
LanguageModelEffortLevel, LanguageModelId, LanguageModelName, LanguageModelProvider,
LanguageModelProviderId, LanguageModelProviderName, LanguageModelProviderState,
LanguageModelRequest, LanguageModelToolChoice, OPEN_AI_PROVIDER_ID, OPEN_AI_PROVIDER_NAME,
- RateLimiter, env_var,
+ ProviderSettingsView, RateLimiter, env_var,
};
-use menu;
use open_ai::{
- OPEN_AI_API_URL, ResponseStreamEvent,
+ ResponseStreamEvent,
responses::{Request as ResponseRequest, StreamEvent as ResponsesStreamEvent, stream_response},
stream_completion,
};
use settings::{OpenAiAvailableModel as AvailableModel, Settings, SettingsStore};
use std::sync::{Arc, LazyLock};
use strum::IntoEnumIterator;
-use ui::{ButtonLink, ConfiguredApiCard, List, ListBulletItem, prelude::*};
-use ui_input::InputField;
-use util::ResultExt;
+use ui::IconName;
pub use open_ai::completion::{
ChatCompletionMaxTokensParameter, OpenAiEventMapper, OpenAiResponseEventMapper, into_open_ai,
@@ -204,34 +201,19 @@ impl LanguageModelProvider for OpenAiLanguageModelProvider {
self.state.update(cx, |state, cx| state.authenticate(cx))
}
- fn configuration_view(
- &self,
- _target_agent: language_model::ConfigurationViewTargetAgent,
- window: &mut Window,
- cx: &mut App,
- ) -> AnyView {
- cx.new(|cx| ConfigurationView::new(self.state.clone(), window, cx))
- .into()
- }
-
- fn reset_credentials(&self, cx: &mut App) -> Task<Result<()>> {
- self.state
- .update(cx, |state, cx| state.set_api_key(None, cx))
- }
-
- fn api_key_configuration(&self, cx: &App) -> Option<ApiKeyConfiguration> {
+ fn settings_view(&self, cx: &mut App) -> Option<ProviderSettingsView> {
let state = self.state.read(cx);
- Some(ApiKeyConfiguration {
- has_key: state.api_key_state.has_key(),
- is_from_env_var: state.api_key_state.is_from_env_var(),
- env_var_name: state.api_key_state.env_var_name().clone(),
- api_key_url: "https://platform.openai.com/api-keys".into(),
- })
+ Some(ProviderSettingsView::ApiKey(ApiKeyConfiguration::new(
+ state.api_key_state.has_key(),
+ state.api_key_state.is_from_env_var(),
+ state.api_key_state.env_var_name().clone(),
+ "https://platform.openai.com/api-keys".into(),
+ )))
}
- fn set_api_key(&self, key: String, cx: &mut App) -> Task<Result<()>> {
+ fn set_api_key(&self, api_key: Option<String>, cx: &mut App) -> Task<Result<()>> {
self.state
- .update(cx, |state, cx| state.set_api_key(Some(key), cx))
+ .update(cx, |state, cx| state.set_api_key(api_key, cx))
}
fn fast_mode_confirmation(&self, _cx: &App) -> Option<FastModeConfirmation> {
@@ -590,183 +572,3 @@ impl LanguageModel for OpenAiLanguageModel {
}
}
}
-
-struct ConfigurationView {
- api_key_editor: Entity<InputField>,
- state: Entity<State>,
- load_credentials_task: Option<Task<()>>,
-}
-
-impl ConfigurationView {
- fn new(state: Entity<State>, window: &mut Window, cx: &mut Context<Self>) -> Self {
- let api_key_editor = cx.new(|cx| {
- InputField::new(
- window,
- cx,
- "sk-000000000000000000000000000000000000000000000000",
- )
- });
-
- cx.observe(&state, |_, _, cx| {
- cx.notify();
- })
- .detach();
-
- let load_credentials_task = Some(cx.spawn_in(window, {
- let state = state.clone();
- async move |this, cx| {
- if let Some(task) = Some(state.update(cx, |state, cx| state.authenticate(cx))) {
- // We don't log an error, because "not signed in" is also an error.
- let _ = task.await;
- }
- this.update(cx, |this, cx| {
- this.load_credentials_task = None;
- cx.notify();
- })
- .log_err();
- }
- }));
-
- Self {
- api_key_editor,
- state,
- load_credentials_task,
- }
- }
-
- fn save_api_key(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
- let api_key = self.api_key_editor.read(cx).text(cx).trim().to_string();
- if api_key.is_empty() {
- return;
- }
-
- // url changes can cause the editor to be displayed again
- self.api_key_editor
- .update(cx, |editor, cx| editor.set_text("", window, cx));
-
- let state = self.state.clone();
- cx.spawn_in(window, async move |_, cx| {
- state
- .update(cx, |state, cx| state.set_api_key(Some(api_key), cx))
- .await
- })
- .detach_and_log_err(cx);
- }
-
- fn reset_api_key(&mut self, window: &mut Window, cx: &mut Context<Self>) {
- self.api_key_editor
- .update(cx, |input, cx| input.set_text("", window, cx));
-
- let state = self.state.clone();
- cx.spawn_in(window, async move |_, cx| {
- state
- .update(cx, |state, cx| state.set_api_key(None, cx))
- .await
- })
- .detach_and_log_err(cx);
- }
-
- fn should_render_editor(&self, cx: &mut Context<Self>) -> bool {
- !self.state.read(cx).is_authenticated()
- }
-}
-
-impl Render for ConfigurationView {
- fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
- let env_var_set = self.state.read(cx).api_key_state.is_from_env_var();
- let configured_card_label = if env_var_set {
- format!("API key set in {API_KEY_ENV_VAR_NAME} environment variable")
- } else {
- let api_url = OpenAiLanguageModelProvider::api_url(cx);
- if api_url == OPEN_AI_API_URL {
- "API key configured".to_string()
- } else {
- format!("API key configured for {}", api_url)
- }
- };
-
- let api_key_section = if self.should_render_editor(cx) {
- v_flex()
- .on_action(cx.listener(Self::save_api_key))
- .child(Label::new("To use Zed's agent with OpenAI, you need to add an API key. Follow these steps:"))
- .child(
- List::new()
- .child(
- ListBulletItem::new("")
- .child(Label::new("Create one by visiting"))
- .child(ButtonLink::new("OpenAI's console", "https://platform.openai.com/api-keys"))
- )
- .child(
- ListBulletItem::new("Ensure your OpenAI account has credits")
- )
- .child(
- ListBulletItem::new("Paste your API key below and hit enter to start using the agent")
- ),
- )
- .child(self.api_key_editor.clone())
- .child(
- Label::new(format!(
- "You can also set the {API_KEY_ENV_VAR_NAME} environment variable and restart Zed."
- ))
- .size(LabelSize::Small)
- .color(Color::Muted),
- )
- .child(
- Label::new(
- "Note that having a subscription for another service like GitHub Copilot won't work.",
- )
- .size(LabelSize::Small).color(Color::Muted),
- )
- .into_any_element()
- } else {
- ConfiguredApiCard::new("openai-reset-key", configured_card_label)
- .disabled(env_var_set)
- .on_click(cx.listener(|this, _, window, cx| this.reset_api_key(window, cx)))
- .when(env_var_set, |this| {
- this.tooltip_label(format!("To reset your API key, unset the {API_KEY_ENV_VAR_NAME} environment variable."))
- })
- .into_any_element()
- };
-
- let compatible_api_section = h_flex()
- .mt_1p5()
- .gap_0p5()
- .flex_wrap()
- .when(self.should_render_editor(cx), |this| {
- this.pt_1p5()
- .border_t_1()
- .border_color(cx.theme().colors().border_variant)
- })
- .child(
- h_flex()
- .gap_2()
- .child(
- Icon::new(IconName::Info)
- .size(IconSize::XSmall)
- .color(Color::Muted),
- )
- .child(Label::new("Zed also supports OpenAI-compatible models.")),
- )
- .child(
- Button::new("docs", "Learn More")
- .end_icon(
- Icon::new(IconName::ArrowUpRight)
- .size(IconSize::Small)
- .color(Color::Muted),
- )
- .on_click(move |_, _window, cx| {
- cx.open_url("https://zed.dev/docs/ai/llm-providers#openai-api-compatible")
- }),
- );
-
- if self.load_credentials_task.is_some() {
- div().child(Label::new("Loading credentials…")).into_any()
- } else {
- v_flex()
- .size_full()
- .child(api_key_section)
- .child(compatible_api_section)
- .into_any()
- }
- }
-}
diff --git a/crates/language_models/src/provider/open_ai_compatible.rs b/crates/language_models/src/provider/open_ai_compatible.rs
index e0c6f1f16ea..e69e847eab9 100644
--- a/crates/language_models/src/provider/open_ai_compatible.rs
+++ b/crates/language_models/src/provider/open_ai_compatible.rs
@@ -1,14 +1,14 @@
use anyhow::Result;
use credentials_provider::CredentialsProvider;
use futures::{FutureExt, StreamExt, future::BoxFuture};
-use gpui::{AnyView, App, AppContext, AsyncApp, Entity, Task, Window};
+use gpui::{App, AppContext, AsyncApp, Entity, Task};
use http_client::{CustomHeaders, HttpClient};
use language_model::{
AuthenticateError, IconOrSvg, LanguageModel, LanguageModelCompletionError,
LanguageModelCompletionEvent, LanguageModelEffortLevel, LanguageModelId, LanguageModelName,
LanguageModelProvider, LanguageModelProviderId, LanguageModelProviderName,
LanguageModelProviderState, LanguageModelRequest, LanguageModelToolChoice,
- LanguageModelToolSchemaFormat, RateLimiter,
+ LanguageModelToolSchemaFormat, ProviderSettingsView, RateLimiter, SubPageProviderSettings,
};
use open_ai::{
ResponseStreamEvent,
@@ -144,32 +144,27 @@ impl LanguageModelProvider for OpenAiCompatibleLanguageModelProvider {
self.state.update(cx, |state, cx| state.authenticate(cx))
}
- fn configuration_view(
- &self,
- _target_agent: language_model::ConfigurationViewTargetAgent,
- window: &mut Window,
- cx: &mut App,
- ) -> AnyView {
- cx.new(|cx| {
- ApiCompatibleProviderConfigurationView::new(
- self.state.clone(),
- "OpenAI",
- API_KEY_PLACEHOLDER,
- window,
- cx,
- )
- })
- .into()
- }
-
- fn set_api_key(&self, key: String, cx: &mut App) -> Task<Result<()>> {
- self.state
- .update(cx, |state, cx| state.set_api_key(Some(key), cx))
+ fn settings_view(&self, _cx: &mut App) -> Option<ProviderSettingsView> {
+ let state = self.state.clone();
+ Some(ProviderSettingsView::SubPage(SubPageProviderSettings::new(
+ move |window, cx| {
+ cx.new(|cx| {
+ ApiCompatibleProviderConfigurationView::new(
+ state.clone(),
+ "OpenAI",
+ API_KEY_PLACEHOLDER,
+ window,
+ cx,
+ )
+ })
+ .into()
+ },
+ )))
}
- fn reset_credentials(&self, cx: &mut App) -> Task<Result<()>> {
+ fn set_api_key(&self, api_key: Option<String>, cx: &mut App) -> Task<Result<()>> {
self.state
- .update(cx, |state, cx| state.set_api_key(None, cx))
+ .update(cx, |state, cx| state.set_api_key(api_key, cx))
}
}
diff --git a/crates/language_models/src/provider/open_router.rs b/crates/language_models/src/provider/open_router.rs
index f41e04972d0..fd5221c9b7c 100644
--- a/crates/language_models/src/provider/open_router.rs
+++ b/crates/language_models/src/provider/open_router.rs
@@ -2,7 +2,7 @@ use anyhow::Result;
use collections::HashMap;
use credentials_provider::CredentialsProvider;
use futures::{FutureExt, Stream, StreamExt, future::BoxFuture};
-use gpui::{AnyView, App, AsyncApp, Context, Entity, SharedString, Task, TaskExt};
+use gpui::{App, AppContext, AsyncApp, Context, Entity, SharedString, Task};
use http_client::{CustomHeaders, HttpClient};
use language_model::{
ApiKeyConfiguration, ApiKeyState, AuthenticateError, EnvVar, IconOrSvg, LanguageModel,
@@ -10,7 +10,7 @@ use language_model::{
LanguageModelProvider, LanguageModelProviderId, LanguageModelProviderName,
LanguageModelProviderState, LanguageModelRequest, LanguageModelToolChoice,
LanguageModelToolResultContent, LanguageModelToolSchemaFormat, LanguageModelToolUse,
- MessageContent, RateLimiter, Role, StopReason, TokenUsage, env_var,
+ MessageContent, ProviderSettingsView, RateLimiter, Role, StopReason, TokenUsage, env_var,
};
use open_router::{
Model, ModelMode as OpenRouterModelMode, OPEN_ROUTER_API_URL, ResponseStreamEvent, list_models,
@@ -18,9 +18,7 @@ use open_router::{
use settings::{OpenRouterAvailableModel as AvailableModel, Settings, SettingsStore};
use std::pin::Pin;
use std::sync::{Arc, LazyLock};
-use ui::{ButtonLink, ConfiguredApiCard, List, ListBulletItem, prelude::*};
-use ui_input::InputField;
-use util::ResultExt;
+use ui::IconName;
use language_model::util::{fix_streamed_json, parse_tool_arguments};
@@ -259,34 +257,19 @@ impl LanguageModelProvider for OpenRouterLanguageModelProvider {
self.state.update(cx, |state, cx| state.authenticate(cx))
}
- fn configuration_view(
- &self,
- _target_agent: language_model::ConfigurationViewTargetAgent,
- window: &mut Window,
- cx: &mut App,
- ) -> AnyView {
- cx.new(|cx| ConfigurationView::new(self.state.clone(), window, cx))
- .into()
- }
-
- fn reset_credentials(&self, cx: &mut App) -> Task<Result<()>> {
- self.state
- .update(cx, |state, cx| state.set_api_key(None, cx))
- }
-
- fn api_key_configuration(&self, cx: &App) -> Option<ApiKeyConfiguration> {
+ fn settings_view(&self, cx: &mut App) -> Option<ProviderSettingsView> {
let state = self.state.read(cx);
- Some(ApiKeyConfiguration {
- has_key: state.api_key_state.has_key(),
- is_from_env_var: state.api_key_state.is_from_env_var(),
- env_var_name: state.api_key_state.env_var_name().clone(),
- api_key_url: "https://openrouter.ai/keys".into(),
- })
+ Some(ProviderSettingsView::ApiKey(ApiKeyConfiguration::new(
+ state.api_key_state.has_key(),
+ state.api_key_state.is_from_env_var(),
+ state.api_key_state.env_var_name().clone(),
+ "https://openrouter.ai/keys".into(),
+ )))
}
- fn set_api_key(&self, key: String, cx: &mut App) -> Task<Result<()>> {
+ fn set_api_key(&self, api_key: Option<String>, cx: &mut App) -> Task<Result<()>> {
self.state
- .update(cx, |state, cx| state.set_api_key(Some(key), cx))
+ .update(cx, |state, cx| state.set_api_key(api_key, cx))
}
}
@@ -886,141 +869,6 @@ struct RawToolCall {
thought_signature: Option<String>,
}
-struct ConfigurationView {
- api_key_editor: Entity<InputField>,
- state: Entity<State>,
- load_credentials_task: Option<Task<()>>,
-}
-
-impl ConfigurationView {
- fn new(state: Entity<State>, window: &mut Window, cx: &mut Context<Self>) -> Self {
- let api_key_editor = cx.new(|cx| {
- InputField::new(
- window,
- cx,
- "sk_or_000000000000000000000000000000000000000000000000",
- )
- });
-
- cx.observe(&state, |_, _, cx| {
- cx.notify();
- })
- .detach();
-
- let load_credentials_task = Some(cx.spawn_in(window, {
- let state = state.clone();
- async move |this, cx| {
- if let Some(task) = Some(state.update(cx, |state, cx| state.authenticate(cx))) {
- let _ = task.await;
- }
-
- this.update(cx, |this, cx| {
- this.load_credentials_task = None;
- cx.notify();
- })
- .log_err();
- }
- }));
-
- Self {
- api_key_editor,
- state,
- load_credentials_task,
- }
- }
-
- fn save_api_key(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
- let api_key = self.api_key_editor.read(cx).text(cx).trim().to_string();
- if api_key.is_empty() {
- return;
- }
-
- // url changes can cause the editor to be displayed again
- self.api_key_editor
- .update(cx, |editor, cx| editor.set_text("", window, cx));
-
- let state = self.state.clone();
- cx.spawn_in(window, async move |_, cx| {
- state
- .update(cx, |state, cx| state.set_api_key(Some(api_key), cx))
- .await
- })
- .detach_and_log_err(cx);
- }
-
- fn reset_api_key(&mut self, window: &mut Window, cx: &mut Context<Self>) {
- self.api_key_editor
- .update(cx, |editor, cx| editor.set_text("", window, cx));
-
- let state = self.state.clone();
- cx.spawn_in(window, async move |_, cx| {
- state
- .update(cx, |state, cx| state.set_api_key(None, cx))
- .await
- })
- .detach_and_log_err(cx);
- }
-
- fn should_render_editor(&self, cx: &mut Context<Self>) -> bool {
- !self.state.read(cx).is_authenticated()
- }
-}
-
-impl Render for ConfigurationView {
- fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
- let env_var_set = self.state.read(cx).api_key_state.is_from_env_var();
- let configured_card_label = if env_var_set {
- format!("API key set in {API_KEY_ENV_VAR_NAME} environment variable")
- } else {
- let api_url = OpenRouterLanguageModelProvider::api_url(cx);
- if api_url == OPEN_ROUTER_API_URL {
- "API key configured".to_string()
- } else {
- format!("API key configured for {}", api_url)
- }
- };
-
- if self.load_credentials_task.is_some() {
- div()
- .child(Label::new("Loading credentials..."))
- .into_any_element()
- } else if self.should_render_editor(cx) {
- v_flex()
- .size_full()
- .on_action(cx.listener(Self::save_api_key))
- .child(Label::new("To use Zed's agent with OpenRouter, you need to add an API key. Follow these steps:"))
- .child(
- List::new()
- .child(
- ListBulletItem::new("")
- .child(Label::new("Create an API key by visiting"))
- .child(ButtonLink::new("OpenRouter's console", "https://openrouter.ai/keys"))
- )
- .child(ListBulletItem::new("Ensure your OpenRouter account has credits")
- )
- .child(ListBulletItem::new("Paste your API key below and hit enter to start using the assistant")
- ),
- )
- .child(self.api_key_editor.clone())
- .child(
- Label::new(
- format!("You can also set the {API_KEY_ENV_VAR_NAME} environment variable and restart Zed."),
- )
- .size(LabelSize::Small).color(Color::Muted),
- )
- .into_any_element()
- } else {
- ConfiguredApiCard::new("openrouter-reset-key", configured_card_label)
- .disabled(env_var_set)
- .on_click(cx.listener(|this, _, window, cx| this.reset_api_key(window, cx)))
- .when(env_var_set, |this| {
- this.tooltip_label(format!("To reset your API key, unset the {API_KEY_ENV_VAR_NAME} environment variable."))
- })
- .into_any_element()
- }
- }
-}
-
#[cfg(test)]
mod tests {
use super::*;
diff --git a/crates/language_models/src/provider/openai_subscribed.rs b/crates/language_models/src/provider/openai_subscribed.rs
index 2b09032ca51..20038e61234 100644
--- a/crates/language_models/src/provider/openai_subscribed.rs
+++ b/crates/language_models/src/provider/openai_subscribed.rs
@@ -3,7 +3,7 @@ use base64::Engine as _;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use credentials_provider::CredentialsProvider;
use futures::{FutureExt, StreamExt, future::BoxFuture, future::Shared};
-use gpui::{AnyView, App, AsyncApp, Context, Entity, SharedString, Task, Window};
+use gpui::{App, AsyncApp, Context, Entity, SharedString, Task, Window};
use http_client::{
AsyncBody, CustomHeaders, HttpClient, Method, Request as HttpRequest,
http::{HeaderName, HeaderValue},
@@ -13,7 +13,7 @@ use language_model::{
LanguageModelCompletionError, LanguageModelCompletionEvent, LanguageModelEffortLevel,
LanguageModelId, LanguageModelName, LanguageModelProvider, LanguageModelProviderId,
LanguageModelProviderName, LanguageModelProviderState, LanguageModelRequest,
- LanguageModelToolChoice, ProviderConfigurationView, RateLimiter,
+ LanguageModelToolChoice, ProviderSettingsView, RateLimiter,
};
use open_ai::{ReasoningEffort, responses::stream_response};
use rand::RngCore as _;
@@ -157,10 +157,6 @@ impl OpenAiSubscribedProvider {
});
}
- fn sign_out(&self, cx: &mut App) -> Task<Result<()>> {
- do_sign_out(&self.state.downgrade(), cx)
- }
-
fn create_language_model(&self, model: ChatGptModel) -> Arc<dyn LanguageModel> {
Arc::new(OpenAiSubscribedLanguageModel {
id: LanguageModelId::from(model.id().to_string()),
@@ -243,71 +239,48 @@ impl LanguageModelProvider for OpenAiSubscribedProvider {
}
}
- fn configuration_view(
- &self,
- _target_agent: language_model::ConfigurationViewTargetAgent,
- _window: &mut Window,
- cx: &mut App,
- ) -> AnyView {
- let state = self.state.clone();
- let http_client = self.http_client.clone();
- cx.new(|_cx| ConfigurationView {
- state,
- http_client,
- compact: false,
- })
- .into()
- }
-
- fn configuration_view_v2(
- &self,
- _target_agent: language_model::ConfigurationViewTargetAgent,
- _window: &mut Window,
- cx: &mut App,
- ) -> ProviderConfigurationView {
- let state = self.state.clone();
- let http_client = self.http_client.clone();
-
- ProviderConfigurationView::Inline {
- view: cx
- .new(|_cx| ConfigurationView {
- state,
- http_client,
- compact: true,
- })
- .into(),
- }
- }
-
- fn inline_title(&self, cx: &App) -> Option<SharedString> {
- if self.state.read(cx).is_authenticated() {
+ fn settings_view(&self, cx: &mut App) -> Option<ProviderSettingsView> {
+ let is_authenticated = self.state.read(cx).is_authenticated();
+ let title = if is_authenticated {
None
} else {
Some("Configure ChatGPT".into())
- }
- }
-
- fn inline_description(&self, cx: &App) -> Option<InlineDescription> {
- if self.state.read(cx).is_authenticated() {
+ };
+ let description = if is_authenticated {
None
} else {
Some(InlineDescription::Text(SUBSCRIPTION_DESCRIPTION.into()))
- }
- }
+ };
- fn reset_credentials(&self, cx: &mut App) -> Task<Result<()>> {
- self.sign_out(cx)
+ Some(ProviderSettingsView::Inline(
+ language_model::InlineProviderSettings {
+ title,
+ description,
+ create_view: Arc::new({
+ let state = self.state.clone();
+ let http_client = self.http_client.clone();
+ move |_window, cx| {
+ cx.new(|_cx| ConfigurationView {
+ state: state.clone(),
+ http_client: http_client.clone(),
+ compact: true,
+ })
+ .into()
+ }
+ }),
+ },
+ ))
}
fn authentication_error_message(&self) -> SharedString {
"Your ChatGPT subscription session is invalid or has expired. \
- Sign in again via the Agent Panel settings to continue."
+ Sign in again via Settings > AI > LLM Providers to continue."
.into()
}
fn missing_credentials_error_message(&self) -> SharedString {
"You are not signed in to your ChatGPT account. \
- Sign in via the Agent Panel settings to continue."
+ Sign in via Settings > AI > LLM Providers to continue."
.into()
}
diff --git a/crates/language_models/src/provider/opencode.rs b/crates/language_models/src/provider/opencode.rs
index f75c71e425b..94689cc0d66 100644
--- a/crates/language_models/src/provider/opencode.rs
+++ b/crates/language_models/src/provider/opencode.rs
@@ -3,14 +3,15 @@ use collections::BTreeMap;
use credentials_provider::CredentialsProvider;
use fs::Fs;
use futures::{FutureExt, StreamExt, future::BoxFuture};
-use gpui::{AnyView, App, AsyncApp, Context, Entity, SharedString, Task, TaskExt, Window};
+use gpui::{App, AsyncApp, Context, Entity, SharedString, Task, TaskExt, Window};
use http_client::{AsyncBody, CustomHeaders, HttpClient, http};
use language_model::{
ApiKeyState, AuthenticateError, EnvVar, IconOrSvg, InlineDescription, LanguageModel,
LanguageModelCompletionError, LanguageModelCompletionEvent, LanguageModelEffortLevel,
LanguageModelId, LanguageModelName, LanguageModelProvider, LanguageModelProviderId,
LanguageModelProviderName, LanguageModelProviderState, LanguageModelRequest,
- LanguageModelToolChoice, RateLimiter, ReasoningEffort, env_var,
+ LanguageModelToolChoice, ProviderSettingsView, RateLimiter, ReasoningEffort,
+ SubPageProviderSettings, env_var,
};
use opencode::{ApiProtocol, OPENCODE_API_URL, OpenCodeSubscription};
pub use settings::OpenCodeAvailableModel as AvailableModel;
@@ -200,12 +201,6 @@ impl LanguageModelProvider for OpenCodeLanguageModelProvider {
IconOrSvg::Icon(IconName::AiOpenCode)
}
- fn inline_description(&self, _cx: &App) -> Option<InlineDescription> {
- Some(InlineDescription::Text(
- "To use OpenCode models in Zed, you need an API key.".into(),
- ))
- }
-
fn default_model(&self, cx: &App) -> Option<Arc<dyn LanguageModel>> {
if Self::subscription_enabled(OpenCodeSubscription::Go, cx) {
// If both Go and Zen are enabled, prefer Go since it's not pay-as-you-go
@@ -311,19 +306,17 @@ impl LanguageModelProvider for OpenCodeLanguageModelProvider {
self.state.update(cx, |state, cx| state.authenticate(cx))
}
- fn configuration_view(
- &self,
- _target_agent: language_model::ConfigurationViewTargetAgent,
- window: &mut Window,
- cx: &mut App,
- ) -> AnyView {
- cx.new(|cx| ConfigurationView::new(self.state.clone(), window, cx))
- .into()
- }
-
- fn reset_credentials(&self, cx: &mut App) -> Task<Result<()>> {
- self.state
- .update(cx, |state, cx| state.set_api_key(None, cx))
+ fn settings_view(&self, _cx: &mut App) -> Option<ProviderSettingsView> {
+ let state = self.state.clone();
+ Some(ProviderSettingsView::SubPage(
+ SubPageProviderSettings::new(move |window, cx| {
+ cx.new(|cx| ConfigurationView::new(state.clone(), window, cx))
+ .into()
+ })
+ .description(InlineDescription::Text(
+ "To use OpenCode models in Zed, you need an API key.".into(),
+ )),
+ ))
}
}
diff --git a/crates/language_models/src/provider/vercel_ai_gateway.rs b/crates/language_models/src/provider/vercel_ai_gateway.rs
index dcceffe22e7..212223eb851 100644
--- a/crates/language_models/src/provider/vercel_ai_gateway.rs
+++ b/crates/language_models/src/provider/vercel_ai_gateway.rs
@@ -2,7 +2,7 @@ use anyhow::Result;
use collections::BTreeMap;
use credentials_provider::CredentialsProvider;
use futures::{AsyncReadExt, FutureExt, StreamExt, future::BoxFuture};
-use gpui::{AnyView, App, AsyncApp, Context, Entity, SharedString, Task, TaskExt, Window};
+use gpui::{App, AppContext, AsyncApp, Context, Entity, SharedString, Task};
use http_client::{
AsyncBody, CustomHeaders, HttpClient, Method, Request as HttpRequest, RequestBuilderExt, http,
};
@@ -11,7 +11,7 @@ use language_model::{
LanguageModelCompletionError, LanguageModelCompletionEvent, LanguageModelId, LanguageModelName,
LanguageModelProvider, LanguageModelProviderId, LanguageModelProviderName,
LanguageModelProviderState, LanguageModelRequest, LanguageModelToolChoice,
- LanguageModelToolSchemaFormat, RateLimiter, env_var,
+ LanguageModelToolSchemaFormat, ProviderSettingsView, RateLimiter, env_var,
};
use open_ai::ResponseStreamEvent;
use serde::Deserialize;
@@ -19,9 +19,7 @@ pub use settings::OpenAiCompatibleModelCapabilities as ModelCapabilities;
pub use settings::VercelAiGatewayAvailableModel as AvailableModel;
use settings::{Settings, SettingsStore};
use std::sync::{Arc, LazyLock};
-use ui::{ButtonLink, ConfiguredApiCard, List, ListBulletItem, prelude::*};
-use ui_input::InputField;
-use util::ResultExt;
+use ui::IconName;
const PROVIDER_ID: LanguageModelProviderId = LanguageModelProviderId::new("vercel_ai_gateway");
const PROVIDER_NAME: LanguageModelProviderName =
@@ -246,36 +244,20 @@ impl LanguageModelProvider for VercelAiGatewayLanguageModelProvider {
self.state.update(cx, |state, cx| state.authenticate(cx))
}
- fn configuration_view(
- &self,
- _target_agent: language_model::ConfigurationViewTargetAgent,
- window: &mut Window,
- cx: &mut App,
- ) -> AnyView {
- cx.new(|cx| ConfigurationView::new(self.state.clone(), window, cx))
- .into()
- }
-
- fn reset_credentials(&self, cx: &mut App) -> Task<Result<()>> {
- self.state
- .update(cx, |state, cx| state.set_api_key(None, cx))
- }
-
- fn api_key_configuration(&self, cx: &App) -> Option<ApiKeyConfiguration> {
+ fn settings_view(&self, cx: &mut App) -> Option<ProviderSettingsView> {
let state = self.state.read(cx);
- Some(ApiKeyConfiguration {
- has_key: state.api_key_state.has_key(),
- is_from_env_var: state.api_key_state.is_from_env_var(),
- env_var_name: state.api_key_state.env_var_name().clone(),
- api_key_url:
- "https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys&title=Go+to+AI+Gateway"
- .into(),
- })
+ Some(ProviderSettingsView::ApiKey(ApiKeyConfiguration::new(
+ state.api_key_state.has_key(),
+ state.api_key_state.is_from_env_var(),
+ state.api_key_state.env_var_name().clone(),
+ "https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys&title=Go+to+AI+Gateway"
+ .into(),
+ )))
}
- fn set_api_key(&self, key: String, cx: &mut App) -> Task<Result<()>> {
+ fn set_api_key(&self, api_key: Option<String>, cx: &mut App) -> Task<Result<()>> {
self.state
- .update(cx, |state, cx| state.set_api_key(Some(key), cx))
+ .update(cx, |state, cx| state.set_api_key(api_key, cx))
}
}
@@ -618,131 +600,3 @@ async fn list_models(
Ok(models)
}
-
-struct ConfigurationView {
- api_key_editor: Entity<InputField>,
- state: Entity<State>,
- load_credentials_task: Option<Task<()>>,
-}
-
-impl ConfigurationView {
- fn new(state: Entity<State>, window: &mut Window, cx: &mut Context<Self>) -> Self {
- let api_key_editor =
- cx.new(|cx| InputField::new(window, cx, "vck_000000000000000000000000000"));
-
- cx.observe(&state, |_, _, cx| cx.notify()).detach();
-
- let load_credentials_task = Some(cx.spawn_in(window, {
- let state = state.clone();
- async move |this, cx| {
- if let Some(task) = Some(state.update(cx, |state, cx| state.authenticate(cx))) {
- let _ = task.await;
- }
- this.update(cx, |this, cx| {
- this.load_credentials_task = None;
- cx.notify();
- })
- .log_err();
- }
- }));
-
- Self {
- api_key_editor,
- state,
- load_credentials_task,
- }
- }
-
- fn save_api_key(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
- let api_key = self.api_key_editor.read(cx).text(cx).trim().to_string();
- if api_key.is_empty() {
- return;
- }
-
- self.api_key_editor
- .update(cx, |editor, cx| editor.set_text("", window, cx));
-
- let state = self.state.clone();
- cx.spawn_in(window, async move |_, cx| {
- state
- .update(cx, |state, cx| state.set_api_key(Some(api_key), cx))
- .await
- })
- .detach_and_log_err(cx);
- }
-
- fn reset_api_key(&mut self, window: &mut Window, cx: &mut Context<Self>) {
- self.api_key_editor
- .update(cx, |editor, cx| editor.set_text("", window, cx));
-
- let state = self.state.clone();
- cx.spawn_in(window, async move |_, cx| {
- state
- .update(cx, |state, cx| state.set_api_key(None, cx))
- .await
- })
- .detach_and_log_err(cx);
- }
-
- fn should_render_editor(&self, cx: &Context<Self>) -> bool {
- !self.state.read(cx).is_authenticated()
- }
-}
-
-impl Render for ConfigurationView {
- fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
- let env_var_set = self.state.read(cx).api_key_state.is_from_env_var();
- let configured_card_label = if env_var_set {
- format!("API key set in {API_KEY_ENV_VAR_NAME} environment variable")
- } else {
- let api_url = VercelAiGatewayLanguageModelProvider::api_url(cx);
- if api_url == API_URL {
- "API key configured".to_string()
- } else {
- format!("API key configured for {}", api_url)
- }
- };
-
- if self.load_credentials_task.is_some() {
- div().child(Label::new("Loading credentials...")).into_any()
- } else if self.should_render_editor(cx) {
- v_flex()
- .size_full()
- .on_action(cx.listener(Self::save_api_key))
- .child(Label::new(
- "To use Zed's agent with Vercel AI Gateway, you need to add an API key. Follow these steps:",
- ))
- .child(
- List::new()
- .child(
- ListBulletItem::new("")
- .child(Label::new("Create an API key in"))
- .child(ButtonLink::new(
- "Vercel AI Gateway's console",
- "https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys&title=Go+to+AI+Gateway",
- )),
- )
- .child(ListBulletItem::new(
- "Paste your API key below and hit enter to start using the assistant",
- )),
- )
- .child(self.api_key_editor.clone())
- .child(
- Label::new(format!(
- "You can also set the {API_KEY_ENV_VAR_NAME} environment variable and restart Zed.",
- ))
- .size(LabelSize::Small)
- .color(Color::Muted),
- )
- .into_any_element()
- } else {
- ConfiguredApiCard::new("vercel-reset-key", configured_card_label)
- .disabled(env_var_set)
- .when(env_var_set, |this| {
- this.tooltip_label(format!("To reset your API key, unset the {API_KEY_ENV_VAR_NAME} environment variable."))
- })
- .on_click(cx.listener(|this, _, window, cx| this.reset_api_key(window, cx)))
- .into_any_element()
- }
- }
-}
diff --git a/crates/language_models/src/provider/x_ai.rs b/crates/language_models/src/provider/x_ai.rs
index 92121f2e5ff..4556e439a39 100644
--- a/crates/language_models/src/provider/x_ai.rs
+++ b/crates/language_models/src/provider/x_ai.rs
@@ -2,23 +2,22 @@ use anyhow::Result;
use collections::BTreeMap;
use credentials_provider::CredentialsProvider;
use futures::{FutureExt, StreamExt, future::BoxFuture};
-use gpui::{AnyView, App, AsyncApp, Context, Entity, Task, TaskExt, Window};
+use gpui::{App, AppContext, AsyncApp, Context, Entity, SharedString, Task};
use http_client::{CustomHeaders, HttpClient};
use language_model::{
ApiKeyConfiguration, ApiKeyState, AuthenticateError, EnvVar, IconOrSvg, LanguageModel,
LanguageModelCompletionError, LanguageModelCompletionEvent, LanguageModelEffortLevel,
LanguageModelId, LanguageModelName, LanguageModelProvider, LanguageModelProviderId,
LanguageModelProviderName, LanguageModelProviderState, LanguageModelRequest,
- LanguageModelToolChoice, LanguageModelToolSchemaFormat, RateLimiter, env_var,
+ LanguageModelToolChoice, LanguageModelToolSchemaFormat, ProviderSettingsView, RateLimiter,
+ env_var,
};
use open_ai::ResponseStreamEvent;
pub use settings::XaiAvailableModel as AvailableModel;
use settings::{Settings, SettingsStore};
use std::sync::{Arc, LazyLock};
use strum::IntoEnumIterator;
-use ui::{ButtonLink, ConfiguredApiCard, List, ListBulletItem, prelude::*};
-use ui_input::InputField;
-use util::ResultExt;
+use ui::IconName;
use x_ai::XAI_API_URL;
const PROVIDER_ID: LanguageModelProviderId = LanguageModelProviderId::new("x_ai");
@@ -193,34 +192,19 @@ impl LanguageModelProvider for XAiLanguageModelProvider {
self.state.update(cx, |state, cx| state.authenticate(cx))
}
- fn configuration_view(
- &self,
- _target_agent: language_model::ConfigurationViewTargetAgent,
- window: &mut Window,
- cx: &mut App,
- ) -> AnyView {
- cx.new(|cx| ConfigurationView::new(self.state.clone(), window, cx))
- .into()
- }
-
- fn reset_credentials(&self, cx: &mut App) -> Task<Result<()>> {
- self.state
- .update(cx, |state, cx| state.set_api_key(None, cx))
- }
-
- fn api_key_configuration(&self, cx: &App) -> Option<ApiKeyConfiguration> {
+ fn settings_view(&self, cx: &mut App) -> Option<ProviderSettingsView> {
let state = self.state.read(cx);
- Some(ApiKeyConfiguration {
- has_key: state.api_key_state.has_key(),
- is_from_env_var: state.api_key_state.is_from_env_var(),
- env_var_name: state.api_key_state.env_var_name().clone(),
- api_key_url: "https://console.x.ai/team/default/api-keys".into(),
- })
+ Some(ProviderSettingsView::ApiKey(ApiKeyConfiguration::new(
+ state.api_key_state.has_key(),
+ state.api_key_state.is_from_env_var(),
+ state.api_key_state.env_var_name().clone(),
+ "https://console.x.ai/team/default/api-keys".into(),
+ )))
}
- fn set_api_key(&self, key: String, cx: &mut App) -> Task<Result<()>> {
+ fn set_api_key(&self, api_key: Option<String>, cx: &mut App) -> Task<Result<()>> {
self.state
- .update(cx, |state, cx| state.set_api_key(Some(key), cx))
+ .update(cx, |state, cx| state.set_api_key(api_key, cx))
}
}
@@ -448,87 +432,6 @@ impl LanguageModel for XAiLanguageModel {
}
}
-struct ConfigurationView {
- api_key_editor: Entity<InputField>,
- state: Entity<State>,
- load_credentials_task: Option<Task<()>>,
-}
-
-impl ConfigurationView {
- fn new(state: Entity<State>, window: &mut Window, cx: &mut Context<Self>) -> Self {
- let api_key_editor = cx.new(|cx| {
- InputField::new(
- window,
- cx,
- "xai-0000000000000000000000000000000000000000000000000",
- )
- .label("API key")
- });
-
- cx.observe(&state, |_, _, cx| {
- cx.notify();
- })
- .detach();
-
- let load_credentials_task = Some(cx.spawn_in(window, {
- let state = state.clone();
- async move |this, cx| {
- if let Some(task) = Some(state.update(cx, |state, cx| state.authenticate(cx))) {
- // We don't log an error, because "not signed in" is also an error.
- let _ = task.await;
- }
- this.update(cx, |this, cx| {
- this.load_credentials_task = None;
- cx.notify();
- })
- .log_err();
- }
- }));
-
- Self {
- api_key_editor,
- state,
- load_credentials_task,
- }
- }
-
- fn save_api_key(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
- let api_key = self.api_key_editor.read(cx).text(cx).trim().to_string();
- if api_key.is_empty() {
- return;
- }
-
- // url changes can cause the editor to be displayed again
- self.api_key_editor
- .update(cx, |editor, cx| editor.set_text("", window, cx));
-
- let state = self.state.clone();
- cx.spawn_in(window, async move |_, cx| {
- state
- .update(cx, |state, cx| state.set_api_key(Some(api_key), cx))
- .await
- })
- .detach_and_log_err(cx);
- }
-
- fn reset_api_key(&mut self, window: &mut Window, cx: &mut Context<Self>) {
- self.api_key_editor
- .update(cx, |input, cx| input.set_text("", window, cx));
-
- let state = self.state.clone();
- cx.spawn_in(window, async move |_, cx| {
- state
- .update(cx, |state, cx| state.set_api_key(None, cx))
- .await
- })
- .detach_and_log_err(cx);
- }
-
- fn should_render_editor(&self, cx: &mut Context<Self>) -> bool {
- !self.state.read(cx).is_authenticated()
- }
-}
-
#[cfg(test)]
mod tests {
use super::*;
@@ -578,64 +481,3 @@ mod tests {
);
}
}
-
-impl Render for ConfigurationView {
- fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
- let env_var_set = self.state.read(cx).api_key_state.is_from_env_var();
- let configured_card_label = if env_var_set {
- format!("API key set in {API_KEY_ENV_VAR_NAME} environment variable")
- } else {
- let api_url = XAiLanguageModelProvider::api_url(cx);
- if api_url == XAI_API_URL {
- "API key configured".to_string()
- } else {
- format!("API key configured for {}", api_url)
- }
- };
-
- let api_key_section = if self.should_render_editor(cx) {
- v_flex()
- .on_action(cx.listener(Self::save_api_key))
- .child(Label::new("To use Zed's agent with xAI, you need to add an API key. Follow these steps:"))
- .child(
- List::new()
- .child(
- ListBulletItem::new("")
- .child(Label::new("Create one by visiting"))
- .child(ButtonLink::new("xAI console", "https://console.x.ai/team/default/api-keys"))
- )
- .child(
- ListBulletItem::new("Paste your API key below and hit enter to start using the agent")
- ),
- )
- .child(self.api_key_editor.clone())
- .child(
- Label::new(format!(
- "You can also set the {API_KEY_ENV_VAR_NAME} environment variable and restart Zed."
- ))
- .size(LabelSize::Small)
- .color(Color::Muted),
- )
- .child(
- Label::new("Note that xAI is a custom OpenAI-compatible provider.")
- .size(LabelSize::Small)
- .color(Color::Muted),
- )
- .into_any_element()
- } else {
- ConfiguredApiCard::new("xai-reset-key", configured_card_label)
- .disabled(env_var_set)
- .when(env_var_set, |this| {
- this.tooltip_label(format!("To reset your API key, unset the {API_KEY_ENV_VAR_NAME} environment variable."))
- })
- .on_click(cx.listener(|this, _, window, cx| this.reset_api_key(window, cx)))
- .into_any_element()
- };
-
- if self.load_credentials_task.is_some() {
- div().child(Label::new("Loading credentials…")).into_any()
- } else {
- v_flex().size_full().child(api_key_section).into_any()
- }
- }
-}
diff --git a/crates/settings_ui/src/pages/llm_providers_page.rs b/crates/settings_ui/src/pages/llm_providers_page.rs
index f888b031eb8..bac9b7abb06 100644
--- a/crates/settings_ui/src/pages/llm_providers_page.rs
+++ b/crates/settings_ui/src/pages/llm_providers_page.rs
@@ -3,9 +3,8 @@ use std::{collections::HashSet, sync::Arc};
use editor::Editor;
use gpui::{AnyView, Entity, Focusable as _, ScrollHandle, prelude::*};
use language_model::{
- ApiKeyConfiguration, ConfigurationViewTargetAgent, IconOrSvg, InlineDescription,
- LanguageModelProvider, LanguageModelProviderId, LanguageModelRegistry,
- ProviderConfigurationView,
+ ApiKeyConfiguration, CreateProviderSettingsView, IconOrSvg, InlineDescription,
+ LanguageModelProvider, LanguageModelProviderId, LanguageModelRegistry, ProviderSettingsView,
};
use settings::{
@@ -149,14 +148,29 @@ fn render_provider_section(
let provider_id = provider.id();
let provider_name = provider.name().0;
- let body = if let Some(config) = provider.api_key_configuration(cx) {
- render_api_key_providers_item(settings_window, provider, provider_name.clone(), config, cx)
- } else {
- match get_or_create_configuration_view(settings_window, &provider_id, provider, window, cx)
- {
- ProviderConfigurationView::Inline { view } => render_inline_body(provider, view, cx),
- ProviderConfigurationView::SubPage(_) => render_subpage_item(provider, cx),
+ let body = match provider.settings_view(cx) {
+ Some(ProviderSettingsView::ApiKey(config)) => {
+ render_api_key_providers_item(provider, provider_name.clone(), config, cx)
}
+ Some(ProviderSettingsView::Inline(settings)) => {
+ let view = get_or_create_configuration_view(
+ settings_window,
+ &provider_id,
+ settings.create_view,
+ window,
+ cx,
+ );
+ render_inline_body(
+ provider_name.clone(),
+ settings.title,
+ settings.description,
+ view,
+ )
+ }
+ Some(ProviderSettingsView::SubPage(settings)) => {
+ render_subpage_item(provider, settings.description, cx)
+ }
+ None => div().into_any_element(),
};
v_flex()
@@ -196,18 +210,16 @@ fn render_provider_header(
}
fn render_api_key_providers_item(
- _settings_window: &SettingsWindow,
provider: &Arc<dyn LanguageModelProvider>,
provider_name: SharedString,
config: ApiKeyConfiguration,
_cx: &mut Context<SettingsWindow>,
) -> AnyElement {
- let ApiKeyConfiguration {
- has_key,
- is_from_env_var,
- env_var_name,
- api_key_url,
- } = config;
+ let provider_id = provider.id();
+ let has_key = config.has_key;
+ let is_from_env_var = config.is_from_env_var;
+ let env_var_name = config.env_var_name;
+ let api_key_url = config.api_key_url;
if has_key {
let configured_label = if is_from_env_var {
@@ -215,7 +227,7 @@ fn render_api_key_providers_item(
} else {
"API Key Configured"
};
- let button_id = format!("reset-api-key-{}", provider.id().0);
+ let button_id = format!("reset-api-key-{}", provider_id.0);
let card = ConfiguredApiCard::new(button_id, configured_label)
.button_label("Reset Key")
@@ -229,7 +241,7 @@ fn render_api_key_providers_item(
.on_click({
let provider = provider.clone();
move |_, _, cx| {
- provider.reset_credentials(cx).detach_and_log_err(cx);
+ provider.set_api_key(None, cx).detach_and_log_err(cx);
}
})
.into_any_element();
@@ -237,7 +249,7 @@ fn render_api_key_providers_item(
return v_flex().gap_2().child(card).into_any_element();
}
- let input_id = format!("{}-api-key-input", provider.id().0);
+ let input_id = format!("{}-api-key-input", provider_id.0);
let aria_label = format!("{provider_name} API Key");
v_flex()
@@ -299,7 +311,7 @@ fn render_api_key_providers_item(
let provider = provider.clone();
move |api_key, _window, cx| {
if let Some(key) = api_key.filter(|key| !key.is_empty()) {
- provider.set_api_key(key, cx).detach_and_log_err(cx);
+ provider.set_api_key(Some(key), cx).detach_and_log_err(cx);
}
}
}),
@@ -309,14 +321,11 @@ fn render_api_key_providers_item(
}
fn render_inline_body(
- provider: &Arc<dyn LanguageModelProvider>,
+ provider_name: SharedString,
+ title: Option<SharedString>,
+ description: Option<InlineDescription>,
view: AnyView,
- cx: &mut Context<SettingsWindow>,
) -> AnyElement {
- let provider_name = provider.name().0;
- let title = provider.inline_title(cx);
- let description = provider.inline_description(cx);
-
if title.is_none() && description.is_none() {
return v_flex()
.pt_1()
@@ -348,11 +357,11 @@ fn render_inline_body(
fn render_subpage_item(
provider: &Arc<dyn LanguageModelProvider>,
+ description: Option<InlineDescription>,
cx: &mut Context<SettingsWindow>,
) -> AnyElement {
let provider_id = provider.id();
let provider_name = provider.name().0;
- let description = provider.inline_description(cx);
h_flex()
.pt_2p5()
@@ -449,18 +458,19 @@ fn render_provider_config_sub_page(
return div().into_any_element();
};
- // A provider routed to a sub-page always provides a `SubPage` view; fall
- // back to whatever view it returns otherwise.
- let view = match get_or_create_configuration_view(
- settings_window,
- &provider_id,
- &provider,
- window,
- cx,
- ) {
- ProviderConfigurationView::Inline { view, .. }
- | ProviderConfigurationView::SubPage(view) => view,
+ let Some(create_view) =
+ provider
+ .settings_view(cx)
+ .and_then(|settings_view| match settings_view {
+ ProviderSettingsView::Inline(settings) => Some(settings.create_view),
+ ProviderSettingsView::SubPage(settings) => Some(settings.create_view),
+ ProviderSettingsView::ApiKey(_) => None,
+ })
+ else {
+ return div().into_any_element();
};
+ let view =
+ get_or_create_configuration_view(settings_window, &provider_id, create_view, window, cx);
v_flex()
.id("provider-config-sub-page")
@@ -477,10 +487,10 @@ fn render_provider_config_sub_page(
fn get_or_create_configuration_view(
settings_window: &SettingsWindow,
provider_id: &LanguageModelProviderId,
- provider: &Arc<dyn LanguageModelProvider>,
+ create_view: CreateProviderSettingsView,
window: &mut Window,
cx: &mut Context<SettingsWindow>,
-) -> ProviderConfigurationView {
+) -> AnyView {
if let Some(view) = settings_window
.provider_configuration_views
.get(provider_id)
@@ -488,7 +498,7 @@ fn get_or_create_configuration_view(
return view.clone();
}
- let view = provider.configuration_view_v2(ConfigurationViewTargetAgent::ZedAgent, window, cx);
+ let view = create_view(window, cx);
// Store the view for future renders by deferring a mutation
let provider_id = provider_id.clone();
@@ -1146,7 +1156,7 @@ fn save_llm_provider_form(
let provider = LanguageModelRegistry::read_global(cx)
.provider(&provider_id)
.ok_or_else(|| anyhow::anyhow!("Provider was not registered"))?;
- anyhow::Ok(provider.set_api_key(api_key, cx))
+ anyhow::Ok(provider.set_api_key(Some(api_key), cx))
})??;
set_api_key.await?;
diff --git a/crates/settings_ui/src/settings_ui.rs b/crates/settings_ui/src/settings_ui.rs
index 34a2ac271d4..35f816d649b 100644
--- a/crates/settings_ui/src/settings_ui.rs
+++ b/crates/settings_ui/src/settings_ui.rs
@@ -948,10 +948,9 @@ pub struct SettingsWindow {
pub(crate) regex_validation_error: Option<String>,
pub(crate) sandbox_host_validation_error: Option<String>,
last_copied_link_path: Option<&'static str>,
- /// Cached configuration views per provider, created lazily. Holds the
- /// provider's chosen presentation ([`Inline`] or [`SubPage`]).
+ /// Cached configuration views per provider, created lazily.
pub(crate) provider_configuration_views:
- HashMap<language_model::LanguageModelProviderId, language_model::ProviderConfigurationView>,
+ HashMap<language_model::LanguageModelProviderId, gpui::AnyView>,
/// The provider whose configuration sub-page is currently open, if any.
pub(crate) configuring_provider: Option<language_model::LanguageModelProviderId>,
/// Directory path of the skill whose share link was most recently copied,
diff --git a/crates/zed_actions/src/lib.rs b/crates/zed_actions/src/lib.rs
index 9d47f272406..8b2d0d45df7 100644
--- a/crates/zed_actions/src/lib.rs
+++ b/crates/zed_actions/src/lib.rs
@@ -539,7 +539,7 @@ pub mod agent {
actions!(
agent,
[
- /// Opens the agent settings panel.
+ /// Opens the agent settings UI.
#[action(deprecated_aliases = ["agent::OpenConfiguration"])]
OpenSettings,
/// Opens the agent onboarding modal.