From 88bf8872c191cd93d3ec7de196d7d05d0b556a54 Mon Sep 17 00:00:00 2001 From: Antonio Scandurra Date: Mon, 26 Jun 2023 19:17:16 +0200 Subject: [PATCH] Introduce the ability to load and save conversations with the assistant (#2623) Closes https://linear.app/zed-industries/issue/Z-1890/save-assistant-conversations-to-the-filesystem Closes https://linear.app/zed-industries/issue/Z-2459/cycling-message-roles-on-the-last-empty-message-alters-the-message Closes https://linear.app/zed-industries/issue/Z-2460/cycling-role-in-an-empty-message-cycles-wrong-messages-role Closes https://linear.app/zed-industries/issue/Z-2365/assistant-toolbar Closes https://linear.app/zed-industries/issue/Z-2461/always-insert-an-empty-message-at-the-end-of-the-conversation Release Notes: - You can now save conversations with the assistant to `~/.config/zed/conversations` with `cmd-s`. Conversations are also automatically saved as they are edited. --- Cargo.lock | 2 + assets/icons/assist_15.svg | 1 + assets/icons/hamburger_15.svg | 3 + assets/icons/quote_15.svg | 1 + assets/icons/split_message_15.svg | 1 + assets/keymaps/default.json | 16 +- assets/settings/default.json | 54 +- crates/ai/Cargo.toml | 4 +- crates/ai/src/ai.rs | 92 +- crates/ai/src/assistant.rs | 1378 ++++++++++++++------ crates/gpui/src/elements/label.rs | 1 + crates/gpui/src/elements/svg.rs | 37 +- crates/project_panel/src/project_panel.rs | 1 + crates/search/src/buffer_search.rs | 10 +- crates/terminal_view/src/terminal_panel.rs | 1 + crates/theme/src/theme.rs | 23 +- crates/theme/src/ui.rs | 30 +- crates/util/src/paths.rs | 1 + crates/workspace/src/dock.rs | 3 +- crates/workspace/src/pane.rs | 13 +- crates/workspace/src/toolbar.rs | 74 +- crates/workspace/src/workspace.rs | 17 +- styles/src/styleTree/assistant.ts | 193 ++- 23 files changed, 1445 insertions(+), 511 deletions(-) create mode 100644 assets/icons/assist_15.svg create mode 100644 assets/icons/hamburger_15.svg create mode 100644 assets/icons/quote_15.svg create mode 100644 assets/icons/split_message_15.svg diff --git a/Cargo.lock b/Cargo.lock index 5fe57567114c40f57485aafa452ec684bcce919b..63287f29c179eeae09fbeca0365654b7128adbde 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 a642697a3765e81c62b2c7808847c9be29535a88..e6727e7a0df69b2397457d6f694de25566dfdb6f 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>, completion_count: usize, pending_completions: Vec, @@ -460,14 +818,16 @@ struct Assistant { max_token_count: usize, pending_token_count: Task>, api_key: Rc>>, + pending_save: Task>, + path: Option, _subscriptions: Vec, } -impl Entity for Assistant { - type Event = AssistantEvent; +impl Entity for Conversation { + type Event = ConversationEvent; } -impl Assistant { +impl Conversation { fn new( api_key: Rc>>, language_registry: Arc, @@ -505,6 +865,8 @@ impl Assistant { pending_token_count: Task::ready(None), model: model.into(), _subscriptions: vec![cx.subscribe(&buffer, Self::handle_buffer_event)], + pending_save: Task::ready(Ok(())), + path: None, api_key, buffer, }; @@ -526,6 +888,88 @@ impl Assistant { this } + fn serialize(&self, cx: &AppContext) -> SavedConversation { + SavedConversation { + zed: "conversation".into(), + version: SavedConversation::VERSION.into(), + text: self.buffer.read(cx).text(), + message_metadata: self.messages_metadata.clone(), + messages: self + .messages(cx) + .map(|message| SavedMessage { + id: message.id, + start: message.offset_range.start, + }) + .collect(), + summary: self + .summary + .as_ref() + .map(|summary| summary.text.clone()) + .unwrap_or_default(), + model: self.model.clone(), + } + } + + fn deserialize( + saved_conversation: SavedConversation, + path: PathBuf, + api_key: Rc>>, + language_registry: Arc, + cx: &mut ModelContext, + ) -> Self { + let model = saved_conversation.model; + let markdown = language_registry.language_for_name("Markdown"); + let mut message_anchors = Vec::new(); + let mut next_message_id = MessageId(0); + let buffer = cx.add_model(|cx| { + let mut buffer = Buffer::new(0, saved_conversation.text, cx); + for message in saved_conversation.messages { + message_anchors.push(MessageAnchor { + id: message.id, + start: buffer.anchor_before(message.start), + }); + next_message_id = cmp::max(next_message_id, MessageId(message.id.0 + 1)); + } + buffer.set_language_registry(language_registry); + cx.spawn_weak(|buffer, mut cx| async move { + let markdown = markdown.await?; + let buffer = buffer + .upgrade(&cx) + .ok_or_else(|| anyhow!("buffer was dropped"))?; + buffer.update(&mut cx, |buffer, cx| { + buffer.set_language(Some(markdown), cx) + }); + anyhow::Ok(()) + }) + .detach_and_log_err(cx); + buffer + }); + + let mut this = Self { + message_anchors, + messages_metadata: saved_conversation.message_metadata, + next_message_id, + summary: Some(Summary { + text: saved_conversation.summary, + done: true, + }), + pending_summary: Task::ready(None), + completion_count: Default::default(), + pending_completions: Default::default(), + token_count: None, + max_token_count: tiktoken_rs::model::get_context_size(&model), + pending_token_count: Task::ready(None), + model, + _subscriptions: vec![cx.subscribe(&buffer, Self::handle_buffer_event)], + pending_save: Task::ready(Ok(())), + path: Some(path), + api_key, + buffer, + }; + this.count_remaining_tokens(cx); + this + } + fn handle_buffer_event( &mut self, _: ModelHandle, @@ -535,7 +979,7 @@ impl Assistant { match event { language::Event::Edited => { self.count_remaining_tokens(cx); - cx.emit(AssistantEvent::MessagesEdited); + cx.emit(ConversationEvent::MessagesEdited); } _ => {} } @@ -552,7 +996,11 @@ impl Assistant { Role::Assistant => "assistant".into(), Role::System => "system".into(), }, - content: self.buffer.read(cx).text_for_range(message.range).collect(), + content: self + .buffer + .read(cx) + .text_for_range(message.offset_range) + .collect(), name: None, }) }) @@ -567,7 +1015,7 @@ impl Assistant { .await?; this.upgrade(&cx) - .ok_or_else(|| anyhow!("assistant was dropped"))? + .ok_or_else(|| anyhow!("conversation was dropped"))? .update(&mut cx, |this, cx| { this.max_token_count = tiktoken_rs::model::get_context_size(&this.model); this.token_count = Some(token_count); @@ -596,6 +1044,14 @@ impl Assistant { ) -> Vec { let mut user_messages = Vec::new(); let mut tasks = Vec::new(); + + let last_message_id = self.message_anchors.iter().rev().find_map(|message| { + message + .start + .is_valid(self.buffer.read(cx)) + .then_some(message.id) + }); + for selected_message_id in selected_messages { let selected_message_role = if let Some(metadata) = self.messages_metadata.get(&selected_message_id) { @@ -658,6 +1114,19 @@ impl Assistant { ) .unwrap(); + // Queue up the user's next reply + if Some(selected_message_id) == last_message_id { + let user_message = self + .insert_message_after( + assistant_message.id, + Role::User, + MessageStatus::Done, + cx, + ) + .unwrap(); + user_messages.push(user_message); + } + tasks.push(cx.spawn_weak({ |this, mut cx| async move { let assistant_message_id = assistant_message.id; @@ -668,7 +1137,7 @@ impl Assistant { let mut message = message?; if let Some(choice) = message.choices.pop() { this.upgrade(&cx) - .ok_or_else(|| anyhow!("assistant was dropped"))? + .ok_or_else(|| anyhow!("conversation was dropped"))? .update(&mut cx, |this, cx| { let text: Arc = choice.delta.content?.into(); let message_ix = this.message_anchors.iter().position( @@ -686,7 +1155,7 @@ impl Assistant { }); buffer.edit([(offset..offset, text)], None, cx); }); - cx.emit(AssistantEvent::StreamedCompletion); + cx.emit(ConversationEvent::StreamedCompletion); Some(()) }); @@ -695,7 +1164,7 @@ impl Assistant { } this.upgrade(&cx) - .ok_or_else(|| anyhow!("assistant was dropped"))? + .ok_or_else(|| anyhow!("conversation was dropped"))? .update(&mut cx, |this, cx| { this.pending_completions.retain(|completion| { completion.id != this.completion_count @@ -749,7 +1218,7 @@ impl Assistant { for id in ids { if let Some(metadata) = self.messages_metadata.get_mut(&id) { metadata.role.cycle(); - cx.emit(AssistantEvent::MessagesEdited); + cx.emit(ConversationEvent::MessagesEdited); cx.notify(); } } @@ -767,10 +1236,19 @@ impl Assistant { .iter() .position(|message| message.id == message_id) { + // Find the next valid message after the one we were given. + let mut next_message_ix = prev_message_ix + 1; + while let Some(next_message) = self.message_anchors.get(next_message_ix) { + if next_message.start.is_valid(self.buffer.read(cx)) { + break; + } + next_message_ix += 1; + } + let start = self.buffer.update(cx, |buffer, cx| { - let offset = self.message_anchors[prev_message_ix + 1..] - .iter() - .find(|message| message.start.is_valid(buffer)) + let offset = self + .message_anchors + .get(next_message_ix) .map_or(buffer.len(), |message| message.start.to_offset(buffer) - 1); buffer.edit([(offset..offset, "\n")], None, cx); buffer.anchor_before(offset + 1) @@ -780,7 +1258,7 @@ impl Assistant { start, }; self.message_anchors - .insert(prev_message_ix + 1, message.clone()); + .insert(next_message_ix, message.clone()); self.messages_metadata.insert( message.id, MessageMetadata { @@ -789,7 +1267,7 @@ impl Assistant { status, }, ); - cx.emit(AssistantEvent::MessagesEdited); + cx.emit(ConversationEvent::MessagesEdited); Some(message) } else { None @@ -805,7 +1283,7 @@ impl Assistant { let end_message = self.message_for_offset(range.end, cx); if let Some((start_message, end_message)) = start_message.zip(end_message) { // Prevent splitting when range spans multiple messages. - if start_message.index != end_message.index { + if start_message.id != end_message.id { return (None, None); } @@ -814,7 +1292,8 @@ impl Assistant { let mut edited_buffer = false; let mut suffix_start = None; - if range.start > message.range.start && range.end < message.range.end - 1 { + if range.start > message.offset_range.start && range.end < message.offset_range.end - 1 + { if self.buffer.read(cx).chars_at(range.end).next() == Some('\n') { suffix_start = Some(range.end + 1); } else if self.buffer.read(cx).reversed_chars_at(range.end).next() == Some('\n') { @@ -839,7 +1318,7 @@ impl Assistant { }; self.message_anchors - .insert(message.index + 1, suffix.clone()); + .insert(message.index_range.end + 1, suffix.clone()); self.messages_metadata.insert( suffix.id, MessageMetadata { @@ -849,52 +1328,55 @@ impl Assistant { }, ); - let new_messages = if range.start == range.end || range.start == message.range.start { - (None, Some(suffix)) - } else { - let mut prefix_end = None; - if range.start > message.range.start && range.end < message.range.end - 1 { - if self.buffer.read(cx).chars_at(range.start).next() == Some('\n') { - prefix_end = Some(range.start + 1); - } else if self.buffer.read(cx).reversed_chars_at(range.start).next() - == Some('\n') + let new_messages = + if range.start == range.end || range.start == message.offset_range.start { + (None, Some(suffix)) + } else { + let mut prefix_end = None; + if range.start > message.offset_range.start + && range.end < message.offset_range.end - 1 { - prefix_end = Some(range.start); + if self.buffer.read(cx).chars_at(range.start).next() == Some('\n') { + prefix_end = Some(range.start + 1); + } else if self.buffer.read(cx).reversed_chars_at(range.start).next() + == Some('\n') + { + prefix_end = Some(range.start); + } } - } - let selection = if let Some(prefix_end) = prefix_end { - cx.emit(AssistantEvent::MessagesEdited); - MessageAnchor { - id: MessageId(post_inc(&mut self.next_message_id.0)), - start: self.buffer.read(cx).anchor_before(prefix_end), - } - } else { - self.buffer.update(cx, |buffer, cx| { - buffer.edit([(range.start..range.start, "\n")], None, cx) - }); - edited_buffer = true; - MessageAnchor { - id: MessageId(post_inc(&mut self.next_message_id.0)), - start: self.buffer.read(cx).anchor_before(range.end + 1), - } - }; + let selection = if let Some(prefix_end) = prefix_end { + cx.emit(ConversationEvent::MessagesEdited); + MessageAnchor { + id: MessageId(post_inc(&mut self.next_message_id.0)), + start: self.buffer.read(cx).anchor_before(prefix_end), + } + } else { + self.buffer.update(cx, |buffer, cx| { + buffer.edit([(range.start..range.start, "\n")], None, cx) + }); + edited_buffer = true; + MessageAnchor { + id: MessageId(post_inc(&mut self.next_message_id.0)), + start: self.buffer.read(cx).anchor_before(range.end + 1), + } + }; - self.message_anchors - .insert(message.index + 1, selection.clone()); - self.messages_metadata.insert( - selection.id, - MessageMetadata { - role, - sent_at: Local::now(), - status: MessageStatus::Done, - }, - ); - (Some(selection), Some(suffix)) - }; + self.message_anchors + .insert(message.index_range.end + 1, selection.clone()); + self.messages_metadata.insert( + selection.id, + MessageMetadata { + role, + sent_at: Local::now(), + status: MessageStatus::Done, + }, + ); + (Some(selection), Some(suffix)) + }; if !edited_buffer { - cx.emit(AssistantEvent::MessagesEdited); + cx.emit(ConversationEvent::MessagesEdited); } new_messages } else { @@ -932,12 +1414,22 @@ impl Assistant { if let Some(choice) = message.choices.pop() { let text = choice.delta.content.unwrap_or_default(); this.update(&mut cx, |this, cx| { - this.summary.get_or_insert(String::new()).push_str(&text); - cx.emit(AssistantEvent::SummaryChanged); + this.summary + .get_or_insert(Default::default()) + .text + .push_str(&text); + cx.emit(ConversationEvent::SummaryChanged); }); } } + this.update(&mut cx, |this, cx| { + if let Some(summary) = this.summary.as_mut() { + summary.done = true; + cx.emit(ConversationEvent::SummaryChanged); + } + }); + anyhow::Ok(()) } .log_err() @@ -957,21 +1449,21 @@ impl Assistant { ) -> Vec { let mut result = Vec::new(); - let buffer_len = self.buffer.read(cx).len(); let mut messages = self.messages(cx).peekable(); let mut offsets = offsets.into_iter().peekable(); + let mut current_message = messages.next(); while let Some(offset) = offsets.next() { - // Skip messages that start after the offset. - while messages.peek().map_or(false, |message| { - message.range.end < offset || (message.range.end == offset && offset < buffer_len) + // Locate the message that contains the offset. + while current_message.as_ref().map_or(false, |message| { + !message.offset_range.contains(&offset) && messages.peek().is_some() }) { - messages.next(); + current_message = messages.next(); } - let Some(message) = messages.peek() else { continue }; + let Some(message) = current_message.as_ref() else { break }; // Skip offsets that are in the same message. while offsets.peek().map_or(false, |offset| { - message.range.contains(offset) || message.range.end == buffer_len + message.offset_range.contains(offset) || messages.peek().is_none() }) { offsets.next(); } @@ -985,15 +1477,17 @@ impl Assistant { let buffer = self.buffer.read(cx); let mut message_anchors = self.message_anchors.iter().enumerate().peekable(); iter::from_fn(move || { - while let Some((ix, message_anchor)) = message_anchors.next() { + while let Some((start_ix, message_anchor)) = message_anchors.next() { let metadata = self.messages_metadata.get(&message_anchor.id)?; let message_start = message_anchor.start.to_offset(buffer); let mut message_end = None; + let mut end_ix = start_ix; while let Some((_, next_message)) = message_anchors.peek() { if next_message.start.is_valid(buffer) { message_end = Some(next_message.start); break; } else { + end_ix += 1; message_anchors.next(); } } @@ -1001,8 +1495,8 @@ impl Assistant { .unwrap_or(language::Anchor::MAX) .to_offset(buffer); return Some(Message { - index: ix, - range: message_start..message_end, + index_range: start_ix..end_ix, + offset_range: message_start..message_end, id: message_anchor.id, anchor: message_anchor.start, role: metadata.role, @@ -1013,6 +1507,63 @@ impl Assistant { None }) } + + fn save( + &mut self, + debounce: Option, + fs: Arc, + cx: &mut ModelContext, + ) { + self.pending_save = cx.spawn(|this, mut cx| async move { + if let Some(debounce) = debounce { + cx.background().timer(debounce).await; + } + + let (old_path, summary) = this.read_with(&cx, |this, _| { + let path = this.path.clone(); + let summary = if let Some(summary) = this.summary.as_ref() { + if summary.done { + Some(summary.text.clone()) + } else { + None + } + } else { + None + }; + (path, summary) + }); + + if let Some(summary) = summary { + let conversation = this.read_with(&cx, |this, cx| this.serialize(cx)); + let path = if let Some(old_path) = old_path { + old_path + } else { + let mut discriminant = 1; + let mut new_path; + loop { + new_path = CONVERSATIONS_DIR.join(&format!( + "{} - {}.zed.json", + summary.trim(), + discriminant + )); + if fs.is_file(&new_path).await { + discriminant += 1; + } else { + break; + } + } + new_path + }; + + fs.create_dir(CONVERSATIONS_DIR.as_ref()).await?; + fs.atomic_write(path.clone(), serde_json::to_string(&conversation).unwrap()) + .await?; + this.update(&mut cx, |this, _| this.path = Some(path)); + } + + Ok(()) + }); + } } struct PendingCompletion { @@ -1020,7 +1571,7 @@ struct PendingCompletion { _tasks: Vec>, } -enum AssistantEditorEvent { +enum ConversationEditorEvent { TabContentChanged, } @@ -1030,39 +1581,50 @@ struct ScrollPosition { cursor: Anchor, } -struct AssistantEditor { - assistant: ModelHandle, +struct ConversationEditor { + conversation: ModelHandle, + fs: Arc, editor: ViewHandle, blocks: HashSet, scroll_position: Option, _subscriptions: Vec, } -impl AssistantEditor { +impl ConversationEditor { fn new( api_key: Rc>>, language_registry: Arc, + fs: Arc, + cx: &mut ViewContext, + ) -> Self { + let conversation = cx.add_model(|cx| Conversation::new(api_key, language_registry, cx)); + Self::for_conversation(conversation, fs, cx) + } + + fn for_conversation( + conversation: ModelHandle, + fs: Arc, cx: &mut ViewContext, ) -> Self { - let assistant = cx.add_model(|cx| Assistant::new(api_key, language_registry, cx)); let editor = cx.add_view(|cx| { - let mut editor = Editor::for_buffer(assistant.read(cx).buffer.clone(), None, cx); + let mut editor = Editor::for_buffer(conversation.read(cx).buffer.clone(), None, cx); editor.set_soft_wrap_mode(SoftWrap::EditorWidth, cx); editor.set_show_gutter(false, cx); editor }); let _subscriptions = vec![ - cx.observe(&assistant, |_, _, cx| cx.notify()), - cx.subscribe(&assistant, Self::handle_assistant_event), + cx.observe(&conversation, |_, _, cx| cx.notify()), + cx.subscribe(&conversation, Self::handle_conversation_event), cx.subscribe(&editor, Self::handle_editor_event), ]; let mut this = Self { - assistant, + conversation, editor, blocks: Default::default(), scroll_position: None, + fs, _subscriptions, }; this.update_message_headers(cx); @@ -1072,20 +1634,20 @@ impl AssistantEditor { fn assist(&mut self, _: &Assist, cx: &mut ViewContext) { let cursors = self.cursors(cx); - let user_messages = self.assistant.update(cx, |assistant, cx| { - let selected_messages = assistant + let user_messages = self.conversation.update(cx, |conversation, cx| { + let selected_messages = conversation .messages_for_offsets(cursors, cx) .into_iter() .map(|message| message.id) .collect(); - assistant.assist(selected_messages, cx) + conversation.assist(selected_messages, cx) }); let new_selections = user_messages .iter() .map(|message| { let cursor = message .start - .to_offset(self.assistant.read(cx).buffer.read(cx)); + .to_offset(self.conversation.read(cx).buffer.read(cx)); cursor..cursor }) .collect::>(); @@ -1102,8 +1664,8 @@ impl AssistantEditor { fn cancel_last_assist(&mut self, _: &editor::Cancel, cx: &mut ViewContext) { if !self - .assistant - .update(cx, |assistant, _| assistant.cancel_last_assist()) + .conversation + .update(cx, |conversation, _| conversation.cancel_last_assist()) { cx.propagate_action(); } @@ -1111,13 +1673,13 @@ impl AssistantEditor { fn cycle_message_role(&mut self, _: &CycleMessageRole, cx: &mut ViewContext) { let cursors = self.cursors(cx); - self.assistant.update(cx, |assistant, cx| { - let messages = assistant + self.conversation.update(cx, |conversation, cx| { + let messages = conversation .messages_for_offsets(cursors, cx) .into_iter() .map(|message| message.id) .collect(); - assistant.cycle_message_roles(messages, cx) + conversation.cycle_message_roles(messages, cx) }); } @@ -1129,18 +1691,26 @@ impl AssistantEditor { .collect() } - fn handle_assistant_event( + fn handle_conversation_event( &mut self, - _: ModelHandle, - event: &AssistantEvent, + _: ModelHandle, + event: &ConversationEvent, cx: &mut ViewContext, ) { match event { - AssistantEvent::MessagesEdited => self.update_message_headers(cx), - AssistantEvent::SummaryChanged => { - cx.emit(AssistantEditorEvent::TabContentChanged); + ConversationEvent::MessagesEdited => { + self.update_message_headers(cx); + self.conversation.update(cx, |conversation, cx| { + conversation.save(Some(Duration::from_millis(500)), self.fs.clone(), cx); + }); } - AssistantEvent::StreamedCompletion => { + ConversationEvent::SummaryChanged => { + cx.emit(ConversationEditorEvent::TabContentChanged); + self.conversation.update(cx, |conversation, cx| { + conversation.save(None, self.fs.clone(), cx); + }); + } + ConversationEvent::StreamedCompletion => { self.editor.update(cx, |editor, cx| { if let Some(scroll_position) = self.scroll_position { let snapshot = editor.snapshot(cx); @@ -1210,7 +1780,7 @@ impl AssistantEditor { let excerpt_id = *buffer.as_singleton().unwrap().0; let old_blocks = std::mem::take(&mut self.blocks); let new_blocks = self - .assistant + .conversation .read(cx) .messages(cx) .map(|message| BlockProperties { @@ -1218,7 +1788,7 @@ impl AssistantEditor { height: 2, style: BlockStyle::Sticky, render: Arc::new({ - let assistant = self.assistant.clone(); + let conversation = self.conversation.clone(); // let metadata = message.metadata.clone(); // let message = message.clone(); move |cx| { @@ -1254,10 +1824,10 @@ impl AssistantEditor { ) .with_cursor_style(CursorStyle::PointingHand) .on_down(MouseButton::Left, { - let assistant = assistant.clone(); + let conversation = conversation.clone(); move |_, _, cx| { - assistant.update(cx, |assistant, cx| { - assistant.cycle_message_roles( + conversation.update(cx, |conversation, cx| { + conversation.cycle_message_roles( HashSet::from_iter(Some(message_id)), cx, ) @@ -1301,7 +1871,7 @@ impl AssistantEditor { .aligned() .left() .contained() - .with_style(style.header) + .with_style(style.message_header) .into_any() } }), @@ -1362,41 +1932,36 @@ impl AssistantEditor { if let Some(text) = text { panel.update(cx, |panel, cx| { - if let Some(assistant) = panel - .pane - .read(cx) - .active_item() - .and_then(|item| item.downcast::()) - .ok_or_else(|| anyhow!("no active context")) - .log_err() - { - assistant.update(cx, |assistant, cx| { - assistant - .editor - .update(cx, |editor, cx| editor.insert(&text, cx)) - }); - } + let conversation = panel + .active_editor() + .cloned() + .unwrap_or_else(|| panel.new_conversation(cx)); + conversation.update(cx, |conversation, cx| { + conversation + .editor + .update(cx, |editor, cx| editor.insert(&text, cx)) + }); }); } } fn copy(&mut self, _: &editor::Copy, cx: &mut ViewContext) { let editor = self.editor.read(cx); - let assistant = self.assistant.read(cx); + let conversation = self.conversation.read(cx); if editor.selections.count() == 1 { let selection = editor.selections.newest::(cx); let mut copied_text = String::new(); let mut spanned_messages = 0; - for message in assistant.messages(cx) { - if message.range.start >= selection.range().end { + for message in conversation.messages(cx) { + if message.offset_range.start >= selection.range().end { break; - } else if message.range.end >= selection.range().start { - let range = cmp::max(message.range.start, selection.range().start) - ..cmp::min(message.range.end, selection.range().end); + } else if message.offset_range.end >= selection.range().start { + let range = cmp::max(message.offset_range.start, selection.range().start) + ..cmp::min(message.offset_range.end, selection.range().end); if !range.is_empty() { spanned_messages += 1; write!(&mut copied_text, "## {}\n\n", message.role).unwrap(); - for chunk in assistant.buffer.read(cx).text_for_range(range) { + for chunk in conversation.buffer.read(cx).text_for_range(range) { copied_text.push_str(&chunk); } copied_text.push('\n'); @@ -1415,65 +1980,93 @@ impl AssistantEditor { } fn split(&mut self, _: &Split, cx: &mut ViewContext) { - self.assistant.update(cx, |assistant, cx| { + self.conversation.update(cx, |conversation, cx| { let selections = self.editor.read(cx).selections.disjoint_anchors(); for selection in selections.into_iter() { let buffer = self.editor.read(cx).buffer().read(cx).snapshot(cx); let range = selection .map(|endpoint| endpoint.to_offset(&buffer)) .range(); - assistant.split_message(range, cx); + conversation.split_message(range, cx); } }); } + fn save(&mut self, _: &Save, cx: &mut ViewContext) { + self.conversation.update(cx, |conversation, cx| { + conversation.save(None, self.fs.clone(), cx) + }); + } + fn cycle_model(&mut self, cx: &mut ViewContext) { - self.assistant.update(cx, |assistant, cx| { - let new_model = match assistant.model.as_str() { + self.conversation.update(cx, |conversation, cx| { + let new_model = match conversation.model.as_str() { "gpt-4-0613" => "gpt-3.5-turbo-0613", _ => "gpt-4-0613", }; - assistant.set_model(new_model.into(), cx); + conversation.set_model(new_model.into(), cx); }); } fn title(&self, cx: &AppContext) -> String { - self.assistant + self.conversation .read(cx) .summary - .clone() - .unwrap_or_else(|| "New Context".into()) + .as_ref() + .map(|summary| summary.text.clone()) + .unwrap_or_else(|| "New Conversation".into()) } -} -impl Entity for AssistantEditor { - type Event = AssistantEditorEvent; -} + fn render_current_model( + &self, + style: &AssistantStyle, + cx: &mut ViewContext, + ) -> impl Element { + enum Model {} -impl View for AssistantEditor { - fn ui_name() -> &'static str { - "AssistantEditor" + MouseEventHandler::::new(0, cx, |state, cx| { + let style = style.model.style_for(state); + Label::new(self.conversation.read(cx).model.clone(), style.text.clone()) + .contained() + .with_style(style.container) + }) + .with_cursor_style(CursorStyle::PointingHand) + .on_click(MouseButton::Left, |_, this, cx| this.cycle_model(cx)) } - fn render(&mut self, cx: &mut ViewContext) -> AnyElement { - enum Model {} - let theme = &theme::current(cx).assistant; - let assistant = &self.assistant.read(cx); - let model = assistant.model.clone(); - let remaining_tokens = assistant.remaining_tokens().map(|remaining_tokens| { - let remaining_tokens_style = if remaining_tokens <= 0 { - &theme.no_remaining_tokens - } else { - &theme.remaining_tokens - }; + fn render_remaining_tokens( + &self, + style: &AssistantStyle, + cx: &mut ViewContext, + ) -> Option> { + let remaining_tokens = self.conversation.read(cx).remaining_tokens()?; + let remaining_tokens_style = if remaining_tokens <= 0 { + &style.no_remaining_tokens + } else { + &style.remaining_tokens + }; + Some( Label::new( remaining_tokens.to_string(), remaining_tokens_style.text.clone(), ) .contained() - .with_style(remaining_tokens_style.container) - }); + .with_style(remaining_tokens_style.container), + ) + } +} + +impl Entity for ConversationEditor { + type Event = ConversationEditorEvent; +} +impl View for ConversationEditor { + fn ui_name() -> &'static str { + "ConversationEditor" + } + + fn render(&mut self, cx: &mut ViewContext) -> AnyElement { + let theme = &theme::current(cx).assistant; Stack::new() .with_child( ChildView::new(&self.editor, cx) @@ -1482,19 +2075,8 @@ impl View for AssistantEditor { ) .with_child( Flex::row() - .with_child( - MouseEventHandler::::new(0, cx, |state, _| { - let style = theme.model.style_for(state); - Label::new(model, style.text.clone()) - .contained() - .with_style(style.container) - }) - .with_cursor_style(CursorStyle::PointingHand) - .on_click(MouseButton::Left, |_, this, cx| this.cycle_model(cx)), - ) - .with_children(remaining_tokens) - .contained() - .with_style(theme.model_info_container) + .with_child(self.render_current_model(theme, cx)) + .with_children(self.render_remaining_tokens(theme, cx)) .aligned() .top() .right(), @@ -1509,56 +2091,16 @@ impl View for AssistantEditor { } } -impl Item for AssistantEditor { - fn tab_content( - &self, - _: Option, - style: &theme::Tab, - cx: &gpui::AppContext, - ) -> AnyElement { - let title = truncate_and_trailoff(&self.title(cx), editor::MAX_TAB_TITLE_LEN); - Label::new(title, style.label.clone()).into_any() - } - - fn tab_tooltip_text(&self, cx: &AppContext) -> Option> { - Some(self.title(cx).into()) - } - - fn as_searchable( - &self, - _: &ViewHandle, - ) -> Option> { - Some(Box::new(self.editor.clone())) - } -} - -#[derive(Copy, Clone, Debug, Default, Eq, PartialEq, Hash)] -struct MessageId(usize); - #[derive(Clone, Debug)] struct MessageAnchor { id: MessageId, start: language::Anchor, } -#[derive(Clone, Debug)] -struct MessageMetadata { - role: Role, - sent_at: DateTime, - status: MessageStatus, -} - -#[derive(Clone, Debug)] -enum MessageStatus { - Pending, - Done, - Error(Arc), -} - #[derive(Clone, Debug)] pub struct Message { - range: Range, - index: usize, + offset_range: Range, + index_range: Range, id: MessageId, anchor: language::Anchor, role: Role, @@ -1569,10 +2111,10 @@ pub struct Message { impl Message { fn to_open_ai_message(&self, buffer: &Buffer) -> RequestMessage { let mut content = format!("[Message {}]\n", self.id.0).to_string(); - content.extend(buffer.text_for_range(self.range.clone())); + content.extend(buffer.text_for_range(self.offset_range.clone())); RequestMessage { role: self.role, - content, + content: content.trim_end().into(), } } } @@ -1666,27 +2208,28 @@ async fn stream_completion( #[cfg(test)] mod tests { use super::*; + use crate::MessageId; use gpui::AppContext; #[gpui::test] fn test_inserting_and_removing_messages(cx: &mut AppContext) { let registry = Arc::new(LanguageRegistry::test()); - let assistant = cx.add_model(|cx| Assistant::new(Default::default(), registry, cx)); - let buffer = assistant.read(cx).buffer.clone(); + let conversation = cx.add_model(|cx| Conversation::new(Default::default(), registry, cx)); + let buffer = conversation.read(cx).buffer.clone(); - let message_1 = assistant.read(cx).message_anchors[0].clone(); + let message_1 = conversation.read(cx).message_anchors[0].clone(); assert_eq!( - messages(&assistant, cx), + messages(&conversation, cx), vec![(message_1.id, Role::User, 0..0)] ); - let message_2 = assistant.update(cx, |assistant, cx| { - assistant + let message_2 = conversation.update(cx, |conversation, cx| { + conversation .insert_message_after(message_1.id, Role::Assistant, MessageStatus::Done, cx) .unwrap() }); assert_eq!( - messages(&assistant, cx), + messages(&conversation, cx), vec![ (message_1.id, Role::User, 0..1), (message_2.id, Role::Assistant, 1..1) @@ -1697,20 +2240,20 @@ mod tests { buffer.edit([(0..0, "1"), (1..1, "2")], None, cx) }); assert_eq!( - messages(&assistant, cx), + messages(&conversation, cx), vec![ (message_1.id, Role::User, 0..2), (message_2.id, Role::Assistant, 2..3) ] ); - let message_3 = assistant.update(cx, |assistant, cx| { - assistant + let message_3 = conversation.update(cx, |conversation, cx| { + conversation .insert_message_after(message_2.id, Role::User, MessageStatus::Done, cx) .unwrap() }); assert_eq!( - messages(&assistant, cx), + messages(&conversation, cx), vec![ (message_1.id, Role::User, 0..2), (message_2.id, Role::Assistant, 2..4), @@ -1718,13 +2261,13 @@ mod tests { ] ); - let message_4 = assistant.update(cx, |assistant, cx| { - assistant + let message_4 = conversation.update(cx, |conversation, cx| { + conversation .insert_message_after(message_2.id, Role::User, MessageStatus::Done, cx) .unwrap() }); assert_eq!( - messages(&assistant, cx), + messages(&conversation, cx), vec![ (message_1.id, Role::User, 0..2), (message_2.id, Role::Assistant, 2..4), @@ -1737,7 +2280,7 @@ mod tests { buffer.edit([(4..4, "C"), (5..5, "D")], None, cx) }); assert_eq!( - messages(&assistant, cx), + messages(&conversation, cx), vec![ (message_1.id, Role::User, 0..2), (message_2.id, Role::Assistant, 2..4), @@ -1749,7 +2292,7 @@ mod tests { // Deleting across message boundaries merges the messages. buffer.update(cx, |buffer, cx| buffer.edit([(1..4, "")], None, cx)); assert_eq!( - messages(&assistant, cx), + messages(&conversation, cx), vec![ (message_1.id, Role::User, 0..3), (message_3.id, Role::User, 3..4), @@ -1759,7 +2302,7 @@ mod tests { // Undoing the deletion should also undo the merge. buffer.update(cx, |buffer, cx| buffer.undo(cx)); assert_eq!( - messages(&assistant, cx), + messages(&conversation, cx), vec![ (message_1.id, Role::User, 0..2), (message_2.id, Role::Assistant, 2..4), @@ -1771,7 +2314,7 @@ mod tests { // Redoing the deletion should also redo the merge. buffer.update(cx, |buffer, cx| buffer.redo(cx)); assert_eq!( - messages(&assistant, cx), + messages(&conversation, cx), vec![ (message_1.id, Role::User, 0..3), (message_3.id, Role::User, 3..4), @@ -1779,13 +2322,13 @@ mod tests { ); // Ensure we can still insert after a merged message. - let message_5 = assistant.update(cx, |assistant, cx| { - assistant + let message_5 = conversation.update(cx, |conversation, cx| { + conversation .insert_message_after(message_1.id, Role::System, MessageStatus::Done, cx) .unwrap() }); assert_eq!( - messages(&assistant, cx), + messages(&conversation, cx), vec![ (message_1.id, Role::User, 0..3), (message_5.id, Role::System, 3..4), @@ -1797,12 +2340,12 @@ mod tests { #[gpui::test] fn test_message_splitting(cx: &mut AppContext) { let registry = Arc::new(LanguageRegistry::test()); - let assistant = cx.add_model(|cx| Assistant::new(Default::default(), registry, cx)); - let buffer = assistant.read(cx).buffer.clone(); + let conversation = cx.add_model(|cx| Conversation::new(Default::default(), registry, cx)); + let buffer = conversation.read(cx).buffer.clone(); - let message_1 = assistant.read(cx).message_anchors[0].clone(); + let message_1 = conversation.read(cx).message_anchors[0].clone(); assert_eq!( - messages(&assistant, cx), + messages(&conversation, cx), vec![(message_1.id, Role::User, 0..0)] ); @@ -1811,13 +2354,13 @@ mod tests { }); let (_, message_2) = - assistant.update(cx, |assistant, cx| assistant.split_message(3..3, cx)); + conversation.update(cx, |conversation, cx| conversation.split_message(3..3, cx)); let message_2 = message_2.unwrap(); // We recycle newlines in the middle of a split message assert_eq!(buffer.read(cx).text(), "aaa\nbbb\nccc\nddd\n"); assert_eq!( - messages(&assistant, cx), + messages(&conversation, cx), vec![ (message_1.id, Role::User, 0..4), (message_2.id, Role::User, 4..16), @@ -1825,13 +2368,13 @@ mod tests { ); let (_, message_3) = - assistant.update(cx, |assistant, cx| assistant.split_message(3..3, cx)); + conversation.update(cx, |conversation, cx| conversation.split_message(3..3, cx)); let message_3 = message_3.unwrap(); // We don't recycle newlines at the end of a split message assert_eq!(buffer.read(cx).text(), "aaa\n\nbbb\nccc\nddd\n"); assert_eq!( - messages(&assistant, cx), + messages(&conversation, cx), vec![ (message_1.id, Role::User, 0..4), (message_3.id, Role::User, 4..5), @@ -1840,11 +2383,11 @@ mod tests { ); let (_, message_4) = - assistant.update(cx, |assistant, cx| assistant.split_message(9..9, cx)); + conversation.update(cx, |conversation, cx| conversation.split_message(9..9, cx)); let message_4 = message_4.unwrap(); assert_eq!(buffer.read(cx).text(), "aaa\n\nbbb\nccc\nddd\n"); assert_eq!( - messages(&assistant, cx), + messages(&conversation, cx), vec![ (message_1.id, Role::User, 0..4), (message_3.id, Role::User, 4..5), @@ -1854,11 +2397,11 @@ mod tests { ); let (_, message_5) = - assistant.update(cx, |assistant, cx| assistant.split_message(9..9, cx)); + conversation.update(cx, |conversation, cx| conversation.split_message(9..9, cx)); let message_5 = message_5.unwrap(); assert_eq!(buffer.read(cx).text(), "aaa\n\nbbb\n\nccc\nddd\n"); assert_eq!( - messages(&assistant, cx), + messages(&conversation, cx), vec![ (message_1.id, Role::User, 0..4), (message_3.id, Role::User, 4..5), @@ -1868,13 +2411,14 @@ mod tests { ] ); - let (message_6, message_7) = - assistant.update(cx, |assistant, cx| assistant.split_message(14..16, cx)); + let (message_6, message_7) = conversation.update(cx, |conversation, cx| { + conversation.split_message(14..16, cx) + }); let message_6 = message_6.unwrap(); let message_7 = message_7.unwrap(); assert_eq!(buffer.read(cx).text(), "aaa\n\nbbb\n\nccc\ndd\nd\n"); assert_eq!( - messages(&assistant, cx), + messages(&conversation, cx), vec![ (message_1.id, Role::User, 0..4), (message_3.id, Role::User, 4..5), @@ -1890,33 +2434,33 @@ mod tests { #[gpui::test] fn test_messages_for_offsets(cx: &mut AppContext) { let registry = Arc::new(LanguageRegistry::test()); - let assistant = cx.add_model(|cx| Assistant::new(Default::default(), registry, cx)); - let buffer = assistant.read(cx).buffer.clone(); + let conversation = cx.add_model(|cx| Conversation::new(Default::default(), registry, cx)); + let buffer = conversation.read(cx).buffer.clone(); - let message_1 = assistant.read(cx).message_anchors[0].clone(); + let message_1 = conversation.read(cx).message_anchors[0].clone(); assert_eq!( - messages(&assistant, cx), + messages(&conversation, cx), vec![(message_1.id, Role::User, 0..0)] ); buffer.update(cx, |buffer, cx| buffer.edit([(0..0, "aaa")], None, cx)); - let message_2 = assistant - .update(cx, |assistant, cx| { - assistant.insert_message_after(message_1.id, Role::User, MessageStatus::Done, cx) + let message_2 = conversation + .update(cx, |conversation, cx| { + conversation.insert_message_after(message_1.id, Role::User, MessageStatus::Done, cx) }) .unwrap(); buffer.update(cx, |buffer, cx| buffer.edit([(4..4, "bbb")], None, cx)); - let message_3 = assistant - .update(cx, |assistant, cx| { - assistant.insert_message_after(message_2.id, Role::User, MessageStatus::Done, cx) + let message_3 = conversation + .update(cx, |conversation, cx| { + conversation.insert_message_after(message_2.id, Role::User, MessageStatus::Done, cx) }) .unwrap(); buffer.update(cx, |buffer, cx| buffer.edit([(8..8, "ccc")], None, cx)); assert_eq!(buffer.read(cx).text(), "aaa\nbbb\nccc"); assert_eq!( - messages(&assistant, cx), + messages(&conversation, cx), vec![ (message_1.id, Role::User, 0..4), (message_2.id, Role::User, 4..8), @@ -1925,20 +2469,40 @@ mod tests { ); assert_eq!( - message_ids_for_offsets(&assistant, &[0, 4, 9], cx), + message_ids_for_offsets(&conversation, &[0, 4, 9], cx), [message_1.id, message_2.id, message_3.id] ); assert_eq!( - message_ids_for_offsets(&assistant, &[0, 1, 11], cx), + message_ids_for_offsets(&conversation, &[0, 1, 11], cx), [message_1.id, message_3.id] ); + let message_4 = conversation + .update(cx, |conversation, cx| { + conversation.insert_message_after(message_3.id, Role::User, MessageStatus::Done, cx) + }) + .unwrap(); + assert_eq!(buffer.read(cx).text(), "aaa\nbbb\nccc\n"); + assert_eq!( + messages(&conversation, cx), + vec![ + (message_1.id, Role::User, 0..4), + (message_2.id, Role::User, 4..8), + (message_3.id, Role::User, 8..12), + (message_4.id, Role::User, 12..12) + ] + ); + assert_eq!( + message_ids_for_offsets(&conversation, &[0, 4, 8, 12], cx), + [message_1.id, message_2.id, message_3.id, message_4.id] + ); + fn message_ids_for_offsets( - assistant: &ModelHandle, + conversation: &ModelHandle, offsets: &[usize], cx: &AppContext, ) -> Vec { - assistant + conversation .read(cx) .messages_for_offsets(offsets.iter().copied(), cx) .into_iter() @@ -1947,14 +2511,72 @@ mod tests { } } + #[gpui::test] + fn test_serialization(cx: &mut AppContext) { + let registry = Arc::new(LanguageRegistry::test()); + let conversation = + cx.add_model(|cx| Conversation::new(Default::default(), registry.clone(), cx)); + let buffer = conversation.read(cx).buffer.clone(); + let message_0 = conversation.read(cx).message_anchors[0].id; + let message_1 = conversation.update(cx, |conversation, cx| { + conversation + .insert_message_after(message_0, Role::Assistant, MessageStatus::Done, cx) + .unwrap() + }); + let message_2 = conversation.update(cx, |conversation, cx| { + conversation + .insert_message_after(message_1.id, Role::System, MessageStatus::Done, cx) + .unwrap() + }); + buffer.update(cx, |buffer, cx| { + buffer.edit([(0..0, "a"), (1..1, "b\nc")], None, cx); + buffer.finalize_last_transaction(); + }); + let _message_3 = conversation.update(cx, |conversation, cx| { + conversation + .insert_message_after(message_2.id, Role::System, MessageStatus::Done, cx) + .unwrap() + }); + buffer.update(cx, |buffer, cx| buffer.undo(cx)); + assert_eq!(buffer.read(cx).text(), "a\nb\nc\n"); + assert_eq!( + messages(&conversation, cx), + [ + (message_0, Role::User, 0..2), + (message_1.id, Role::Assistant, 2..6), + (message_2.id, Role::System, 6..6), + ] + ); + + let deserialized_conversation = cx.add_model(|cx| { + Conversation::deserialize( + conversation.read(cx).serialize(cx), + Default::default(), + Default::default(), + registry.clone(), + cx, + ) + }); + let deserialized_buffer = deserialized_conversation.read(cx).buffer.clone(); + assert_eq!(deserialized_buffer.read(cx).text(), "a\nb\nc\n"); + assert_eq!( + messages(&deserialized_conversation, cx), + [ + (message_0, Role::User, 0..2), + (message_1.id, Role::Assistant, 2..6), + (message_2.id, Role::System, 6..6), + ] + ); + } + fn messages( - assistant: &ModelHandle, + conversation: &ModelHandle, cx: &AppContext, ) -> Vec<(MessageId, Role, Range)> { - assistant + conversation .read(cx) .messages(cx) - .map(|message| (message.id, message.role, message.range)) + .map(|message| (message.id, message.role, message.offset_range)) .collect() } } diff --git a/crates/gpui/src/elements/label.rs b/crates/gpui/src/elements/label.rs index 9499841b3d46a0d8c77da4e741bd1c623eeb0de4..a4c4cfba3b6c9dcd1cad17cbca9e01b5fe911dd2 100644 --- a/crates/gpui/src/elements/label.rs +++ b/crates/gpui/src/elements/label.rs @@ -164,6 +164,7 @@ impl Element for Label { _: &mut V, cx: &mut ViewContext, ) -> Self::PaintState { + let visible_bounds = bounds.intersection(visible_bounds).unwrap_or_default(); line.paint( scene, bounds.origin(), diff --git a/crates/gpui/src/elements/svg.rs b/crates/gpui/src/elements/svg.rs index 544422132298be738e97a29a0cd9f7e4a56eba38..9792f16cbe19b65c7ff8d7d620f71d87d3c51f57 100644 --- a/crates/gpui/src/elements/svg.rs +++ b/crates/gpui/src/elements/svg.rs @@ -1,7 +1,5 @@ -use std::{borrow::Cow, ops::Range}; - -use serde_json::json; - +use super::constrain_size_preserving_aspect_ratio; +use crate::json::ToJson; use crate::{ color::Color, geometry::{ @@ -10,6 +8,10 @@ use crate::{ }, scene, Element, LayoutContext, SceneBuilder, SizeConstraint, View, ViewContext, }; +use schemars::JsonSchema; +use serde_derive::Deserialize; +use serde_json::json; +use std::{borrow::Cow, ops::Range}; pub struct Svg { path: Cow<'static, str>, @@ -24,6 +26,14 @@ impl Svg { } } + pub fn for_style(style: SvgStyle) -> impl Element { + Self::new(style.asset) + .with_color(style.color) + .constrained() + .with_width(style.dimensions.width) + .with_height(style.dimensions.height) + } + pub fn with_color(mut self, color: Color) -> Self { self.color = color; self @@ -105,9 +115,24 @@ impl Element for Svg { } } -use crate::json::ToJson; +#[derive(Clone, Deserialize, Default, JsonSchema)] +pub struct SvgStyle { + pub color: Color, + pub asset: String, + pub dimensions: Dimensions, +} -use super::constrain_size_preserving_aspect_ratio; +#[derive(Clone, Deserialize, Default, JsonSchema)] +pub struct Dimensions { + pub width: f32, + pub height: f32, +} + +impl Dimensions { + pub fn to_vec(&self) -> Vector2F { + vec2f(self.width, self.height) + } +} fn from_usvg_rect(rect: usvg::Rect) -> RectF { RectF::new( diff --git a/crates/project_panel/src/project_panel.rs b/crates/project_panel/src/project_panel.rs index dc592b758880601dec6bb63d22d73fb0a9e4e289..110bdc846bbc4ff602aea28f17d101f86e76bf25 100644 --- a/crates/project_panel/src/project_panel.rs +++ b/crates/project_panel/src/project_panel.rs @@ -153,6 +153,7 @@ pub fn init(cx: &mut AppContext) { ); } +#[derive(Debug)] pub enum Event { OpenedEntry { entry_id: ProjectEntryId, diff --git a/crates/search/src/buffer_search.rs b/crates/search/src/buffer_search.rs index c6a86b2f6a209f89de05f80f6fa314120e074297..59d25c2659f5ebbcad2b0a7ca4825c8a5bbf0d37 100644 --- a/crates/search/src/buffer_search.rs +++ b/crates/search/src/buffer_search.rs @@ -259,7 +259,11 @@ impl BufferSearchBar { } } - fn dismiss(&mut self, _: &Dismiss, cx: &mut ViewContext) { + pub fn is_dismissed(&self) -> bool { + self.dismissed + } + + pub fn dismiss(&mut self, _: &Dismiss, cx: &mut ViewContext) { self.dismissed = true; for searchable_item in self.seachable_items_with_matches.keys() { if let Some(searchable_item) = @@ -275,7 +279,7 @@ impl BufferSearchBar { cx.notify(); } - fn show(&mut self, focus: bool, suggest_query: bool, cx: &mut ViewContext) -> bool { + pub fn show(&mut self, focus: bool, suggest_query: bool, cx: &mut ViewContext) -> bool { let searchable_item = if let Some(searchable_item) = &self.active_searchable_item { SearchableItemHandle::boxed_clone(searchable_item.as_ref()) } else { @@ -484,7 +488,7 @@ impl BufferSearchBar { self.select_match(Direction::Prev, cx); } - fn select_match(&mut self, direction: Direction, cx: &mut ViewContext) { + pub fn select_match(&mut self, direction: Direction, cx: &mut ViewContext) { if let Some(index) = self.active_match_index { if let Some(searchable_item) = self.active_searchable_item.as_ref() { if let Some(matches) = self diff --git a/crates/terminal_view/src/terminal_panel.rs b/crates/terminal_view/src/terminal_panel.rs index ac3875af9e10704be06a7a2a047f86ec1fe992b6..6de6527a2617fae85ba1b1347cd9c3542c863994 100644 --- a/crates/terminal_view/src/terminal_panel.rs +++ b/crates/terminal_view/src/terminal_panel.rs @@ -25,6 +25,7 @@ pub fn init(cx: &mut AppContext) { cx.add_action(TerminalPanel::new_terminal); } +#[derive(Debug)] pub enum Event { Close, DockPositionChanged, diff --git a/crates/theme/src/theme.rs b/crates/theme/src/theme.rs index 69c06c85addfe84ff8fda996abcab1f84a271966..26f02df362f0132ba42934060ff80c1d02d754cc 100644 --- a/crates/theme/src/theme.rs +++ b/crates/theme/src/theme.rs @@ -4,7 +4,7 @@ pub mod ui; use gpui::{ color::Color, - elements::{ContainerStyle, ImageStyle, LabelStyle, Shadow, TooltipStyle}, + elements::{ContainerStyle, ImageStyle, LabelStyle, Shadow, SvgStyle, TooltipStyle}, fonts::{HighlightStyle, TextStyle}, platform, AppContext, AssetSource, Border, MouseState, }; @@ -12,7 +12,7 @@ use serde::{de::DeserializeOwned, Deserialize}; use serde_json::Value; use settings::SettingsStore; use std::{collections::HashMap, sync::Arc}; -use ui::{ButtonStyle, CheckboxStyle, IconStyle, ModalStyle, SvgStyle}; +use ui::{ButtonStyle, CheckboxStyle, IconStyle, ModalStyle}; pub use theme_registry::*; pub use theme_settings::*; @@ -992,18 +992,33 @@ pub struct TerminalStyle { #[derive(Clone, Deserialize, Default)] pub struct AssistantStyle { pub container: ContainerStyle, - pub header: ContainerStyle, + pub hamburger_button: Interactive, + pub split_button: Interactive, + pub assist_button: Interactive, + pub quote_button: Interactive, + pub zoom_in_button: Interactive, + pub zoom_out_button: Interactive, + pub plus_button: Interactive, + pub title: ContainedText, + pub message_header: ContainerStyle, pub sent_at: ContainedText, pub user_sender: Interactive, pub assistant_sender: Interactive, pub system_sender: Interactive, - pub model_info_container: ContainerStyle, pub model: Interactive, pub remaining_tokens: ContainedText, pub no_remaining_tokens: ContainedText, pub error_icon: Icon, pub api_key_editor: FieldEditor, pub api_key_prompt: ContainedText, + pub saved_conversation: SavedConversation, +} + +#[derive(Clone, Deserialize, Default, JsonSchema)] +pub struct SavedConversation { + pub container: Interactive, + pub saved_at: ContainedText, + pub title: ContainedText, } #[derive(Clone, Deserialize, Default)] diff --git a/crates/theme/src/ui.rs b/crates/theme/src/ui.rs index a0fd741d1d65e3e18bb4e83f876086f39cf4c0ae..221cfdfeaf1cd7a80ed29fbb2b80165dc495296f 100644 --- a/crates/theme/src/ui.rs +++ b/crates/theme/src/ui.rs @@ -1,13 +1,12 @@ use std::borrow::Cow; use gpui::{ - color::Color, elements::{ - ConstrainedBox, Container, ContainerStyle, Empty, Flex, KeystrokeLabel, Label, - MouseEventHandler, ParentElement, Stack, Svg, + ConstrainedBox, Container, ContainerStyle, Dimensions, Empty, Flex, KeystrokeLabel, Label, + MouseEventHandler, ParentElement, Stack, Svg, SvgStyle, }, fonts::TextStyle, - geometry::vector::{vec2f, Vector2F}, + geometry::vector::Vector2F, platform, platform::MouseButton, scene::MouseClick, @@ -93,25 +92,6 @@ where .with_cursor_style(platform::CursorStyle::PointingHand) } -#[derive(Clone, Deserialize, Default)] -pub struct SvgStyle { - pub color: Color, - pub asset: String, - pub dimensions: Dimensions, -} - -#[derive(Clone, Deserialize, Default)] -pub struct Dimensions { - pub width: f32, - pub height: f32, -} - -impl Dimensions { - pub fn to_vec(&self) -> Vector2F { - vec2f(self.width, self.height) - } -} - pub fn svg(style: &SvgStyle) -> ConstrainedBox { Svg::new(style.asset.clone()) .with_color(style.color) @@ -122,8 +102,8 @@ pub fn svg(style: &SvgStyle) -> ConstrainedBox { #[derive(Clone, Deserialize, Default)] pub struct IconStyle { - icon: SvgStyle, - container: ContainerStyle, + pub icon: SvgStyle, + pub container: ContainerStyle, } pub fn icon(style: &IconStyle) -> Container { diff --git a/crates/util/src/paths.rs b/crates/util/src/paths.rs index e3397a1557cfeed520e4c56fa38c40e4539d71a9..7ef55a991822a52ba18e3dc45184f9881a38dc74 100644 --- a/crates/util/src/paths.rs +++ b/crates/util/src/paths.rs @@ -5,6 +5,7 @@ use serde::{Deserialize, Serialize}; lazy_static::lazy_static! { pub static ref HOME: PathBuf = dirs::home_dir().expect("failed to determine home directory"); pub static ref CONFIG_DIR: PathBuf = HOME.join(".config").join("zed"); + pub static ref CONVERSATIONS_DIR: PathBuf = HOME.join(".config/zed/conversations"); pub static ref LOGS_DIR: PathBuf = HOME.join("Library/Logs/Zed"); pub static ref SUPPORT_DIR: PathBuf = HOME.join("Library/Application Support/Zed"); pub static ref LANGUAGES_DIR: PathBuf = HOME.join("Library/Application Support/Zed/languages"); diff --git a/crates/workspace/src/dock.rs b/crates/workspace/src/dock.rs index 9d23c6aca45af14ef85619c154c8cb2abe344e2f..ebaf399e22b3ecfa51b217327f5912a34dc7b542 100644 --- a/crates/workspace/src/dock.rs +++ b/crates/workspace/src/dock.rs @@ -249,7 +249,7 @@ impl Dock { } } - pub fn add_panel(&mut self, panel: ViewHandle, cx: &mut ViewContext) { + pub(crate) fn add_panel(&mut self, panel: ViewHandle, cx: &mut ViewContext) { let subscriptions = [ cx.observe(&panel, |_, _, cx| cx.notify()), cx.subscribe(&panel, |this, panel, event, cx| { @@ -605,6 +605,7 @@ pub mod test { use super::*; use gpui::{ViewContext, WindowContext}; + #[derive(Debug)] pub enum TestPanelEvent { PositionChanged, Activated, diff --git a/crates/workspace/src/pane.rs b/crates/workspace/src/pane.rs index 5136db1d18b7aea794bbdcad87a851228fadd8ab..54b18ea8b33510f61d6e11b13a05de1eedc1d4a2 100644 --- a/crates/workspace/src/pane.rs +++ b/crates/workspace/src/pane.rs @@ -1,9 +1,10 @@ mod dragged_item_receiver; use super::{ItemHandle, SplitDirection}; +pub use crate::toolbar::Toolbar; use crate::{ - item::WeakItemHandle, notify_of_new_dock, toolbar::Toolbar, AutosaveSetting, Item, - NewCenterTerminal, NewFile, NewSearch, ToggleZoom, Workspace, WorkspaceSettings, + item::WeakItemHandle, notify_of_new_dock, AutosaveSetting, Item, NewCenterTerminal, NewFile, + NewSearch, ToggleZoom, Workspace, WorkspaceSettings, }; use anyhow::Result; use collections::{HashMap, HashSet, VecDeque}; @@ -250,7 +251,7 @@ impl Pane { pane: handle.clone(), next_timestamp, }))), - toolbar: cx.add_view(|_| Toolbar::new(handle)), + toolbar: cx.add_view(|_| Toolbar::new(Some(handle))), tab_bar_context_menu: TabBarContextMenu { kind: TabBarContextMenuKind::New, handle: context_menu, @@ -1112,7 +1113,7 @@ impl Pane { .get(self.active_item_index) .map(|item| item.as_ref()); self.toolbar.update(cx, |toolbar, cx| { - toolbar.set_active_pane_item(active_item, cx); + toolbar.set_active_item(active_item, cx); }); } @@ -1602,7 +1603,7 @@ impl View for Pane { } self.toolbar.update(cx, |toolbar, cx| { - toolbar.pane_focus_update(true, cx); + toolbar.focus_changed(true, cx); }); if let Some(active_item) = self.active_item() { @@ -1631,7 +1632,7 @@ impl View for Pane { fn focus_out(&mut self, _: AnyViewHandle, cx: &mut ViewContext) { self.has_focus = false; self.toolbar.update(cx, |toolbar, cx| { - toolbar.pane_focus_update(false, cx); + toolbar.focus_changed(false, cx); }); cx.notify(); } diff --git a/crates/workspace/src/toolbar.rs b/crates/workspace/src/toolbar.rs index 49f9db12e6bb182976c5f4d76d55aed8b8d4688b..69394b842132b61b6403537d76eacf3f6b0b484f 100644 --- a/crates/workspace/src/toolbar.rs +++ b/crates/workspace/src/toolbar.rs @@ -38,7 +38,7 @@ trait ToolbarItemViewHandle { active_pane_item: Option<&dyn ItemHandle>, cx: &mut WindowContext, ) -> ToolbarItemLocation; - fn pane_focus_update(&mut self, pane_focused: bool, cx: &mut WindowContext); + fn focus_changed(&mut self, pane_focused: bool, cx: &mut WindowContext); fn row_count(&self, cx: &WindowContext) -> usize; } @@ -51,10 +51,10 @@ pub enum ToolbarItemLocation { } pub struct Toolbar { - active_pane_item: Option>, + active_item: Option>, hidden: bool, can_navigate: bool, - pane: WeakViewHandle, + pane: Option>, items: Vec<(Box, ToolbarItemLocation)>, } @@ -121,7 +121,7 @@ impl View for Toolbar { let pane = self.pane.clone(); let mut enable_go_backward = false; let mut enable_go_forward = false; - if let Some(pane) = pane.upgrade(cx) { + if let Some(pane) = pane.and_then(|pane| pane.upgrade(cx)) { let pane = pane.read(cx); enable_go_backward = pane.can_navigate_backward(); enable_go_forward = pane.can_navigate_forward(); @@ -143,19 +143,17 @@ impl View for Toolbar { enable_go_backward, spacing, { - let pane = pane.clone(); move |toolbar, cx| { - if let Some(workspace) = toolbar - .pane - .upgrade(cx) - .and_then(|pane| pane.read(cx).workspace().upgrade(cx)) + if let Some(pane) = toolbar.pane.as_ref().and_then(|pane| pane.upgrade(cx)) { - let pane = pane.clone(); - cx.window_context().defer(move |cx| { - workspace.update(cx, |workspace, cx| { - workspace.go_back(pane.clone(), cx).detach_and_log_err(cx); - }); - }) + if let Some(workspace) = pane.read(cx).workspace().upgrade(cx) { + let pane = pane.downgrade(); + cx.window_context().defer(move |cx| { + workspace.update(cx, |workspace, cx| { + workspace.go_back(pane, cx).detach_and_log_err(cx); + }); + }) + } } } }, @@ -171,21 +169,17 @@ impl View for Toolbar { enable_go_forward, spacing, { - let pane = pane.clone(); move |toolbar, cx| { - if let Some(workspace) = toolbar - .pane - .upgrade(cx) - .and_then(|pane| pane.read(cx).workspace().upgrade(cx)) + if let Some(pane) = toolbar.pane.as_ref().and_then(|pane| pane.upgrade(cx)) { - let pane = pane.clone(); - cx.window_context().defer(move |cx| { - workspace.update(cx, |workspace, cx| { - workspace - .go_forward(pane.clone(), cx) - .detach_and_log_err(cx); - }); - }); + if let Some(workspace) = pane.read(cx).workspace().upgrade(cx) { + let pane = pane.downgrade(); + cx.window_context().defer(move |cx| { + workspace.update(cx, |workspace, cx| { + workspace.go_forward(pane, cx).detach_and_log_err(cx); + }); + }) + } } } }, @@ -269,9 +263,9 @@ fn nav_button } impl Toolbar { - pub fn new(pane: WeakViewHandle) -> Self { + pub fn new(pane: Option>) -> Self { Self { - active_pane_item: None, + active_item: None, pane, items: Default::default(), hidden: false, @@ -288,7 +282,7 @@ impl Toolbar { where T: 'static + ToolbarItemView, { - let location = item.set_active_pane_item(self.active_pane_item.as_deref(), cx); + let location = item.set_active_pane_item(self.active_item.as_deref(), cx); cx.subscribe(&item, |this, item, event, cx| { if let Some((_, current_location)) = this.items.iter_mut().find(|(i, _)| i.id() == item.id()) @@ -307,20 +301,16 @@ impl Toolbar { cx.notify(); } - pub fn set_active_pane_item( - &mut self, - pane_item: Option<&dyn ItemHandle>, - cx: &mut ViewContext, - ) { - self.active_pane_item = pane_item.map(|item| item.boxed_clone()); + pub fn set_active_item(&mut self, item: Option<&dyn ItemHandle>, cx: &mut ViewContext) { + self.active_item = item.map(|item| item.boxed_clone()); self.hidden = self - .active_pane_item + .active_item .as_ref() .map(|item| !item.show_toolbar(cx)) .unwrap_or(false); for (toolbar_item, current_location) in self.items.iter_mut() { - let new_location = toolbar_item.set_active_pane_item(pane_item, cx); + let new_location = toolbar_item.set_active_pane_item(item, cx); if new_location != *current_location { *current_location = new_location; cx.notify(); @@ -328,9 +318,9 @@ impl Toolbar { } } - pub fn pane_focus_update(&mut self, pane_focused: bool, cx: &mut ViewContext) { + pub fn focus_changed(&mut self, focused: bool, cx: &mut ViewContext) { for (toolbar_item, _) in self.items.iter_mut() { - toolbar_item.pane_focus_update(pane_focused, cx); + toolbar_item.focus_changed(focused, cx); } } @@ -364,7 +354,7 @@ impl ToolbarItemViewHandle for ViewHandle { }) } - fn pane_focus_update(&mut self, pane_focused: bool, cx: &mut WindowContext) { + fn focus_changed(&mut self, pane_focused: bool, cx: &mut WindowContext) { self.update(cx, |this, cx| { this.pane_focus_update(pane_focused, cx); cx.notify(); diff --git a/crates/workspace/src/workspace.rs b/crates/workspace/src/workspace.rs index a4974fc17344a92d706a132f9102b9469fc9a3be..8b1092fad0f0b53c2bcd6fc03621006286e205ab 100644 --- a/crates/workspace/src/workspace.rs +++ b/crates/workspace/src/workspace.rs @@ -861,7 +861,10 @@ impl Workspace { &self.right_dock } - pub fn add_panel(&mut self, panel: ViewHandle, cx: &mut ViewContext) { + pub fn add_panel(&mut self, panel: ViewHandle, cx: &mut ViewContext) + where + T::Event: std::fmt::Debug, + { let dock = match panel.position(cx) { DockPosition::Left => &self.left_dock, DockPosition::Bottom => &self.bottom_dock, @@ -904,10 +907,11 @@ impl Workspace { }); } else if T::should_zoom_in_on_event(event) { dock.update(cx, |dock, cx| dock.set_panel_zoomed(&panel, true, cx)); - if panel.has_focus(cx) { - this.zoomed = Some(panel.downgrade().into_any()); - this.zoomed_position = Some(panel.read(cx).position(cx)); + if !panel.has_focus(cx) { + cx.focus(&panel); } + this.zoomed = Some(panel.downgrade().into_any()); + this.zoomed_position = Some(panel.read(cx).position(cx)); } else if T::should_zoom_out_on_event(event) { dock.update(cx, |dock, cx| dock.set_panel_zoomed(&panel, false, cx)); if this.zoomed_position == Some(prev_position) { @@ -1702,6 +1706,11 @@ impl Workspace { cx.notify(); } + #[cfg(any(test, feature = "test-support"))] + pub fn zoomed_view(&self, cx: &AppContext) -> Option { + self.zoomed.and_then(|view| view.upgrade(cx)) + } + fn dismiss_zoomed_items_to_reveal( &mut self, dock_to_reveal: Option, diff --git a/styles/src/styleTree/assistant.ts b/styles/src/styleTree/assistant.ts index 163584cd6db6b409112422398cde90adf21f9208..91b52f20ad1902bac074ad1575dd83dc6a3230fc 100644 --- a/styles/src/styleTree/assistant.ts +++ b/styles/src/styleTree/assistant.ts @@ -10,11 +10,190 @@ export default function assistant(colorScheme: ColorScheme) { background: editor(colorScheme).background, padding: { left: 12 }, }, - header: { + messageHeader: { border: border(layer, "default", { bottom: true, top: true }), margin: { bottom: 6, top: 6 }, background: editor(colorScheme).background, }, + hamburgerButton: interactive({ + base: { + icon: { + color: foreground(layer, "variant"), + asset: "icons/hamburger_15.svg", + dimensions: { + width: 15, + height: 15, + }, + }, + container: { + margin: { left: 12 }, + } + }, + state: { + hovered: { + icon: { + color: foreground(layer, "hovered") + } + } + } + }), + splitButton: interactive({ + base: { + icon: { + color: foreground(layer, "variant"), + asset: "icons/split_message_15.svg", + dimensions: { + width: 15, + height: 15, + }, + }, + container: { + margin: { left: 12 }, + } + }, + state: { + hovered: { + icon: { + color: foreground(layer, "hovered") + } + } + } + }), + quoteButton: interactive({ + base: { + icon: { + color: foreground(layer, "variant"), + asset: "icons/quote_15.svg", + dimensions: { + width: 15, + height: 15, + }, + }, + container: { + margin: { left: 12 }, + } + }, + state: { + hovered: { + icon: { + color: foreground(layer, "hovered") + } + } + } + }), + assistButton: interactive({ + base: { + icon: { + color: foreground(layer, "variant"), + asset: "icons/assist_15.svg", + dimensions: { + width: 15, + height: 15, + }, + }, + container: { + margin: { left: 12, right: 24 }, + } + }, + state: { + hovered: { + icon: { + color: foreground(layer, "hovered") + } + } + } + }), + zoomInButton: interactive({ + base: { + icon: { + color: foreground(layer, "variant"), + asset: "icons/maximize_8.svg", + dimensions: { + width: 12, + height: 12, + }, + }, + container: { + margin: { right: 12 }, + } + }, + state: { + hovered: { + icon: { + color: foreground(layer, "hovered") + } + } + } + }), + zoomOutButton: interactive({ + base: { + icon: { + color: foreground(layer, "variant"), + asset: "icons/minimize_8.svg", + dimensions: { + width: 12, + height: 12, + }, + }, + container: { + margin: { right: 12 }, + } + }, + state: { + hovered: { + icon: { + color: foreground(layer, "hovered") + } + } + } + }), + plusButton: interactive({ + base: { + icon: { + color: foreground(layer, "variant"), + asset: "icons/plus_12.svg", + dimensions: { + width: 12, + height: 12, + }, + }, + container: { + margin: { right: 12 }, + } + }, + state: { + hovered: { + icon: { + color: foreground(layer, "hovered") + } + } + } + }), + title: { + margin: { left: 12 }, + ...text(layer, "sans", "default", { size: "sm" }) + }, + savedConversation: { + container: interactive({ + base: { + background: background(layer, "on"), + padding: { top: 4, bottom: 4 } + }, + state: { + hovered: { + background: background(layer, "on", "hovered"), + } + }, + }), + savedAt: { + margin: { left: 8 }, + ...text(layer, "sans", "default", { size: "xs" }), + }, + title: { + margin: { left: 16 }, + ...text(layer, "sans", "default", { size: "sm", weight: "bold" }), + } + }, userSender: { default: { ...text(layer, "sans", "default", { @@ -43,13 +222,10 @@ export default function assistant(colorScheme: ColorScheme) { margin: { top: 2, left: 8 }, ...text(layer, "sans", "default", { size: "2xs" }), }, - modelInfoContainer: { - margin: { right: 16, top: 4 }, - }, model: interactive({ base: { background: background(layer, "on"), - border: border(layer, "on", { overlay: true }), + margin: { left: 12, right: 12, top: 12 }, padding: 4, cornerRadius: 4, ...text(layer, "sans", "default", { size: "xs" }), @@ -57,22 +233,21 @@ export default function assistant(colorScheme: ColorScheme) { state: { hovered: { background: background(layer, "on", "hovered"), + border: border(layer, "on", { overlay: true }), }, }, }), remainingTokens: { background: background(layer, "on"), - border: border(layer, "on", { overlay: true }), + margin: { top: 12, right: 12 }, padding: 4, - margin: { left: 4 }, cornerRadius: 4, ...text(layer, "sans", "positive", { size: "xs" }), }, noRemainingTokens: { background: background(layer, "on"), - border: border(layer, "on", { overlay: true }), + margin: { top: 12, right: 12 }, padding: 4, - margin: { left: 4 }, cornerRadius: 4, ...text(layer, "sans", "negative", { size: "xs" }), },