diff --git a/Cargo.lock b/Cargo.lock
index 3e28404fc118ea6eb3ea95033a72821b0a3ee162..3732653a15ff4dcd342a03d0c35c821b2e897640 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -109,6 +109,8 @@ dependencies = [
"isahc",
"language",
"menu",
+ "project",
+ "regex",
"schemars",
"search",
"serde",
diff --git a/assets/icons/assist_15.svg b/assets/icons/assist_15.svg
new file mode 100644
index 0000000000000000000000000000000000000000..3baf8df3e936347415749cf0667c04e32391f828
--- /dev/null
+++ b/assets/icons/assist_15.svg
@@ -0,0 +1 @@
+
diff --git a/assets/icons/hamburger_15.svg b/assets/icons/hamburger_15.svg
new file mode 100644
index 0000000000000000000000000000000000000000..060caeecbfd58603530f253248a0c369ba329b4e
--- /dev/null
+++ b/assets/icons/hamburger_15.svg
@@ -0,0 +1,3 @@
+
diff --git a/assets/icons/quote_15.svg b/assets/icons/quote_15.svg
new file mode 100644
index 0000000000000000000000000000000000000000..be5eabd9b019902a44c03ac5545441702b6d7925
--- /dev/null
+++ b/assets/icons/quote_15.svg
@@ -0,0 +1 @@
+
diff --git a/assets/icons/split_message_15.svg b/assets/icons/split_message_15.svg
new file mode 100644
index 0000000000000000000000000000000000000000..54d9e81224cbf55eca2a4f354f7fcfc8f98b6854
--- /dev/null
+++ b/assets/icons/split_message_15.svg
@@ -0,0 +1 @@
+
diff --git a/assets/keymaps/default.json b/assets/keymaps/default.json
index 84b11b53a1086ef0c5a422213c50a4cb5961ed33..853d62f3e421e68732743011408cb487b50c0cc8 100644
--- a/assets/keymaps/default.json
+++ b/assets/keymaps/default.json
@@ -40,7 +40,8 @@
"cmd-o": "workspace::Open",
"alt-cmd-o": "projects::OpenRecent",
"ctrl-~": "workspace::NewTerminal",
- "ctrl-`": "terminal_panel::ToggleFocus"
+ "ctrl-`": "terminal_panel::ToggleFocus",
+ "shift-escape": "workspace::ToggleZoom"
}
},
{
@@ -197,9 +198,17 @@
}
},
{
- "context": "AssistantEditor > Editor",
+ "context": "AssistantPanel",
+ "bindings": {
+ "cmd-g": "search::SelectNextMatch",
+ "cmd-shift-g": "search::SelectPrevMatch"
+ }
+ },
+ {
+ "context": "ConversationEditor > Editor",
"bindings": {
"cmd-enter": "assistant::Assist",
+ "cmd-s": "workspace::Save",
"cmd->": "assistant::QuoteSelection",
"shift-enter": "assistant::Split",
"ctrl-r": "assistant::CycleMessageRole"
@@ -234,8 +243,7 @@
"cmd-shift-g": "search::SelectPrevMatch",
"alt-cmd-c": "search::ToggleCaseSensitive",
"alt-cmd-w": "search::ToggleWholeWord",
- "alt-cmd-r": "search::ToggleRegex",
- "shift-escape": "workspace::ToggleZoom"
+ "alt-cmd-r": "search::ToggleRegex"
}
},
// Bindings from VS Code
diff --git a/assets/settings/default.json b/assets/settings/default.json
index bd73bcbf08032946736159393e8385107f5873d1..c69d8089bc6e91e616da0c12bd90da277c78fefe 100644
--- a/assets/settings/default.json
+++ b/assets/settings/default.json
@@ -57,37 +57,37 @@
"show_whitespaces": "selection",
// Scrollbar related settings
"scrollbar": {
- // When to show the scrollbar in the editor.
- // This setting can take four values:
- //
- // 1. Show the scrollbar if there's important information or
- // follow the system's configured behavior (default):
- // "auto"
- // 2. Match the system's configured behavior:
- // "system"
- // 3. Always show the scrollbar:
- // "always"
- // 4. Never show the scrollbar:
- // "never"
- "show": "auto",
- // Whether to show git diff indicators in the scrollbar.
- "git_diff": true
+ // When to show the scrollbar in the editor.
+ // This setting can take four values:
+ //
+ // 1. Show the scrollbar if there's important information or
+ // follow the system's configured behavior (default):
+ // "auto"
+ // 2. Match the system's configured behavior:
+ // "system"
+ // 3. Always show the scrollbar:
+ // "always"
+ // 4. Never show the scrollbar:
+ // "never"
+ "show": "auto",
+ // Whether to show git diff indicators in the scrollbar.
+ "git_diff": true
},
"project_panel": {
- // Whether to show the git status in the project panel.
- "git_status": true,
- // Where to dock project panel. Can be 'left' or 'right'.
- "dock": "left",
- // Default width of the project panel.
- "default_width": 240
+ // Whether to show the git status in the project panel.
+ "git_status": true,
+ // Where to dock project panel. Can be 'left' or 'right'.
+ "dock": "left",
+ // Default width of the project panel.
+ "default_width": 240
},
"assistant": {
- // Where to dock the assistant. Can be 'left', 'right' or 'bottom'.
- "dock": "right",
- // Default width when the assistant is docked to the left or right.
- "default_width": 450,
- // Default height when the assistant is docked to the bottom.
- "default_height": 320
+ // Where to dock the assistant. Can be 'left', 'right' or 'bottom'.
+ "dock": "right",
+ // Default width when the assistant is docked to the left or right.
+ "default_width": 640,
+ // Default height when the assistant is docked to the bottom.
+ "default_height": 320
},
// Whether the screen sharing icon is shown in the os status bar.
"show_call_status_icon": true,
diff --git a/crates/ai/Cargo.toml b/crates/ai/Cargo.toml
index 7f8954bb21ea88a0b14f7fd5bacf26743de3c6be..013565e14f449863f3b81be1d94bf4562b4323e0 100644
--- a/crates/ai/Cargo.toml
+++ b/crates/ai/Cargo.toml
@@ -22,9 +22,10 @@ util = { path = "../util" }
workspace = { path = "../workspace" }
anyhow.workspace = true
-chrono = "0.4"
+chrono = { version = "0.4", features = ["serde"] }
futures.workspace = true
isahc.workspace = true
+regex.workspace = true
schemars.workspace = true
serde.workspace = true
serde_json.workspace = true
@@ -33,3 +34,4 @@ tiktoken-rs = "0.4"
[dev-dependencies]
editor = { path = "../editor", features = ["test-support"] }
+project = { path = "../project", features = ["test-support"] }
diff --git a/crates/ai/src/ai.rs b/crates/ai/src/ai.rs
index b3b62c6a2422f0a354f27a34f0e28ffea23af95f..812fb051213f66fd8df1fb83d0b423b1f414effb 100644
--- a/crates/ai/src/ai.rs
+++ b/crates/ai/src/ai.rs
@@ -1,10 +1,22 @@
pub mod assistant;
mod assistant_settings;
+use anyhow::Result;
pub use assistant::AssistantPanel;
+use chrono::{DateTime, Local};
+use collections::HashMap;
+use fs::Fs;
+use futures::StreamExt;
use gpui::AppContext;
+use regex::Regex;
use serde::{Deserialize, Serialize};
-use std::fmt::{self, Display};
+use std::{
+ cmp::Reverse,
+ fmt::{self, Display},
+ path::PathBuf,
+ sync::Arc,
+};
+use util::paths::CONVERSATIONS_DIR;
// Data types for chat completion requests
#[derive(Debug, Serialize)]
@@ -14,6 +26,84 @@ struct OpenAIRequest {
stream: bool,
}
+#[derive(
+ Copy, Clone, Debug, Default, Eq, PartialEq, PartialOrd, Ord, Hash, Serialize, Deserialize,
+)]
+struct MessageId(usize);
+
+#[derive(Clone, Debug, Serialize, Deserialize)]
+struct MessageMetadata {
+ role: Role,
+ sent_at: DateTime,
+ status: MessageStatus,
+}
+
+#[derive(Clone, Debug, Serialize, Deserialize)]
+enum MessageStatus {
+ Pending,
+ Done,
+ Error(Arc),
+}
+
+#[derive(Serialize, Deserialize)]
+struct SavedMessage {
+ id: MessageId,
+ start: usize,
+}
+
+#[derive(Serialize, Deserialize)]
+struct SavedConversation {
+ zed: String,
+ version: String,
+ text: String,
+ messages: Vec,
+ message_metadata: HashMap,
+ summary: String,
+ model: String,
+}
+
+impl SavedConversation {
+ const VERSION: &'static str = "0.1.0";
+}
+
+struct SavedConversationMetadata {
+ title: String,
+ path: PathBuf,
+ mtime: chrono::DateTime,
+}
+
+impl SavedConversationMetadata {
+ pub async fn list(fs: Arc) -> Result> {
+ fs.create_dir(&CONVERSATIONS_DIR).await?;
+
+ let mut paths = fs.read_dir(&CONVERSATIONS_DIR).await?;
+ let mut conversations = Vec::::new();
+ while let Some(path) = paths.next().await {
+ let path = path?;
+
+ let pattern = r" - \d+.zed.json$";
+ let re = Regex::new(pattern).unwrap();
+
+ let metadata = fs.metadata(&path).await?;
+ if let Some((file_name, metadata)) = path
+ .file_name()
+ .and_then(|name| name.to_str())
+ .zip(metadata)
+ {
+ let title = re.replace(file_name, "");
+ conversations.push(Self {
+ title: title.into_owned(),
+ path,
+ mtime: metadata.mtime.into(),
+ });
+ }
+ }
+ conversations.sort_unstable_by_key(|conversation| Reverse(conversation.mtime));
+
+ Ok(conversations)
+ }
+}
+
#[derive(Serialize, Deserialize, Debug, Eq, PartialEq)]
struct RequestMessage {
role: Role,
diff --git a/crates/ai/src/assistant.rs b/crates/ai/src/assistant.rs
index 5b254fac4bedc049a012869b3b78b410be7656e8..01693425fbdf2cbb708c67b1690cf3da4b750371 100644
--- a/crates/ai/src/assistant.rs
+++ b/crates/ai/src/assistant.rs
@@ -1,6 +1,7 @@
use crate::{
assistant_settings::{AssistantDockPosition, AssistantSettings},
- OpenAIRequest, OpenAIResponseStreamEvent, RequestMessage, Role,
+ MessageId, MessageMetadata, MessageStatus, OpenAIRequest, OpenAIResponseStreamEvent,
+ RequestMessage, Role, SavedConversation, SavedConversationMetadata, SavedMessage,
};
use anyhow::{anyhow, Result};
use chrono::{DateTime, Local};
@@ -23,17 +24,26 @@ use gpui::{
};
use isahc::{http::StatusCode, Request, RequestExt};
use language::{language_settings::SoftWrap, Buffer, LanguageRegistry, ToOffset as _};
+use search::BufferSearchBar;
use serde::Deserialize;
use settings::SettingsStore;
use std::{
- borrow::Cow, cell::RefCell, cmp, fmt::Write, io, iter, ops::Range, rc::Rc, sync::Arc,
+ cell::RefCell,
+ cmp, env,
+ fmt::Write,
+ io, iter,
+ ops::Range,
+ path::{Path, PathBuf},
+ rc::Rc,
+ sync::Arc,
time::Duration,
};
-use util::{channel::ReleaseChannel, post_inc, truncate_and_trailoff, ResultExt, TryFutureExt};
+use theme::AssistantStyle;
+use util::{channel::ReleaseChannel, paths::CONVERSATIONS_DIR, post_inc, ResultExt, TryFutureExt};
use workspace::{
dock::{DockPosition, Panel},
- item::Item,
- pane, Pane, Workspace,
+ searchable::Direction,
+ Save, ToggleZoom, Toolbar, Workspace,
};
const OPENAI_API_URL: &'static str = "https://api.openai.com/v1";
@@ -47,7 +57,7 @@ actions!(
CycleMessageRole,
QuoteSelection,
ToggleFocus,
- ResetKey
+ ResetKey,
]
);
@@ -62,20 +72,28 @@ pub fn init(cx: &mut AppContext) {
cx.add_action(
|workspace: &mut Workspace, _: &NewContext, cx: &mut ViewContext| {
if let Some(this) = workspace.panel::(cx) {
- this.update(cx, |this, cx| this.add_context(cx))
+ this.update(cx, |this, cx| {
+ this.new_conversation(cx);
+ })
}
workspace.focus_panel::(cx);
},
);
- cx.add_action(AssistantEditor::assist);
- cx.capture_action(AssistantEditor::cancel_last_assist);
- cx.add_action(AssistantEditor::quote_selection);
- cx.capture_action(AssistantEditor::copy);
- cx.capture_action(AssistantEditor::split);
- cx.capture_action(AssistantEditor::cycle_message_role);
+ cx.add_action(ConversationEditor::assist);
+ cx.capture_action(ConversationEditor::cancel_last_assist);
+ cx.capture_action(ConversationEditor::save);
+ cx.add_action(ConversationEditor::quote_selection);
+ cx.capture_action(ConversationEditor::copy);
+ cx.add_action(ConversationEditor::split);
+ cx.capture_action(ConversationEditor::cycle_message_role);
cx.add_action(AssistantPanel::save_api_key);
cx.add_action(AssistantPanel::reset_api_key);
+ cx.add_action(AssistantPanel::toggle_zoom);
+ cx.add_action(AssistantPanel::deploy);
+ cx.add_action(AssistantPanel::select_next_match);
+ cx.add_action(AssistantPanel::select_prev_match);
+ cx.add_action(AssistantPanel::handle_editor_cancel);
cx.add_action(
|workspace: &mut Workspace, _: &ToggleFocus, cx: &mut ViewContext| {
workspace.toggle_panel_focus::(cx);
@@ -83,6 +101,7 @@ pub fn init(cx: &mut AppContext) {
);
}
+#[derive(Debug)]
pub enum AssistantPanelEvent {
ZoomIn,
ZoomOut,
@@ -92,15 +111,24 @@ pub enum AssistantPanelEvent {
}
pub struct AssistantPanel {
+ workspace: WeakViewHandle,
width: Option,
height: Option,
- pane: ViewHandle,
+ active_editor_index: Option,
+ prev_active_editor_index: Option,
+ editors: Vec>,
+ saved_conversations: Vec,
+ saved_conversations_list_state: UniformListState,
+ zoomed: bool,
+ has_focus: bool,
+ toolbar: ViewHandle,
api_key: Rc>>,
api_key_editor: Option>,
has_read_credentials: bool,
languages: Arc,
fs: Arc,
subscriptions: Vec,
+ _watch_saved_conversations: Task>,
}
impl AssistantPanel {
@@ -109,66 +137,51 @@ impl AssistantPanel {
cx: AsyncAppContext,
) -> Task>> {
cx.spawn(|mut cx| async move {
+ let fs = workspace.read_with(&cx, |workspace, _| workspace.app_state().fs.clone())?;
+ let saved_conversations = SavedConversationMetadata::list(fs.clone())
+ .await
+ .log_err()
+ .unwrap_or_default();
+
// TODO: deserialize state.
+ let workspace_handle = workspace.clone();
workspace.update(&mut cx, |workspace, cx| {
cx.add_view::(|cx| {
- let weak_self = cx.weak_handle();
- let pane = cx.add_view(|cx| {
- let mut pane = Pane::new(
- workspace.weak_handle(),
- workspace.project().clone(),
- workspace.app_state().background_actions,
- Default::default(),
- cx,
- );
- pane.set_can_split(false, cx);
- pane.set_can_navigate(false, cx);
- pane.on_can_drop(move |_, _| false);
- pane.set_render_tab_bar_buttons(cx, move |pane, cx| {
- let weak_self = weak_self.clone();
- Flex::row()
- .with_child(Pane::render_tab_bar_button(
- 0,
- "icons/plus_12.svg",
- false,
- Some(("New Context".into(), Some(Box::new(NewContext)))),
- cx,
- move |_, cx| {
- let weak_self = weak_self.clone();
- cx.window_context().defer(move |cx| {
- if let Some(this) = weak_self.upgrade(cx) {
- this.update(cx, |this, cx| this.add_context(cx));
- }
- })
- },
- None,
- ))
- .with_child(Pane::render_tab_bar_button(
- 1,
- if pane.is_zoomed() {
- "icons/minimize_8.svg"
- } else {
- "icons/maximize_8.svg"
- },
- pane.is_zoomed(),
- Some((
- "Toggle Zoom".into(),
- Some(Box::new(workspace::ToggleZoom)),
- )),
- cx,
- move |pane, cx| pane.toggle_zoom(&Default::default(), cx),
- None,
- ))
- .into_any()
- });
- let buffer_search_bar = cx.add_view(search::BufferSearchBar::new);
- pane.toolbar()
- .update(cx, |toolbar, cx| toolbar.add_item(buffer_search_bar, cx));
- pane
+ const CONVERSATION_WATCH_DURATION: Duration = Duration::from_millis(100);
+ let _watch_saved_conversations = cx.spawn(move |this, mut cx| async move {
+ let mut events = fs
+ .watch(&CONVERSATIONS_DIR, CONVERSATION_WATCH_DURATION)
+ .await;
+ while events.next().await.is_some() {
+ let saved_conversations = SavedConversationMetadata::list(fs.clone())
+ .await
+ .log_err()
+ .unwrap_or_default();
+ this.update(&mut cx, |this, _| {
+ this.saved_conversations = saved_conversations
+ })
+ .ok();
+ }
+
+ anyhow::Ok(())
});
+ let toolbar = cx.add_view(|cx| {
+ let mut toolbar = Toolbar::new(None);
+ toolbar.set_can_navigate(false, cx);
+ toolbar.add_item(cx.add_view(|cx| BufferSearchBar::new(cx)), cx);
+ toolbar
+ });
let mut this = Self {
- pane,
+ workspace: workspace_handle,
+ active_editor_index: Default::default(),
+ prev_active_editor_index: Default::default(),
+ editors: Default::default(),
+ saved_conversations,
+ saved_conversations_list_state: Default::default(),
+ zoomed: false,
+ has_focus: false,
+ toolbar,
api_key: Rc::new(RefCell::new(None)),
api_key_editor: None,
has_read_credentials: false,
@@ -177,20 +190,18 @@ impl AssistantPanel {
width: None,
height: None,
subscriptions: Default::default(),
+ _watch_saved_conversations,
};
let mut old_dock_position = this.position(cx);
- this.subscriptions = vec![
- cx.observe(&this.pane, |_, _, cx| cx.notify()),
- cx.subscribe(&this.pane, Self::handle_pane_event),
- cx.observe_global::(move |this, cx| {
+ this.subscriptions =
+ vec![cx.observe_global::(move |this, cx| {
let new_dock_position = this.position(cx);
if new_dock_position != old_dock_position {
old_dock_position = new_dock_position;
cx.emit(AssistantPanelEvent::DockPositionChanged);
}
- }),
- ];
+ })];
this
})
@@ -198,40 +209,64 @@ impl AssistantPanel {
})
}
- fn handle_pane_event(
+ fn new_conversation(&mut self, cx: &mut ViewContext) -> ViewHandle {
+ let editor = cx.add_view(|cx| {
+ ConversationEditor::new(
+ self.api_key.clone(),
+ self.languages.clone(),
+ self.fs.clone(),
+ cx,
+ )
+ });
+ self.add_conversation(editor.clone(), cx);
+ editor
+ }
+
+ fn add_conversation(
&mut self,
- _pane: ViewHandle,
- event: &pane::Event,
+ editor: ViewHandle,
cx: &mut ViewContext,
) {
- match event {
- pane::Event::ZoomIn => cx.emit(AssistantPanelEvent::ZoomIn),
- pane::Event::ZoomOut => cx.emit(AssistantPanelEvent::ZoomOut),
- pane::Event::Focus => cx.emit(AssistantPanelEvent::Focus),
- pane::Event::Remove => cx.emit(AssistantPanelEvent::Close),
- _ => {}
- }
- }
+ self.subscriptions
+ .push(cx.subscribe(&editor, Self::handle_conversation_editor_event));
- fn add_context(&mut self, cx: &mut ViewContext) {
- let focus = self.has_focus(cx);
- let editor = cx
- .add_view(|cx| AssistantEditor::new(self.api_key.clone(), self.languages.clone(), cx));
+ let conversation = editor.read(cx).conversation.clone();
self.subscriptions
- .push(cx.subscribe(&editor, Self::handle_assistant_editor_event));
- self.pane.update(cx, |pane, cx| {
- pane.add_item(Box::new(editor), true, focus, None, cx)
- });
+ .push(cx.observe(&conversation, |_, _, cx| cx.notify()));
+
+ let index = self.editors.len();
+ self.editors.push(editor);
+ self.set_active_editor_index(Some(index), cx);
}
- fn handle_assistant_editor_event(
+ fn set_active_editor_index(&mut self, index: Option, cx: &mut ViewContext) {
+ self.prev_active_editor_index = self.active_editor_index;
+ self.active_editor_index = index;
+ if let Some(editor) = self.active_editor() {
+ let editor = editor.read(cx).editor.clone();
+ self.toolbar.update(cx, |toolbar, cx| {
+ toolbar.set_active_item(Some(&editor), cx);
+ });
+ if self.has_focus(cx) {
+ cx.focus(&editor);
+ }
+ } else {
+ self.toolbar.update(cx, |toolbar, cx| {
+ toolbar.set_active_item(None, cx);
+ });
+ }
+
+ cx.notify();
+ }
+
+ fn handle_conversation_editor_event(
&mut self,
- _: ViewHandle,
- event: &AssistantEditorEvent,
+ _: ViewHandle,
+ event: &ConversationEditorEvent,
cx: &mut ViewContext,
) {
match event {
- AssistantEditorEvent::TabContentChanged => self.pane.update(cx, |_, cx| cx.notify()),
+ ConversationEditorEvent::TabContentChanged => cx.notify(),
}
}
@@ -262,6 +297,266 @@ impl AssistantPanel {
cx.focus_self();
cx.notify();
}
+
+ fn toggle_zoom(&mut self, _: &workspace::ToggleZoom, cx: &mut ViewContext) {
+ if self.zoomed {
+ cx.emit(AssistantPanelEvent::ZoomOut)
+ } else {
+ cx.emit(AssistantPanelEvent::ZoomIn)
+ }
+ }
+
+ fn deploy(&mut self, action: &search::buffer_search::Deploy, cx: &mut ViewContext) {
+ if let Some(search_bar) = self.toolbar.read(cx).item_of_type::() {
+ if search_bar.update(cx, |search_bar, cx| search_bar.show(action.focus, true, cx)) {
+ return;
+ }
+ }
+ cx.propagate_action();
+ }
+
+ fn handle_editor_cancel(&mut self, _: &editor::Cancel, cx: &mut ViewContext) {
+ if let Some(search_bar) = self.toolbar.read(cx).item_of_type::() {
+ if !search_bar.read(cx).is_dismissed() {
+ search_bar.update(cx, |search_bar, cx| {
+ search_bar.dismiss(&Default::default(), cx)
+ });
+ return;
+ }
+ }
+ cx.propagate_action();
+ }
+
+ fn select_next_match(&mut self, _: &search::SelectNextMatch, cx: &mut ViewContext) {
+ if let Some(search_bar) = self.toolbar.read(cx).item_of_type::() {
+ search_bar.update(cx, |bar, cx| bar.select_match(Direction::Next, cx));
+ }
+ }
+
+ fn select_prev_match(&mut self, _: &search::SelectPrevMatch, cx: &mut ViewContext) {
+ if let Some(search_bar) = self.toolbar.read(cx).item_of_type::() {
+ search_bar.update(cx, |bar, cx| bar.select_match(Direction::Prev, cx));
+ }
+ }
+
+ fn active_editor(&self) -> Option<&ViewHandle> {
+ self.editors.get(self.active_editor_index?)
+ }
+
+ fn render_hamburger_button(cx: &mut ViewContext) -> impl Element {
+ enum ListConversations {}
+ let theme = theme::current(cx);
+ MouseEventHandler::::new(0, cx, |state, _| {
+ let style = theme.assistant.hamburger_button.style_for(state);
+ Svg::for_style(style.icon.clone())
+ .contained()
+ .with_style(style.container)
+ })
+ .with_cursor_style(CursorStyle::PointingHand)
+ .on_click(MouseButton::Left, |_, this: &mut Self, cx| {
+ if this.active_editor().is_some() {
+ this.set_active_editor_index(None, cx);
+ } else {
+ this.set_active_editor_index(this.prev_active_editor_index, cx);
+ }
+ })
+ }
+
+ fn render_editor_tools(&self, cx: &mut ViewContext) -> Vec> {
+ if self.active_editor().is_some() {
+ vec![
+ Self::render_split_button(cx).into_any(),
+ Self::render_quote_button(cx).into_any(),
+ Self::render_assist_button(cx).into_any(),
+ ]
+ } else {
+ Default::default()
+ }
+ }
+
+ fn render_split_button(cx: &mut ViewContext) -> impl Element {
+ let theme = theme::current(cx);
+ let tooltip_style = theme::current(cx).tooltip.clone();
+ MouseEventHandler::::new(0, cx, |state, _| {
+ let style = theme.assistant.split_button.style_for(state);
+ Svg::for_style(style.icon.clone())
+ .contained()
+ .with_style(style.container)
+ })
+ .with_cursor_style(CursorStyle::PointingHand)
+ .on_click(MouseButton::Left, |_, this: &mut Self, cx| {
+ if let Some(active_editor) = this.active_editor() {
+ active_editor.update(cx, |editor, cx| editor.split(&Default::default(), cx));
+ }
+ })
+ .with_tooltip::(
+ 1,
+ "Split Message".into(),
+ Some(Box::new(Split)),
+ tooltip_style,
+ cx,
+ )
+ }
+
+ fn render_assist_button(cx: &mut ViewContext) -> impl Element {
+ let theme = theme::current(cx);
+ let tooltip_style = theme::current(cx).tooltip.clone();
+ MouseEventHandler::::new(0, cx, |state, _| {
+ let style = theme.assistant.assist_button.style_for(state);
+ Svg::for_style(style.icon.clone())
+ .contained()
+ .with_style(style.container)
+ })
+ .with_cursor_style(CursorStyle::PointingHand)
+ .on_click(MouseButton::Left, |_, this: &mut Self, cx| {
+ if let Some(active_editor) = this.active_editor() {
+ active_editor.update(cx, |editor, cx| editor.assist(&Default::default(), cx));
+ }
+ })
+ .with_tooltip::(
+ 1,
+ "Assist".into(),
+ Some(Box::new(Assist)),
+ tooltip_style,
+ cx,
+ )
+ }
+
+ fn render_quote_button(cx: &mut ViewContext) -> impl Element {
+ let theme = theme::current(cx);
+ let tooltip_style = theme::current(cx).tooltip.clone();
+ MouseEventHandler::::new(0, cx, |state, _| {
+ let style = theme.assistant.quote_button.style_for(state);
+ Svg::for_style(style.icon.clone())
+ .contained()
+ .with_style(style.container)
+ })
+ .with_cursor_style(CursorStyle::PointingHand)
+ .on_click(MouseButton::Left, |_, this: &mut Self, cx| {
+ if let Some(workspace) = this.workspace.upgrade(cx) {
+ cx.window_context().defer(move |cx| {
+ workspace.update(cx, |workspace, cx| {
+ ConversationEditor::quote_selection(workspace, &Default::default(), cx)
+ });
+ });
+ }
+ })
+ .with_tooltip::(
+ 1,
+ "Assist".into(),
+ Some(Box::new(QuoteSelection)),
+ tooltip_style,
+ cx,
+ )
+ }
+
+ fn render_plus_button(cx: &mut ViewContext) -> impl Element {
+ enum AddConversation {}
+ let theme = theme::current(cx);
+ MouseEventHandler::::new(0, cx, |state, _| {
+ let style = theme.assistant.plus_button.style_for(state);
+ Svg::for_style(style.icon.clone())
+ .contained()
+ .with_style(style.container)
+ })
+ .with_cursor_style(CursorStyle::PointingHand)
+ .on_click(MouseButton::Left, |_, this: &mut Self, cx| {
+ this.new_conversation(cx);
+ })
+ }
+
+ fn render_zoom_button(&self, cx: &mut ViewContext) -> impl Element {
+ enum ToggleZoomButton {}
+
+ let theme = theme::current(cx);
+ let style = if self.zoomed {
+ &theme.assistant.zoom_out_button
+ } else {
+ &theme.assistant.zoom_in_button
+ };
+
+ MouseEventHandler::::new(0, cx, |state, _| {
+ let style = style.style_for(state);
+ Svg::for_style(style.icon.clone())
+ .contained()
+ .with_style(style.container)
+ })
+ .with_cursor_style(CursorStyle::PointingHand)
+ .on_click(MouseButton::Left, |_, this, cx| {
+ this.toggle_zoom(&ToggleZoom, cx);
+ })
+ }
+
+ fn render_saved_conversation(
+ &mut self,
+ index: usize,
+ cx: &mut ViewContext,
+ ) -> impl Element {
+ let conversation = &self.saved_conversations[index];
+ let path = conversation.path.clone();
+ MouseEventHandler::::new(index, cx, move |state, cx| {
+ let style = &theme::current(cx).assistant.saved_conversation;
+ Flex::row()
+ .with_child(
+ Label::new(
+ conversation.mtime.format("%F %I:%M%p").to_string(),
+ style.saved_at.text.clone(),
+ )
+ .aligned()
+ .contained()
+ .with_style(style.saved_at.container),
+ )
+ .with_child(
+ Label::new(conversation.title.clone(), style.title.text.clone())
+ .aligned()
+ .contained()
+ .with_style(style.title.container),
+ )
+ .contained()
+ .with_style(*style.container.style_for(state))
+ })
+ .with_cursor_style(CursorStyle::PointingHand)
+ .on_click(MouseButton::Left, move |_, this, cx| {
+ this.open_conversation(path.clone(), cx)
+ .detach_and_log_err(cx)
+ })
+ }
+
+ fn open_conversation(&mut self, path: PathBuf, cx: &mut ViewContext) -> Task> {
+ if let Some(ix) = self.editor_index_for_path(&path, cx) {
+ self.set_active_editor_index(Some(ix), cx);
+ return Task::ready(Ok(()));
+ }
+
+ let fs = self.fs.clone();
+ let api_key = self.api_key.clone();
+ let languages = self.languages.clone();
+ cx.spawn(|this, mut cx| async move {
+ let saved_conversation = fs.load(&path).await?;
+ let saved_conversation = serde_json::from_str(&saved_conversation)?;
+ let conversation = cx.add_model(|cx| {
+ Conversation::deserialize(saved_conversation, path.clone(), api_key, languages, cx)
+ });
+ this.update(&mut cx, |this, cx| {
+ // If, by the time we've loaded the conversation, the user has already opened
+ // the same conversation, we don't want to open it again.
+ if let Some(ix) = this.editor_index_for_path(&path, cx) {
+ this.set_active_editor_index(Some(ix), cx);
+ } else {
+ let editor = cx
+ .add_view(|cx| ConversationEditor::for_conversation(conversation, fs, cx));
+ this.add_conversation(editor, cx);
+ }
+ })?;
+ Ok(())
+ })
+ }
+
+ fn editor_index_for_path(&self, path: &Path, cx: &AppContext) -> Option {
+ self.editors
+ .iter()
+ .position(|editor| editor.read(cx).conversation.read(cx).path.as_deref() == Some(path))
+ }
}
fn build_api_key_editor(cx: &mut ViewContext) -> ViewHandle {
@@ -285,7 +580,8 @@ impl View for AssistantPanel {
}
fn render(&mut self, cx: &mut ViewContext) -> AnyElement {
- let style = &theme::current(cx).assistant;
+ let theme = &theme::current(cx);
+ let style = &theme.assistant;
if let Some(api_key_editor) = self.api_key_editor.as_ref() {
Flex::column()
.with_child(
@@ -306,19 +602,76 @@ impl View for AssistantPanel {
.aligned()
.into_any()
} else {
- ChildView::new(&self.pane, cx).into_any()
+ let title = self.active_editor().map(|editor| {
+ Label::new(editor.read(cx).title(cx), style.title.text.clone())
+ .contained()
+ .with_style(style.title.container)
+ .aligned()
+ .left()
+ .flex(1., false)
+ });
+
+ Flex::column()
+ .with_child(
+ Flex::row()
+ .with_child(Self::render_hamburger_button(cx).aligned())
+ .with_children(title)
+ .with_children(
+ self.render_editor_tools(cx)
+ .into_iter()
+ .map(|tool| tool.aligned().flex_float()),
+ )
+ .with_child(Self::render_plus_button(cx).aligned().flex_float())
+ .with_child(self.render_zoom_button(cx).aligned())
+ .contained()
+ .with_style(theme.workspace.tab_bar.container)
+ .expanded()
+ .constrained()
+ .with_height(theme.workspace.tab_bar.height),
+ )
+ .with_children(if self.toolbar.read(cx).hidden() {
+ None
+ } else {
+ Some(ChildView::new(&self.toolbar, cx).expanded())
+ })
+ .with_child(if let Some(editor) = self.active_editor() {
+ ChildView::new(editor, cx).flex(1., true).into_any()
+ } else {
+ UniformList::new(
+ self.saved_conversations_list_state.clone(),
+ self.saved_conversations.len(),
+ cx,
+ |this, range, items, cx| {
+ for ix in range {
+ items.push(this.render_saved_conversation(ix, cx).into_any());
+ }
+ },
+ )
+ .flex(1., true)
+ .into_any()
+ })
+ .into_any()
}
}
fn focus_in(&mut self, _: gpui::AnyViewHandle, cx: &mut ViewContext) {
+ self.has_focus = true;
+ self.toolbar
+ .update(cx, |toolbar, cx| toolbar.focus_changed(true, cx));
if cx.is_self_focused() {
- if let Some(api_key_editor) = self.api_key_editor.as_ref() {
+ if let Some(editor) = self.active_editor() {
+ cx.focus(editor);
+ } else if let Some(api_key_editor) = self.api_key_editor.as_ref() {
cx.focus(api_key_editor);
- } else {
- cx.focus(&self.pane);
}
}
}
+
+ fn focus_out(&mut self, _: gpui::AnyViewHandle, cx: &mut ViewContext) {
+ self.has_focus = false;
+ self.toolbar
+ .update(cx, |toolbar, cx| toolbar.focus_changed(false, cx));
+ }
}
impl Panel for AssistantPanel {
@@ -371,19 +724,22 @@ impl Panel for AssistantPanel {
matches!(event, AssistantPanelEvent::ZoomOut)
}
- fn is_zoomed(&self, cx: &WindowContext) -> bool {
- self.pane.read(cx).is_zoomed()
+ fn is_zoomed(&self, _: &WindowContext) -> bool {
+ self.zoomed
}
fn set_zoomed(&mut self, zoomed: bool, cx: &mut ViewContext) {
- self.pane.update(cx, |pane, cx| pane.set_zoomed(zoomed, cx));
+ self.zoomed = zoomed;
+ cx.notify();
}
fn set_active(&mut self, active: bool, cx: &mut ViewContext) {
if active {
if self.api_key.borrow().is_none() && !self.has_read_credentials {
self.has_read_credentials = true;
- let api_key = if let Some((_, api_key)) = cx
+ let api_key = if let Ok(api_key) = env::var("OPENAI_API_KEY") {
+ Some(api_key)
+ } else if let Some((_, api_key)) = cx
.platform()
.read_credentials(OPENAI_API_URL)
.log_err()
@@ -401,8 +757,8 @@ impl Panel for AssistantPanel {
}
}
- if self.pane.read(cx).items_len() == 0 {
- self.add_context(cx);
+ if self.editors.is_empty() {
+ self.new_conversation(cx);
}
}
}
@@ -427,12 +783,8 @@ impl Panel for AssistantPanel {
matches!(event, AssistantPanelEvent::Close)
}
- fn has_focus(&self, cx: &WindowContext) -> bool {
- self.pane.read(cx).has_focus()
- || self
- .api_key_editor
- .as_ref()
- .map_or(false, |editor| editor.is_focused(cx))
+ fn has_focus(&self, _: &WindowContext) -> bool {
+ self.has_focus
}
fn is_focus_event(event: &Self::Event) -> bool {
@@ -440,18 +792,24 @@ impl Panel for AssistantPanel {
}
}
-enum AssistantEvent {
+enum ConversationEvent {
MessagesEdited,
SummaryChanged,
StreamedCompletion,
}
-struct Assistant {
+#[derive(Default)]
+struct Summary {
+ text: String,
+ done: bool,
+}
+
+struct Conversation {
buffer: ModelHandle,
message_anchors: Vec,
messages_metadata: HashMap,
next_message_id: MessageId,
- summary: Option,
+ summary: Option,
pending_summary: Task