diff --git a/Cargo.lock b/Cargo.lock
index 5d5f0bb712..042f6b69d9 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -372,6 +372,7 @@ version = "0.1.0"
dependencies = [
"anthropic",
"anyhow",
+ "assets",
"assistant_slash_command",
"async-watch",
"breadcrumbs",
@@ -408,6 +409,7 @@ dependencies = [
"rand 0.8.5",
"regex",
"rope",
+ "roxmltree 0.20.0",
"schemars",
"search",
"semantic_index",
@@ -416,7 +418,6 @@ dependencies = [
"settings",
"similar",
"smol",
- "strsim 0.11.1",
"strum",
"telemetry_events",
"terminal",
@@ -2244,7 +2245,7 @@ dependencies = [
"bitflags 1.3.2",
"clap_lex 0.2.4",
"indexmap 1.9.3",
- "strsim 0.10.0",
+ "strsim",
"termcolor",
"textwrap",
]
@@ -2268,7 +2269,7 @@ dependencies = [
"anstream",
"anstyle",
"clap_lex 0.5.1",
- "strsim 0.10.0",
+ "strsim",
]
[[package]]
@@ -4272,7 +4273,7 @@ version = "0.5.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6a595cb550439a117696039dfc69830492058211b771a2a165379f2a1a53d84d"
dependencies = [
- "roxmltree",
+ "roxmltree 0.19.0",
]
[[package]]
@@ -5944,6 +5945,7 @@ version = "0.1.0"
dependencies = [
"anyhow",
"async-trait",
+ "async-watch",
"clock",
"collections",
"ctor",
@@ -8901,6 +8903,12 @@ version = "0.19.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3cd14fd5e3b777a7422cca79358c57a8f6e3a703d9ac187448d0daf220c2407f"
+[[package]]
+name = "roxmltree"
+version = "0.20.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6c20b6793b5c2fa6553b250154b78d6d0db37e72700ae35fad9387a46f487c97"
+
[[package]]
name = "rpc"
version = "0.1.0"
@@ -10359,12 +10367,6 @@ version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623"
-[[package]]
-name = "strsim"
-version = "0.11.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
-
[[package]]
name = "strum"
version = "0.25.0"
@@ -11899,7 +11901,7 @@ dependencies = [
"kurbo",
"log",
"pico-args",
- "roxmltree",
+ "roxmltree 0.19.0",
"simplecss",
"siphasher 1.0.1",
"strict-num",
diff --git a/assets/prompts/operations.md b/assets/prompts/operations.md
new file mode 100644
index 0000000000..b77cfedf12
--- /dev/null
+++ b/assets/prompts/operations.md
@@ -0,0 +1,241 @@
+Your task is to map a step from the conversation above to operations on symbols inside the provided source files.
+
+Guidelines:
+- There's no need to describe *what* to do, just *where* to do it.
+- If creating a file, assume any subsequent updates are included at the time of creation.
+- Don't create and then update a file.
+- We'll create it in one shot.
+- Prefer updating symbols lower in the syntax tree if possible.
+- Never include operations on a parent symbol and one of its children in the same block.
+- Never nest an operation with another operation or include CDATA or other content. All operations are leaf nodes.
+- Include a description attribute for each operation with a brief, one-line description of the change to perform.
+- Descriptions are required for all operations except delete.
+- When generating multiple operations, ensure the descriptions are specific to each individual operation.
+- Avoid referring to the location in the description. Focus on the change to be made, not the location where it's made. That's implicit with the symbol you provide.
+- Don't generate multiple operations at the same location. Instead, combine them together in a single operation with a succinct combined description.
+
+The available operation types are:
+
+1. : Modify an existing symbol in a file.
+2. : Create a new file.
+3. : Add a new symbol as sibling after an existing symbol in a file.
+4. : Add a new symbol as the last child of an existing symbol in a file.
+5. : Add a new symbol as the first child of an existing symbol in a file.
+6. : Remove an existing symbol from a file. The `description` attribute is invalid for delete, but required for other ops.
+
+All operations *require* a path.
+Operations that *require* a symbol: , ,
+Operations that don't allow a symbol:
+Operations that have an *optional* symbol: ,
+
+Example 1:
+
+User:
+ ```rs src/rectangle.rs
+ struct Rectangle {
+ width: f64,
+ height: f64,
+ }
+
+ impl Rectangle {
+ fn new(width: f64, height: f64) -> Self {
+ Rectangle { width, height }
+ }
+ }
+ ```
+
+ Symbols for src/rectangle.rs:
+ - struct Rectangle
+ - impl Rectangle
+ - impl Rectangle fn new
+
+ Add new methods 'calculate_area' and 'calculate_perimeter' to the Rectangle struct
+ Implement the 'Display' trait for the Rectangle struct
+
+ What are the operations for the step: Add a new method 'calculate_area' to the Rectangle struct
+
+Assistant (wrong):
+
+
+
+
+
+This demonstrates what NOT to do. NEVER append multiple children at the same location.
+
+Assistant (corrected):
+
+
+
+
+User:
+What are the operations for the step: Implement the 'Display' trait for the Rectangle struct
+
+Assistant:
+
+
+
+
+Example 2:
+
+User:
+```rs src/user.rs
+struct User {
+ pub name: String,
+ age: u32,
+ email: String,
+}
+
+impl User {
+ fn new(name: String, age: u32, email: String) -> Self {
+ User { name, age, email }
+ }
+
+ pub fn print_info(&self) {
+ println!("Name: {}, Age: {}, Email: {}", self.name, self.age, self.email);
+ }
+}
+```
+
+Symbols for src/user.rs:
+- struct User
+- struct User pub name
+- struct User age
+- struct User email
+- impl User
+- impl User fn new
+- impl User pub fn print_info
+
+Update the 'print_info' method to use formatted output
+Remove the 'email' field from the User struct
+
+What are the operations for the step: Update the 'print_info' method to use formatted output
+
+Assistant:
+
+
+
+
+User:
+What are the operations for the step: Remove the 'email' field from the User struct
+
+Assistant:
+
+
+
+
+Example 3:
+
+User:
+```rs src/vehicle.rs
+struct Vehicle {
+ make: String,
+ model: String,
+ year: u32,
+}
+
+impl Vehicle {
+ fn new(make: String, model: String, year: u32) -> Self {
+ Vehicle { make, model, year }
+ }
+
+ fn print_year(&self) {
+ println!("Year: {}", self.year);
+ }
+}
+```
+
+Symbols for src/vehicle.rs:
+- struct Vehicle
+- struct Vehicle make
+- struct Vehicle model
+- struct Vehicle year
+- impl Vehicle
+- impl Vehicle fn new
+- impl Vehicle fn print_year
+
+Add a 'use std::fmt;' statement at the beginning of the file
+Add a new method 'start_engine' in the Vehicle impl block
+
+What are the operations for the step: Add a 'use std::fmt;' statement at the beginning of the file
+
+Assistant:
+
+
+
+
+User:
+What are the operations for the step: Add a new method 'start_engine' in the Vehicle impl block
+
+Assistant:
+
+
+
+
+Example 4:
+
+User:
+```rs src/employee.rs
+struct Employee {
+ name: String,
+ position: String,
+ salary: u32,
+ department: String,
+}
+
+impl Employee {
+ fn new(name: String, position: String, salary: u32, department: String) -> Self {
+ Employee { name, position, salary, department }
+ }
+
+ fn print_details(&self) {
+ println!("Name: {}, Position: {}, Salary: {}, Department: {}",
+ self.name, self.position, self.salary, self.department);
+ }
+
+ fn give_raise(&mut self, amount: u32) {
+ self.salary += amount;
+ }
+}
+```
+
+Symbols for src/employee.rs:
+- struct Employee
+- struct Employee name
+- struct Employee position
+- struct Employee salary
+- struct Employee department
+- impl Employee
+- impl Employee fn new
+- impl Employee fn print_details
+- impl Employee fn give_raise
+
+Make salary an f32
+
+What are the operations for the step: Make salary an f32
+
+A (wrong):
+
+
+
+
+
+This example demonstrates what not to do. `struct Employee salary` is a child of `struct Employee`.
+
+A (corrected):
+
+
+
+
+User:
+ What are the correct operations for the step: Remove the 'department' field and update the 'print_details' method
+
+A:
+
+
+
+
+
+Now generate the operations for the following step.
+Output only valid XML containing valid operations with their required attributes.
+NEVER output code or any other text inside tags. If you do, you will replaced with another model.
+Your response *MUST* begin with and end with :
diff --git a/crates/activity_indicator/src/activity_indicator.rs b/crates/activity_indicator/src/activity_indicator.rs
index 89023c12cf..d39cb4af47 100644
--- a/crates/activity_indicator/src/activity_indicator.rs
+++ b/crates/activity_indicator/src/activity_indicator.rs
@@ -107,6 +107,7 @@ impl ActivityIndicator {
Editor::for_buffer(buffer, Some(project.clone()), cx)
})),
None,
+ true,
cx,
);
})?;
diff --git a/crates/assistant/Cargo.toml b/crates/assistant/Cargo.toml
index c48da49a0d..e3ddd4e2c7 100644
--- a/crates/assistant/Cargo.toml
+++ b/crates/assistant/Cargo.toml
@@ -23,6 +23,7 @@ test-support = [
[dependencies]
anthropic = { workspace = true, features = ["schemars"] }
anyhow.workspace = true
+assets.workspace = true
assistant_slash_command.workspace = true
async-watch.workspace = true
breadcrumbs.workspace = true
@@ -63,7 +64,6 @@ serde_json.workspace = true
settings.workspace = true
similar.workspace = true
smol.workspace = true
-strsim = "0.11"
strum.workspace = true
telemetry_events.workspace = true
terminal.workspace = true
@@ -76,6 +76,7 @@ util.workspace = true
uuid.workspace = true
workspace.workspace = true
picker.workspace = true
+roxmltree = "0.20.0"
[dev-dependencies]
ctor.workspace = true
diff --git a/crates/assistant/src/assistant.rs b/crates/assistant/src/assistant.rs
index 50fec4a575..698465ecfb 100644
--- a/crates/assistant/src/assistant.rs
+++ b/crates/assistant/src/assistant.rs
@@ -7,7 +7,6 @@ mod inline_assistant;
mod model_selector;
mod prompt_library;
mod prompts;
-mod search;
mod slash_command;
mod streaming_diff;
mod terminal_inline_assistant;
@@ -53,9 +52,9 @@ actions!(
InsertActivePrompt,
DeployHistory,
DeployPromptLibrary,
- ApplyEdit,
ConfirmCommand,
- ToggleModelSelector
+ ToggleModelSelector,
+ DebugEditSteps
]
);
diff --git a/crates/assistant/src/assistant_panel.rs b/crates/assistant/src/assistant_panel.rs
index b6bd583587..d96f1f4bc1 100644
--- a/crates/assistant/src/assistant_panel.rs
+++ b/crates/assistant/src/assistant_panel.rs
@@ -1,19 +1,19 @@
use crate::{
assistant_settings::{AssistantDockPosition, AssistantSettings},
- humanize_token_count, parse_next_edit_suggestion,
+ humanize_token_count,
prompt_library::open_prompt_library,
- search::*,
slash_command::{
default_command::DefaultSlashCommand,
docs_command::{DocsSlashCommand, DocsSlashCommandArgs},
SlashCommandCompletionProvider, SlashCommandRegistry,
},
terminal_inline_assistant::TerminalInlineAssistant,
- ApplyEdit, Assist, CompletionProvider, ConfirmCommand, Context, ContextEvent, ContextId,
- ContextStore, CycleMessageRole, DeployHistory, DeployPromptLibrary, EditSuggestion,
- InlineAssist, InlineAssistant, InsertIntoEditor, MessageStatus, ModelSelector,
- PendingSlashCommand, PendingSlashCommandStatus, QuoteSelection, RemoteContextMetadata,
- ResetKey, Role, SavedContextMetadata, Split, ToggleFocus, ToggleModelSelector,
+ Assist, CompletionProvider, ConfirmCommand, Context, ContextEvent, ContextId, ContextStore,
+ CycleMessageRole, DebugEditSteps, DeployHistory, DeployPromptLibrary, EditStep,
+ EditStepOperations, EditSuggestionGroup, InlineAssist, InlineAssistId, InlineAssistant,
+ InsertIntoEditor, MessageStatus, ModelSelector, PendingSlashCommand, PendingSlashCommandStatus,
+ QuoteSelection, RemoteContextMetadata, ResetKey, Role, SavedContextMetadata, Split,
+ ToggleFocus, ToggleModelSelector,
};
use anyhow::{anyhow, Result};
use assistant_slash_command::{SlashCommand, SlashCommandOutputSection};
@@ -25,29 +25,36 @@ use editor::{
display_map::{
BlockDisposition, BlockId, BlockProperties, BlockStyle, Crease, RenderBlock, ToDisplayPoint,
},
- scroll::{Autoscroll, AutoscrollStrategy},
- Anchor, Editor, EditorEvent, RowExt, ToOffset as _, ToPoint,
+ scroll::{Autoscroll, AutoscrollStrategy, ScrollAnchor},
+ Anchor, Editor, EditorEvent, ExcerptRange, MultiBuffer, RowExt, ToOffset as _, ToPoint,
};
use editor::{display_map::CreaseId, FoldPlaceholder};
use fs::Fs;
use gpui::{
div, percentage, point, Action, Animation, AnimationExt, AnyElement, AnyView, AppContext,
- AsyncWindowContext, ClipboardItem, DismissEvent, Empty, EventEmitter, FocusHandle,
- FocusableView, InteractiveElement, IntoElement, Model, ParentElement, Pixels, Render,
- SharedString, StatefulInteractiveElement, Styled, Subscription, Task, Transformation,
+ AsyncWindowContext, ClipboardItem, Context as _, DismissEvent, Empty, Entity, EventEmitter,
+ FocusHandle, FocusableView, InteractiveElement, IntoElement, Model, ParentElement, Pixels,
+ Render, SharedString, StatefulInteractiveElement, Styled, Subscription, Task, Transformation,
UpdateGlobal, View, ViewContext, VisualContext, WeakView, WindowContext,
};
use indexed_docs::IndexedDocsStore;
use language::{
- language_settings::SoftWrap, AutoindentMode, Buffer, LanguageRegistry, LspAdapterDelegate,
- OffsetRangeExt as _, Point, ToOffset,
+ language_settings::SoftWrap, Buffer, Capability, LanguageRegistry, LspAdapterDelegate, Point,
+ ToOffset,
};
use multi_buffer::MultiBufferRow;
use picker::{Picker, PickerDelegate};
-use project::{Project, ProjectLspAdapterDelegate, ProjectTransaction};
+use project::{Project, ProjectLspAdapterDelegate};
use search::{buffer_search::DivRegistrar, BufferSearchBar};
use settings::Settings;
-use std::{cmp, fmt::Write, ops::Range, path::PathBuf, sync::Arc, time::Duration};
+use std::{
+ cmp::{self, Ordering},
+ fmt::Write,
+ ops::Range,
+ path::PathBuf,
+ sync::Arc,
+ time::Duration,
+};
use terminal_view::{terminal_panel::TerminalPanel, TerminalView};
use theme::ThemeSettings;
use ui::{
@@ -60,7 +67,8 @@ use util::ResultExt;
use workspace::{
dock::{DockPosition, Panel, PanelEvent},
item::{self, BreadcrumbText, FollowableItem, Item, ItemHandle},
- pane,
+ notifications::NotifyTaskExt,
+ pane::{self, SaveIntent},
searchable::{SearchEvent, SearchableItem},
Pane, Save, ToggleZoom, ToolbarItemEvent, ToolbarItemLocation, ToolbarItemView, Workspace,
};
@@ -591,6 +599,7 @@ impl AssistantPanel {
make_lsp_adapter_delegate(workspace.project(), cx).log_err()
});
+ let assistant_panel = cx.view().downgrade();
let editor = cx.new_view(|cx| {
let mut editor = ContextEditor::for_context(
context,
@@ -598,6 +607,7 @@ impl AssistantPanel {
workspace.clone(),
self.project.clone(),
lsp_adapter_delegate,
+ assistant_panel,
cx,
);
editor.insert_default_prompt(cx);
@@ -720,6 +730,7 @@ impl AssistantPanel {
cx.spawn(|this, mut cx| async move {
let context = context.await?;
+ let assistant_panel = this.clone();
this.update(&mut cx, |this, cx| {
let workspace = workspace
.upgrade()
@@ -731,6 +742,7 @@ impl AssistantPanel {
workspace,
project,
lsp_adapter_delegate,
+ assistant_panel,
cx,
)
});
@@ -774,6 +786,7 @@ impl AssistantPanel {
cx.spawn(|this, mut cx| async move {
let context = context.await?;
+ let assistant_panel = this.clone();
this.update(&mut cx, |this, cx| {
let workspace = workspace
.upgrade()
@@ -785,6 +798,7 @@ impl AssistantPanel {
workspace,
this.project.clone(),
lsp_adapter_delegate,
+ assistant_panel,
cx,
)
});
@@ -956,10 +970,18 @@ struct ScrollPosition {
cursor: Anchor,
}
+struct ActiveEditStep {
+ start: language::Anchor,
+ assist_ids: Vec,
+ editor: Option>,
+ _open_editor: Task>,
+}
+
pub struct ContextEditor {
context: Model,
fs: Arc,
workspace: WeakView,
+ project: Model,
lsp_adapter_delegate: Option>,
editor: View,
blocks: HashSet,
@@ -968,6 +990,8 @@ pub struct ContextEditor {
pending_slash_command_creases: HashMap, CreaseId>,
pending_slash_command_blocks: HashMap, BlockId>,
_subscriptions: Vec,
+ active_edit_step: Option,
+ assistant_panel: WeakView,
}
impl ContextEditor {
@@ -979,6 +1003,7 @@ impl ContextEditor {
workspace: View,
project: Model,
lsp_adapter_delegate: Option>,
+ assistant_panel: WeakView,
cx: &mut ViewContext,
) -> Self {
let completion_provider = SlashCommandCompletionProvider::new(
@@ -996,7 +1021,7 @@ impl ContextEditor {
editor.set_show_wrap_guides(false, cx);
editor.set_show_indent_guides(false, cx);
editor.set_completion_provider(Box::new(completion_provider));
- editor.set_collaboration_hub(Box::new(project));
+ editor.set_collaboration_hub(Box::new(project.clone()));
editor
});
@@ -1017,9 +1042,12 @@ impl ContextEditor {
remote_id: None,
fs,
workspace: workspace.downgrade(),
+ project,
pending_slash_command_creases: HashMap::default(),
pending_slash_command_blocks: HashMap::default(),
_subscriptions,
+ active_edit_step: None,
+ assistant_panel,
};
this.update_message_headers(cx);
this.insert_slash_command_output_sections(sections, cx);
@@ -1052,31 +1080,37 @@ impl ContextEditor {
}
fn assist(&mut self, _: &Assist, cx: &mut ViewContext) {
- let cursors = self.cursors(cx);
+ if !self.apply_edit_step(cx) {
+ self.send_to_model(cx);
+ }
+ }
- let user_messages = self.context.update(cx, |context, cx| {
- let selected_messages = context
- .messages_for_offsets(cursors, cx)
- .into_iter()
- .map(|message| message.id)
- .collect();
- context.assist(selected_messages, cx)
- });
- let new_selections = user_messages
- .iter()
- .map(|message| {
- let cursor = message
+ fn apply_edit_step(&mut self, cx: &mut ViewContext) -> bool {
+ if let Some(step) = self.active_edit_step.as_ref() {
+ InlineAssistant::update_global(cx, |assistant, cx| {
+ for assist_id in &step.assist_ids {
+ assistant.start_assist(*assist_id, cx);
+ }
+ !step.assist_ids.is_empty()
+ })
+ } else {
+ false
+ }
+ }
+
+ fn send_to_model(&mut self, cx: &mut ViewContext) {
+ if let Some(user_message) = self.context.update(cx, |context, cx| context.assist(cx)) {
+ let new_selection = {
+ let cursor = user_message
.start
.to_offset(self.context.read(cx).buffer().read(cx));
cursor..cursor
- })
- .collect::>();
- if !new_selections.is_empty() {
+ };
self.editor.update(cx, |editor, cx| {
editor.change_selections(
Some(Autoscroll::Strategy(AutoscrollStrategy::Fit)),
cx,
- |selections| selections.select_ranges(new_selections),
+ |selections| selections.select_ranges([new_selection]),
);
});
// Avoid scrolling to the new cursor position so the assistant's output is stable.
@@ -1093,6 +1127,53 @@ impl ContextEditor {
}
}
+ fn debug_edit_steps(&mut self, _: &DebugEditSteps, cx: &mut ViewContext) {
+ let mut output = String::new();
+ for (i, step) in self.context.read(cx).edit_steps().iter().enumerate() {
+ output.push_str(&format!("Step {}:\n", i + 1));
+ output.push_str(&format!(
+ "Content: {}\n",
+ self.context
+ .read(cx)
+ .buffer()
+ .read(cx)
+ .text_for_range(step.source_range.clone())
+ .collect::()
+ ));
+ match &step.operations {
+ Some(EditStepOperations::Parsed {
+ operations,
+ raw_output,
+ }) => {
+ output.push_str(&format!("Raw Output:\n{raw_output}\n"));
+ output.push_str("Parsed Operations:\n");
+ for op in operations {
+ output.push_str(&format!(" {:?}\n", op));
+ }
+ }
+ Some(EditStepOperations::Pending(_)) => {
+ output.push_str("Operations: Pending\n");
+ }
+ None => {
+ output.push_str("Operations: None\n");
+ }
+ }
+ output.push('\n');
+ }
+
+ let editor = self
+ .workspace
+ .update(cx, |workspace, cx| Editor::new_in_workspace(workspace, cx));
+
+ if let Ok(editor) = editor {
+ cx.spawn(|_, mut cx| async move {
+ let editor = editor.await?;
+ editor.update(&mut cx, |editor, cx| editor.set_text(output, cx))
+ })
+ .detach_and_notify_err(cx);
+ }
+ }
+
fn cycle_message_role(&mut self, _: &CycleMessageRole, cx: &mut ViewContext) {
let cursors = self.cursors(cx);
self.context.update(cx, |context, cx| {
@@ -1222,39 +1303,8 @@ impl ContextEditor {
context.save(Some(Duration::from_millis(500)), self.fs.clone(), cx);
});
}
- ContextEvent::EditSuggestionsChanged => {
- self.editor.update(cx, |editor, cx| {
- let buffer = editor.buffer().read(cx).snapshot(cx);
- let excerpt_id = *buffer.as_singleton().unwrap().0;
- let context = self.context.read(cx);
- let highlighted_rows = context
- .edit_suggestions()
- .iter()
- .map(|suggestion| {
- let start = buffer
- .anchor_in_excerpt(excerpt_id, suggestion.source_range.start)
- .unwrap();
- let end = buffer
- .anchor_in_excerpt(excerpt_id, suggestion.source_range.end)
- .unwrap();
- start..=end
- })
- .collect::>();
-
- editor.clear_row_highlights::();
- for range in highlighted_rows {
- editor.highlight_rows::(
- range,
- Some(
- cx.theme()
- .colors()
- .editor_document_highlight_read_background,
- ),
- false,
- cx,
- );
- }
- });
+ ContextEvent::EditStepsChanged => {
+ cx.notify();
}
ContextEvent::SummaryChanged => {
cx.emit(EditorEvent::TitleChanged);
@@ -1515,12 +1565,200 @@ impl ContextEditor {
}
EditorEvent::SelectionsChanged { .. } => {
self.scroll_position = self.cursor_scroll_position(cx);
+ if self
+ .edit_step_for_cursor(cx)
+ .map(|step| step.source_range.start)
+ != self.active_edit_step.as_ref().map(|step| step.start)
+ {
+ if let Some(old_active_edit_step) = self.active_edit_step.take() {
+ if let Some(editor) = old_active_edit_step
+ .editor
+ .and_then(|editor| editor.upgrade())
+ {
+ self.workspace
+ .update(cx, |workspace, cx| {
+ if let Some(pane) = workspace.pane_for(&editor) {
+ pane.update(cx, |pane, cx| {
+ let item_id = editor.entity_id();
+ if pane.is_active_preview_item(item_id) {
+ pane.close_item_by_id(
+ item_id,
+ SaveIntent::Skip,
+ cx,
+ )
+ .detach_and_log_err(cx);
+ }
+ });
+ }
+ })
+ .ok();
+ }
+ }
+
+ if let Some(new_active_step) = self.edit_step_for_cursor(cx) {
+ let suggestions = new_active_step.edit_suggestions(&self.project, cx);
+ self.active_edit_step = Some(ActiveEditStep {
+ start: new_active_step.source_range.start,
+ assist_ids: Vec::new(),
+ editor: None,
+ _open_editor: self.open_editor_for_edit_suggestions(suggestions, cx),
+ });
+ }
+ }
}
_ => {}
}
cx.emit(event.clone());
}
+ fn open_editor_for_edit_suggestions(
+ &mut self,
+ edit_suggestions: Task, Vec>>,
+ cx: &mut ViewContext,
+ ) -> Task> {
+ let workspace = self.workspace.clone();
+ let project = self.project.clone();
+ let assistant_panel = self.assistant_panel.clone();
+ cx.spawn(|this, mut cx| async move {
+ let edit_suggestions = edit_suggestions.await;
+
+ let mut assist_ids = Vec::new();
+ let editor = if edit_suggestions.is_empty() {
+ return Ok(());
+ } else if edit_suggestions.len() == 1
+ && edit_suggestions.values().next().unwrap().len() == 1
+ {
+ // If there's only one buffer and one suggestion group, open it directly
+ let (buffer, suggestion_groups) = edit_suggestions.into_iter().next().unwrap();
+ let suggestion_group = suggestion_groups.into_iter().next().unwrap();
+ let editor = workspace.update(&mut cx, |workspace, cx| {
+ let active_pane = workspace.active_pane().clone();
+ workspace.open_project_item::(active_pane, buffer, false, false, cx)
+ })?;
+
+ cx.update(|cx| {
+ for suggestion in suggestion_group.suggestions {
+ let description = suggestion.description.unwrap_or_else(|| "Delete".into());
+ let range = {
+ let buffer = editor.read(cx).buffer().read(cx).read(cx);
+ let (&excerpt_id, _, _) = buffer.as_singleton().unwrap();
+ buffer
+ .anchor_in_excerpt(excerpt_id, suggestion.range.start)
+ .unwrap()
+ ..buffer
+ .anchor_in_excerpt(excerpt_id, suggestion.range.end)
+ .unwrap()
+ };
+ let initial_text = suggestion.prepend_newline.then(|| "\n".into());
+ InlineAssistant::update_global(cx, |assistant, cx| {
+ assist_ids.push(assistant.suggest_assist(
+ &editor,
+ range,
+ description,
+ initial_text,
+ Some(workspace.clone()),
+ assistant_panel.upgrade().as_ref(),
+ cx,
+ ));
+ });
+ }
+
+ // Scroll the editor to the suggested assist
+ editor.update(cx, |editor, cx| {
+ let anchor = {
+ let buffer = editor.buffer().read(cx).read(cx);
+ let (&excerpt_id, _, _) = buffer.as_singleton().unwrap();
+ buffer
+ .anchor_in_excerpt(excerpt_id, suggestion_group.context_range.start)
+ .unwrap()
+ };
+
+ editor.set_scroll_anchor(
+ ScrollAnchor {
+ offset: gpui::Point::default(),
+ anchor,
+ },
+ cx,
+ );
+ });
+ })?;
+
+ editor
+ } else {
+ // If there are multiple buffers or suggestion groups, create a multibuffer
+ let mut inline_assist_suggestions = Vec::new();
+ let multibuffer = cx.new_model(|cx| {
+ let replica_id = project.read(cx).replica_id();
+ let mut multibuffer = MultiBuffer::new(replica_id, Capability::ReadWrite);
+ for (buffer, suggestion_groups) in edit_suggestions {
+ let excerpt_ids = multibuffer.push_excerpts(
+ buffer,
+ suggestion_groups
+ .iter()
+ .map(|suggestion_group| ExcerptRange {
+ context: suggestion_group.context_range.clone(),
+ primary: None,
+ }),
+ cx,
+ );
+
+ for (excerpt_id, suggestion_group) in
+ excerpt_ids.into_iter().zip(suggestion_groups)
+ {
+ for suggestion in suggestion_group.suggestions {
+ let description =
+ suggestion.description.unwrap_or_else(|| "Delete".into());
+ let range = {
+ let multibuffer = multibuffer.read(cx);
+ multibuffer
+ .anchor_in_excerpt(excerpt_id, suggestion.range.start)
+ .unwrap()
+ ..multibuffer
+ .anchor_in_excerpt(excerpt_id, suggestion.range.end)
+ .unwrap()
+ };
+ let initial_text =
+ suggestion.prepend_newline.then(|| "\n".to_string());
+ inline_assist_suggestions.push((range, description, initial_text));
+ }
+ }
+ }
+ multibuffer
+ })?;
+
+ let editor = cx
+ .new_view(|cx| Editor::for_multibuffer(multibuffer, Some(project), true, cx))?;
+ cx.update(|cx| {
+ InlineAssistant::update_global(cx, |assistant, cx| {
+ for (range, description, initial_text) in inline_assist_suggestions {
+ assist_ids.push(assistant.suggest_assist(
+ &editor,
+ range,
+ description,
+ initial_text,
+ Some(workspace.clone()),
+ assistant_panel.upgrade().as_ref(),
+ cx,
+ ));
+ }
+ })
+ })?;
+ workspace.update(&mut cx, |workspace, cx| {
+ workspace.add_item_to_active_pane(Box::new(editor.clone()), None, false, cx)
+ })?;
+
+ editor
+ };
+
+ this.update(&mut cx, |this, _cx| {
+ if let Some(step) = this.active_edit_step.as_mut() {
+ step.assist_ids = assist_ids;
+ step.editor = Some(editor.downgrade());
+ }
+ })
+ })
+ }
+
fn handle_editor_search_event(
&mut self,
_: View,
@@ -1785,173 +2023,6 @@ impl ContextEditor {
});
}
- fn apply_edit(&mut self, _: &ApplyEdit, cx: &mut ViewContext) {
- let Some(workspace) = self.workspace.upgrade() else {
- return;
- };
- let project = workspace.read(cx).project().clone();
-
- struct Edit {
- old_text: String,
- new_text: String,
- }
-
- let context = self.context.read(cx);
- let context_buffer = context.buffer().read(cx);
- let context_buffer_snapshot = context_buffer.snapshot();
-
- let selections = self.editor.read(cx).selections.disjoint_anchors();
- let mut selections = selections.iter().peekable();
- let selected_suggestions = context
- .edit_suggestions()
- .iter()
- .filter(|suggestion| {
- while let Some(selection) = selections.peek() {
- if selection
- .end
- .text_anchor
- .cmp(&suggestion.source_range.start, context_buffer)
- .is_lt()
- {
- selections.next();
- continue;
- }
- if selection
- .start
- .text_anchor
- .cmp(&suggestion.source_range.end, context_buffer)
- .is_gt()
- {
- break;
- }
- return true;
- }
- false
- })
- .cloned()
- .collect::>();
-
- let mut opened_buffers: HashMap>>> = HashMap::default();
- project.update(cx, |project, cx| {
- for suggestion in &selected_suggestions {
- opened_buffers
- .entry(suggestion.full_path.clone())
- .or_insert_with(|| {
- project.open_buffer_for_full_path(&suggestion.full_path, cx)
- });
- }
- });
-
- cx.spawn(|this, mut cx| async move {
- let mut buffers_by_full_path = HashMap::default();
- for (full_path, buffer) in opened_buffers {
- if let Some(buffer) = buffer.await.log_err() {
- buffers_by_full_path.insert(full_path, buffer);
- }
- }
-
- let mut suggestions_by_buffer = HashMap::default();
- cx.update(|cx| {
- for suggestion in selected_suggestions {
- if let Some(buffer) = buffers_by_full_path.get(&suggestion.full_path) {
- let (_, edits) = suggestions_by_buffer
- .entry(buffer.clone())
- .or_insert_with(|| (buffer.read(cx).snapshot(), Vec::new()));
-
- let mut lines = context_buffer_snapshot
- .as_rope()
- .chunks_in_range(
- suggestion.source_range.to_offset(&context_buffer_snapshot),
- )
- .lines();
- if let Some(suggestion) = parse_next_edit_suggestion(&mut lines) {
- let old_text = context_buffer_snapshot
- .text_for_range(suggestion.old_text_range)
- .collect();
- let new_text = context_buffer_snapshot
- .text_for_range(suggestion.new_text_range)
- .collect();
- edits.push(Edit { old_text, new_text });
- }
- }
- }
- })?;
-
- let edits_by_buffer = cx
- .background_executor()
- .spawn(async move {
- let mut result = HashMap::default();
- for (buffer, (snapshot, suggestions)) in suggestions_by_buffer {
- let edits =
- result
- .entry(buffer)
- .or_insert(Vec::<(Range, _)>::new());
- for suggestion in suggestions {
- if let Some(range) =
- fuzzy_search_lines(snapshot.as_rope(), &suggestion.old_text)
- {
- let edit_start = snapshot.anchor_after(range.start);
- let edit_end = snapshot.anchor_before(range.end);
- if let Err(ix) = edits.binary_search_by(|(range, _)| {
- range.start.cmp(&edit_start, &snapshot)
- }) {
- edits.insert(
- ix,
- (edit_start..edit_end, suggestion.new_text.clone()),
- );
- }
- } else {
- log::info!(
- "assistant edit did not match any text in buffer {:?}",
- &suggestion.old_text
- );
- }
- }
- }
- result
- })
- .await;
-
- let mut project_transaction = ProjectTransaction::default();
- let (editor, workspace, title) = this.update(&mut cx, |this, cx| {
- for (buffer_handle, edits) in edits_by_buffer {
- buffer_handle.update(cx, |buffer, cx| {
- buffer.start_transaction();
- buffer.edit(
- edits,
- Some(AutoindentMode::Block {
- original_indent_columns: Vec::new(),
- }),
- cx,
- );
- buffer.end_transaction(cx);
- if let Some(transaction) = buffer.finalize_last_transaction() {
- project_transaction
- .0
- .insert(buffer_handle.clone(), transaction.clone());
- }
- });
- }
-
- (
- this.editor.downgrade(),
- this.workspace.clone(),
- this.title(cx),
- )
- })?;
-
- Editor::open_project_transaction(
- &editor,
- workspace,
- project_transaction,
- format!("Edits from {}", title),
- cx,
- )
- .await
- })
- .detach_and_log_err(cx);
- }
-
fn save(&mut self, _: &Save, cx: &mut ViewContext) {
self.context
.update(cx, |context, cx| context.save(None, self.fs.clone(), cx));
@@ -1967,6 +2038,14 @@ impl ContextEditor {
fn render_send_button(&self, cx: &mut ViewContext) -> impl IntoElement {
let focus_handle = self.focus_handle(cx).clone();
+ let button_text = match self.edit_step_for_cursor(cx) {
+ Some(edit_step) => match &edit_step.operations {
+ Some(EditStepOperations::Pending(_)) => "Computing Changes...",
+ Some(EditStepOperations::Parsed { .. }) => "Apply Changes",
+ None => "Send",
+ },
+ None => "Send",
+ };
ButtonLike::new("send_button")
.style(ButtonStyle::Filled)
.layer(ElevationIndex::ModalSurface)
@@ -1974,11 +2053,38 @@ impl ContextEditor {
KeyBinding::for_action_in(&Assist, &focus_handle, cx)
.map(|binding| binding.into_any_element()),
)
- .child(Label::new("Send"))
+ .child(Label::new(button_text))
.on_click(move |_event, cx| {
focus_handle.dispatch_action(&Assist, cx);
})
}
+
+ fn edit_step_for_cursor<'a>(&'a self, cx: &'a AppContext) -> Option<&'a EditStep> {
+ let newest_cursor = self
+ .editor
+ .read(cx)
+ .selections
+ .newest_anchor()
+ .head()
+ .text_anchor;
+ let context = self.context.read(cx);
+ let buffer = context.buffer().read(cx);
+
+ let edit_steps = context.edit_steps();
+ edit_steps
+ .binary_search_by(|step| {
+ let step_range = step.source_range.clone();
+ if newest_cursor.cmp(&step_range.start, buffer).is_lt() {
+ Ordering::Greater
+ } else if newest_cursor.cmp(&step_range.end, buffer).is_gt() {
+ Ordering::Less
+ } else {
+ Ordering::Equal
+ }
+ })
+ .ok()
+ .map(|index| &edit_steps[index])
+ }
}
impl EventEmitter for ContextEditor {}
@@ -1995,7 +2101,7 @@ impl Render for ContextEditor {
.capture_action(cx.listener(ContextEditor::confirm_command))
.on_action(cx.listener(ContextEditor::assist))
.on_action(cx.listener(ContextEditor::split))
- .on_action(cx.listener(ContextEditor::apply_edit))
+ .on_action(cx.listener(ContextEditor::debug_edit_steps))
.size_full()
.v_flex()
.child(
diff --git a/crates/assistant/src/completion_provider.rs b/crates/assistant/src/completion_provider.rs
index a51d3256e2..13f91f70e3 100644
--- a/crates/assistant/src/completion_provider.rs
+++ b/crates/assistant/src/completion_provider.rs
@@ -20,11 +20,10 @@ use crate::{
};
use anyhow::Result;
use client::Client;
-use futures::{future::BoxFuture, stream::BoxStream};
+use futures::{future::BoxFuture, stream::BoxStream, StreamExt};
use gpui::{AnyView, AppContext, BorrowAppContext, Task, WindowContext};
use settings::{Settings, SettingsStore};
-use std::time::Duration;
-use std::{any::Any, sync::Arc};
+use std::{any::Any, pin::Pin, sync::Arc, task::Poll, time::Duration};
/// Choose which model to use for openai provider.
/// If the model is not available, try to use the first available model, or fallback to the original model.
@@ -55,10 +54,21 @@ pub fn init(client: Arc, cx: &mut AppContext) {
}
pub struct CompletionResponse {
- pub inner: BoxFuture<'static, Result>>>,
+ inner: BoxStream<'static, Result>,
_lock: SemaphoreGuardArc,
}
+impl futures::Stream for CompletionResponse {
+ type Item = Result;
+
+ fn poll_next(
+ mut self: Pin<&mut Self>,
+ cx: &mut std::task::Context<'_>,
+ ) -> Poll".len();
+
+ let doc = roxmltree::Document::parse(&xml[start_ix..end_ix]).log_err();
+ doc.map_or(Vec::new(), |doc| {
+ doc.root_element()
+ .children()
+ .map(|node| {
+ let tag_name = node.tag_name().name();
+ let path = node
+ .attribute("path")
+ .with_context(|| {
+ format!("invalid node {node:?}, missing attribute 'path'")
+ })?
+ .to_string();
+ let kind = match tag_name {
+ "update" => EditOperationKind::Update {
+ symbol: node
+ .attribute("symbol")
+ .with_context(|| {
+ format!("invalid node {node:?}, missing attribute 'symbol'")
+ })?
+ .to_string(),
+ description: node
+ .attribute("description")
+ .with_context(|| {
+ format!(
+ "invalid node {node:?}, missing attribute 'description'"
+ )
+ })?
+ .to_string(),
+ },
+ "create" => EditOperationKind::Create {
+ description: node
+ .attribute("description")
+ .with_context(|| {
+ format!(
+ "invalid node {node:?}, missing attribute 'description'"
+ )
+ })?
+ .to_string(),
+ },
+ "insert_sibling_after" => EditOperationKind::InsertSiblingAfter {
+ symbol: node
+ .attribute("symbol")
+ .with_context(|| {
+ format!("invalid node {node:?}, missing attribute 'symbol'")
+ })?
+ .to_string(),
+ description: node
+ .attribute("description")
+ .with_context(|| {
+ format!(
+ "invalid node {node:?}, missing attribute 'description'"
+ )
+ })?
+ .to_string(),
+ },
+ "insert_sibling_before" => EditOperationKind::InsertSiblingBefore {
+ symbol: node
+ .attribute("symbol")
+ .with_context(|| {
+ format!("invalid node {node:?}, missing attribute 'symbol'")
+ })?
+ .to_string(),
+ description: node
+ .attribute("description")
+ .with_context(|| {
+ format!(
+ "invalid node {node:?}, missing attribute 'description'"
+ )
+ })?
+ .to_string(),
+ },
+ "prepend_child" => EditOperationKind::PrependChild {
+ symbol: node.attribute("symbol").map(String::from),
+ description: node
+ .attribute("description")
+ .with_context(|| {
+ format!(
+ "invalid node {node:?}, missing attribute 'description'"
+ )
+ })?
+ .to_string(),
+ },
+ "append_child" => EditOperationKind::AppendChild {
+ symbol: node.attribute("symbol").map(String::from),
+ description: node
+ .attribute("description")
+ .with_context(|| {
+ format!(
+ "invalid node {node:?}, missing attribute 'description'"
+ )
+ })?
+ .to_string(),
+ },
+ "delete" => EditOperationKind::Delete {
+ symbol: node
+ .attribute("symbol")
+ .with_context(|| {
+ format!("invalid node {node:?}, missing attribute 'symbol'")
+ })?
+ .to_string(),
+ },
+ _ => return Err(anyhow!("invalid node {node:?}")),
+ };
+ anyhow::Ok(EditOperation { path, kind })
+ })
+ .filter_map(|op| op.log_err())
+ .collect()
+ })
+ }
+
pub fn pending_command_for_position(
&mut self,
position: language::Anchor,
@@ -1092,159 +1602,120 @@ impl Context {
self.count_remaining_tokens(cx);
}
- pub fn assist(
- &mut self,
- selected_messages: HashSet,
- cx: &mut ModelContext,
- ) -> Vec {
- let mut user_messages = Vec::new();
+ pub fn assist(&mut self, cx: &mut ModelContext) -> Option {
+ let last_message_id = self.message_anchors.iter().rev().find_map(|message| {
+ message
+ .start
+ .is_valid(self.buffer.read(cx))
+ .then_some(message.id)
+ })?;
- let last_message_id = if let Some(last_message_id) =
- self.message_anchors.iter().rev().find_map(|message| {
- message
- .start
- .is_valid(self.buffer.read(cx))
- .then_some(message.id)
- }) {
- last_message_id
- } else {
- return Default::default();
- };
-
- let mut should_assist = false;
- for selected_message_id in selected_messages {
- let selected_message_role =
- if let Some(metadata) = self.messages_metadata.get(&selected_message_id) {
- metadata.role
- } else {
- continue;
- };
-
- if selected_message_role == Role::Assistant {
- if let Some(user_message) = self.insert_message_after(
- selected_message_id,
- Role::User,
- MessageStatus::Done,
- cx,
- ) {
- user_messages.push(user_message);
- }
- } else {
- should_assist = true;
- }
+ if !CompletionProvider::global(cx).is_authenticated() {
+ log::info!("completion provider has no credentials");
+ return None;
}
- if should_assist {
- if !CompletionProvider::global(cx).is_authenticated() {
- log::info!("completion provider has no credentials");
- return Default::default();
- }
+ let request = self.to_completion_request(cx);
+ let stream = CompletionProvider::global(cx).stream_completion(request, cx);
+ let assistant_message = self
+ .insert_message_after(last_message_id, Role::Assistant, MessageStatus::Pending, cx)
+ .unwrap();
- let request = self.to_completion_request(cx);
- let stream = CompletionProvider::global(cx).complete(request, cx);
- let assistant_message = self
- .insert_message_after(last_message_id, Role::Assistant, MessageStatus::Pending, cx)
- .unwrap();
+ // Queue up the user's next reply.
+ let user_message = self
+ .insert_message_after(assistant_message.id, Role::User, MessageStatus::Done, cx)
+ .unwrap();
- // Queue up the user's next reply.
- let user_message = self
- .insert_message_after(assistant_message.id, Role::User, MessageStatus::Done, cx)
- .unwrap();
- user_messages.push(user_message);
+ let task = cx.spawn({
+ |this, mut cx| async move {
+ let assistant_message_id = assistant_message.id;
+ let mut response_latency = None;
+ let stream_completion = async {
+ let request_start = Instant::now();
+ let mut chunks = stream.await?;
- let task = cx.spawn({
- |this, mut cx| async move {
- let assistant_message_id = assistant_message.id;
- let mut response_latency = None;
- let stream_completion = async {
- let request_start = Instant::now();
- let mut messages = stream.await.inner.await?;
-
- while let Some(message) = messages.next().await {
- if response_latency.is_none() {
- response_latency = Some(request_start.elapsed());
- }
- let text = message?;
-
- this.update(&mut cx, |this, cx| {
- let message_ix = this
- .message_anchors
- .iter()
- .position(|message| message.id == assistant_message_id)?;
- let message_range = this.buffer.update(cx, |buffer, cx| {
- let message_start_offset =
- this.message_anchors[message_ix].start.to_offset(buffer);
- let message_old_end_offset = this.message_anchors
- [message_ix + 1..]
- .iter()
- .find(|message| message.start.is_valid(buffer))
- .map_or(buffer.len(), |message| {
- message.start.to_offset(buffer).saturating_sub(1)
- });
- let message_new_end_offset =
- message_old_end_offset + text.len();
- buffer.edit(
- [(message_old_end_offset..message_old_end_offset, text)],
- None,
- cx,
- );
- message_start_offset..message_new_end_offset
- });
- this.reparse_edit_suggestions_in_range(message_range, cx);
- cx.emit(ContextEvent::StreamedCompletion);
-
- Some(())
- })?;
- smol::future::yield_now().await;
+ while let Some(chunk) = chunks.next().await {
+ if response_latency.is_none() {
+ response_latency = Some(request_start.elapsed());
}
+ let chunk = chunk?;
this.update(&mut cx, |this, cx| {
- this.pending_completions
- .retain(|completion| completion.id != this.completion_count);
- this.summarize(cx);
+ let message_ix = this
+ .message_anchors
+ .iter()
+ .position(|message| message.id == assistant_message_id)?;
+ let message_range = this.buffer.update(cx, |buffer, cx| {
+ let message_start_offset =
+ this.message_anchors[message_ix].start.to_offset(buffer);
+ let message_old_end_offset = this.message_anchors[message_ix + 1..]
+ .iter()
+ .find(|message| message.start.is_valid(buffer))
+ .map_or(buffer.len(), |message| {
+ message.start.to_offset(buffer).saturating_sub(1)
+ });
+ let message_new_end_offset = message_old_end_offset + chunk.len();
+ buffer.edit(
+ [(message_old_end_offset..message_old_end_offset, chunk)],
+ None,
+ cx,
+ );
+ message_start_offset..message_new_end_offset
+ });
+ this.parse_edit_steps_in_range(message_range, cx);
+ cx.emit(ContextEvent::StreamedCompletion);
+
+ Some(())
})?;
-
- anyhow::Ok(())
- };
-
- let result = stream_completion.await;
+ smol::future::yield_now().await;
+ }
this.update(&mut cx, |this, cx| {
- let error_message = result
- .err()
- .map(|error| error.to_string().trim().to_string());
+ this.pending_completions
+ .retain(|completion| completion.id != this.completion_count);
+ this.summarize(cx);
+ })?;
- this.update_metadata(assistant_message_id, cx, |metadata| {
- if let Some(error_message) = error_message.as_ref() {
- metadata.status =
- MessageStatus::Error(SharedString::from(error_message.clone()));
- } else {
- metadata.status = MessageStatus::Done;
- }
- });
+ anyhow::Ok(())
+ };
- if let Some(telemetry) = this.telemetry.as_ref() {
- let model = CompletionProvider::global(cx).model();
- telemetry.report_assistant_event(
- Some(this.id.0.clone()),
- AssistantKind::Panel,
- model.telemetry_id(),
- response_latency,
- error_message,
- );
+ let result = stream_completion.await;
+
+ this.update(&mut cx, |this, cx| {
+ let error_message = result
+ .err()
+ .map(|error| error.to_string().trim().to_string());
+
+ this.update_metadata(assistant_message_id, cx, |metadata| {
+ if let Some(error_message) = error_message.as_ref() {
+ metadata.status =
+ MessageStatus::Error(SharedString::from(error_message.clone()));
+ } else {
+ metadata.status = MessageStatus::Done;
}
- })
- .ok();
- }
- });
+ });
- self.pending_completions.push(PendingCompletion {
- id: post_inc(&mut self.completion_count),
- _task: task,
- });
- }
+ if let Some(telemetry) = this.telemetry.as_ref() {
+ let model = CompletionProvider::global(cx).model();
+ telemetry.report_assistant_event(
+ Some(this.id.0.clone()),
+ AssistantKind::Panel,
+ model.telemetry_id(),
+ response_latency,
+ error_message,
+ );
+ }
+ })
+ .ok();
+ }
+ });
- user_messages
+ self.pending_completions.push(PendingCompletion {
+ id: post_inc(&mut self.completion_count),
+ _task: task,
+ });
+
+ Some(user_message)
}
pub fn to_completion_request(&self, cx: &AppContext) -> LanguageModelRequest {
@@ -1515,10 +1986,10 @@ impl Context {
temperature: 1.0,
};
- let stream = CompletionProvider::global(cx).complete(request, cx);
+ let stream = CompletionProvider::global(cx).stream_completion(request, cx);
self.pending_summary = cx.spawn(|this, mut cx| {
async move {
- let mut messages = stream.await.inner.await?;
+ let mut messages = stream.await?;
while let Some(message) = messages.next().await {
let text = message?;
@@ -1723,99 +2194,6 @@ impl ContextVersion {
}
}
-#[derive(Debug)]
-enum EditParsingState {
- None,
- InOldText {
- path: PathBuf,
- start_offset: usize,
- old_text_start_offset: usize,
- },
- InNewText {
- path: PathBuf,
- start_offset: usize,
- old_text_range: Range,
- new_text_start_offset: usize,
- },
-}
-
-#[derive(Clone, Debug, PartialEq)]
-pub struct EditSuggestion {
- pub source_range: Range,
- pub full_path: PathBuf,
-}
-
-pub struct ParsedEditSuggestion {
- pub path: PathBuf,
- pub outer_range: Range,
- pub old_text_range: Range,
- pub new_text_range: Range,
-}
-
-pub fn parse_next_edit_suggestion(lines: &mut rope::Lines) -> Option {
- let mut state = EditParsingState::None;
- loop {
- let offset = lines.offset();
- let message_line = lines.next()?;
- match state {
- EditParsingState::None => {
- if let Some(rest) = message_line.strip_prefix("```edit ") {
- let path = rest.trim();
- if !path.is_empty() {
- state = EditParsingState::InOldText {
- path: PathBuf::from(path),
- start_offset: offset,
- old_text_start_offset: lines.offset(),
- };
- }
- }
- }
- EditParsingState::InOldText {
- path,
- start_offset,
- old_text_start_offset,
- } => {
- if message_line == "---" {
- state = EditParsingState::InNewText {
- path,
- start_offset,
- old_text_range: old_text_start_offset..offset,
- new_text_start_offset: lines.offset(),
- };
- } else {
- state = EditParsingState::InOldText {
- path,
- start_offset,
- old_text_start_offset,
- };
- }
- }
- EditParsingState::InNewText {
- path,
- start_offset,
- old_text_range,
- new_text_start_offset,
- } => {
- if message_line == "```" {
- return Some(ParsedEditSuggestion {
- path,
- outer_range: start_offset..offset + "```".len(),
- old_text_range,
- new_text_range: new_text_start_offset..offset,
- });
- } else {
- state = EditParsingState::InNewText {
- path,
- start_offset,
- old_text_range,
- new_text_start_offset,
- };
- }
- }
- }
- }
-}
-
#[derive(Clone)]
pub struct PendingSlashCommand {
pub name: String,
@@ -2097,22 +2475,22 @@ pub struct SavedContextMetadata {
mod tests {
use super::*;
use crate::{
- assistant_panel,
+ assistant_panel, prompt_library,
slash_command::{active_command, file_command},
FakeCompletionProvider, MessageId,
};
use assistant_slash_command::{ArgumentCompletion, SlashCommand};
use fs::FakeFs;
use gpui::{AppContext, TestAppContext, WeakView};
+ use indoc::indoc;
use language::LspAdapterDelegate;
use parking_lot::Mutex;
use project::Project;
use rand::prelude::*;
- use rope::Rope;
use serde_json::json;
use settings::SettingsStore;
- use std::{cell::RefCell, env, path::Path, rc::Rc, sync::atomic::AtomicBool};
- use text::network::Network;
+ use std::{cell::RefCell, env, rc::Rc, sync::atomic::AtomicBool};
+ use text::{network::Network, ToPoint};
use ui::WindowContext;
use unindent::Unindent;
use util::{test::marked_text_ranges, RandomCharIter};
@@ -2551,72 +2929,151 @@ mod tests {
}
}
- #[test]
- fn test_parse_next_edit_suggestion() {
- let text = "
- some output:
+ #[gpui::test]
+ async fn test_edit_step_parsing(cx: &mut TestAppContext) {
+ cx.update(prompt_library::init);
+ let settings_store = cx.update(SettingsStore::test);
+ cx.set_global(settings_store);
+ let fake_provider = cx.update(FakeCompletionProvider::setup_test);
+ cx.update(assistant_panel::init);
+ let registry = Arc::new(LanguageRegistry::test(cx.executor()));
- ```edit src/foo.rs
- let a = 1;
- let b = 2;
- ---
- let w = 1;
- let x = 2;
- let y = 3;
- let z = 4;
+ // Create a new context
+ let context = cx.new_model(|cx| Context::local(registry.clone(), None, cx));
+ let buffer = context.read_with(cx, |context, _| context.buffer.clone());
+
+ // Simulate user input
+ let user_message = indoc! {r#"
+ Please refactor this code:
+
+ fn main() {
+ println!("Hello, World!");
+ }
+ "#};
+ buffer.update(cx, |buffer, cx| {
+ buffer.edit([(0..0, user_message)], None, cx);
+ });
+
+ // Simulate LLM response with edit steps
+ let llm_response = indoc! {r#"
+ Sure, I can help you refactor that code. Here's a step-by-step process:
+
+
+ First, let's extract the greeting into a separate function:
+
+ ```rust
+ fn greet() {
+ println!("Hello, World!");
+ }
+
+ fn main() {
+ greet();
+ }
```
+
- some more output:
+
+ Now, let's make the greeting customizable:
- ```edit src/foo.rs
- let c = 1;
- ---
+ ```rust
+ fn greet(name: &str) {
+ println!("Hello, {}!", name);
+ }
+
+ fn main() {
+ greet("World");
+ }
```
+
- and the conclusion.
- "
- .unindent();
+ These changes make the code more modular and flexible.
+ "#};
- let rope = Rope::from(text.as_str());
- let mut lines = rope.chunks().lines();
- let mut suggestions = vec![];
- while let Some(suggestion) = parse_next_edit_suggestion(&mut lines) {
- suggestions.push((
- suggestion.path.clone(),
- text[suggestion.old_text_range].to_string(),
- text[suggestion.new_text_range].to_string(),
- ));
+ // Simulate the assist method to trigger the LLM response
+ context.update(cx, |context, cx| context.assist(cx));
+ cx.run_until_parked();
+
+ // Retrieve the assistant response message's start from the context
+ let response_start_row = context.read_with(cx, |context, cx| {
+ let buffer = context.buffer.read(cx);
+ context.message_anchors[1].start.to_point(buffer).row
+ });
+
+ // Simulate the LLM completion
+ fake_provider.send_last_completion_chunk(llm_response.to_string());
+ fake_provider.finish_last_completion();
+
+ // Wait for the completion to be processed
+ cx.run_until_parked();
+
+ // Verify that the edit steps were parsed correctly
+ context.read_with(cx, |context, cx| {
+ assert_eq!(
+ edit_steps(context, cx),
+ vec![
+ Point::new(response_start_row + 2, 0)..Point::new(response_start_row + 14, 7),
+ Point::new(response_start_row + 16, 0)..Point::new(response_start_row + 28, 7),
+ ]
+ );
+ });
+
+ fn edit_steps(context: &Context, cx: &AppContext) -> Vec> {
+ context
+ .edit_steps
+ .iter()
+ .map(|step| {
+ let buffer = context.buffer.read(cx);
+ step.source_range.to_point(buffer)
+ })
+ .collect()
}
+ }
+ #[test]
+ fn test_parse_edit_operations() {
+ let operations = indoc! {r#"
+ Here are the operations to make all fields of the Canvas struct private:
+
+
+
+
+
+
+
+ "#};
+
+ let parsed_operations = Context::parse_edit_operations(operations);
assert_eq!(
- suggestions,
+ parsed_operations,
vec![
- (
- Path::new("src/foo.rs").into(),
- [
- " let a = 1;", //
- " let b = 2;",
- "",
- ]
- .join("\n"),
- [
- " let w = 1;",
- " let x = 2;",
- " let y = 3;",
- " let z = 4;",
- "",
- ]
- .join("\n"),
- ),
- (
- Path::new("src/foo.rs").into(),
- [
- " let c = 1;", //
- "",
- ]
- .join("\n"),
- String::new(),
- )
+ EditOperation {
+ path: "font-kit/src/canvas.rs".to_string(),
+ kind: EditOperationKind::Update {
+ symbol: "pub struct Canvas pub pixels".to_string(),
+ description: "Remove pub keyword from pixels field".to_string(),
+ },
+ },
+ EditOperation {
+ path: "font-kit/src/canvas.rs".to_string(),
+ kind: EditOperationKind::Update {
+ symbol: "pub struct Canvas pub size".to_string(),
+ description: "Remove pub keyword from size field".to_string(),
+ },
+ },
+ EditOperation {
+ path: "font-kit/src/canvas.rs".to_string(),
+ kind: EditOperationKind::Update {
+ symbol: "pub struct Canvas pub stride".to_string(),
+ description: "Remove pub keyword from stride field".to_string(),
+ },
+ },
+ EditOperation {
+ path: "font-kit/src/canvas.rs".to_string(),
+ kind: EditOperationKind::Update {
+ symbol: "pub struct Canvas pub format".to_string(),
+ description: "Remove pub keyword from format field".to_string(),
+ },
+ },
]
);
}
diff --git a/crates/assistant/src/inline_assistant.rs b/crates/assistant/src/inline_assistant.rs
index 4ea5696ca7..11672fcb67 100644
--- a/crates/assistant/src/inline_assistant.rs
+++ b/crates/assistant/src/inline_assistant.rs
@@ -16,7 +16,12 @@ use editor::{
ExcerptRange, GutterDimensions, MultiBuffer, MultiBufferSnapshot, ToOffset, ToPoint,
};
use fs::Fs;
-use futures::{channel::mpsc, SinkExt, Stream, StreamExt};
+use futures::{
+ channel::mpsc,
+ future::LocalBoxFuture,
+ stream::{self, BoxStream},
+ SinkExt, Stream, StreamExt,
+};
use gpui::{
point, AppContext, EventEmitter, FocusHandle, FocusableView, FontStyle, Global, HighlightStyle,
Model, ModelContext, Subscription, Task, TextStyle, UpdateGlobal, View, ViewContext, WeakView,
@@ -28,8 +33,11 @@ use parking_lot::Mutex;
use rope::Rope;
use settings::{update_settings_file, Settings};
use similar::TextDiff;
+use smol::future::FutureExt;
use std::{
- cmp, mem,
+ cmp,
+ future::Future,
+ mem,
ops::{Range, RangeInclusive},
pin::Pin,
sync::Arc,
@@ -134,7 +142,6 @@ impl InlineAssistant {
let prompt_buffer = cx.new_model(|cx| MultiBuffer::singleton(prompt_buffer, cx));
let mut assists = Vec::new();
- let mut assist_blocks = Vec::new();
let mut assist_to_focus = None;
for range in codegen_ranges {
let assist_id = self.next_assist_id.post_inc();
@@ -142,6 +149,7 @@ impl InlineAssistant {
Codegen::new(
editor.read(cx).buffer().clone(),
range.clone(),
+ None,
self.telemetry.clone(),
cx,
)
@@ -174,42 +182,18 @@ impl InlineAssistant {
}
}
- assist_blocks.push(BlockProperties {
- style: BlockStyle::Sticky,
- position: range.start,
- height: prompt_editor.read(cx).height_in_lines,
- render: build_assist_editor_renderer(&prompt_editor),
- disposition: BlockDisposition::Above,
- });
- assist_blocks.push(BlockProperties {
- style: BlockStyle::Sticky,
- position: range.end,
- height: 1,
- render: Box::new(|cx| {
- v_flex()
- .h_full()
- .w_full()
- .border_t_1()
- .border_color(cx.theme().status().info_border)
- .into_any_element()
- }),
- disposition: BlockDisposition::Below,
- });
- assists.push((assist_id, prompt_editor));
- }
+ let [prompt_block_id, end_block_id] =
+ self.insert_assist_blocks(editor, &range, &prompt_editor, cx);
- let assist_block_ids = editor.update(cx, |editor, cx| {
- editor.insert_blocks(assist_blocks, None, cx)
- });
+ assists.push((assist_id, prompt_editor, prompt_block_id, end_block_id));
+ }
let editor_assists = self
.assists_by_editor
.entry(editor.downgrade())
.or_insert_with(|| EditorInlineAssists::new(&editor, cx));
let mut assist_group = InlineAssistGroup::new();
- for ((assist_id, prompt_editor), block_ids) in
- assists.into_iter().zip(assist_block_ids.chunks_exact(2))
- {
+ for (assist_id, prompt_editor, prompt_block_id, end_block_id) in assists {
self.assists.insert(
assist_id,
InlineAssist::new(
@@ -218,8 +202,8 @@ impl InlineAssistant {
assistant_panel.is_some(),
editor,
&prompt_editor,
- block_ids[0],
- block_ids[1],
+ prompt_block_id,
+ end_block_id,
prompt_editor.read(cx).codegen.clone(),
workspace.clone(),
cx,
@@ -235,6 +219,128 @@ impl InlineAssistant {
}
}
+ #[allow(clippy::too_many_arguments)]
+ pub fn suggest_assist(
+ &mut self,
+ editor: &View,
+ mut range: Range,
+ initial_prompt: String,
+ initial_insertion: Option,
+ workspace: Option>,
+ assistant_panel: Option<&View>,
+ cx: &mut WindowContext,
+ ) -> InlineAssistId {
+ let assist_group_id = self.next_assist_group_id.post_inc();
+ let prompt_buffer = cx.new_model(|cx| Buffer::local(&initial_prompt, cx));
+ let prompt_buffer = cx.new_model(|cx| MultiBuffer::singleton(prompt_buffer, cx));
+
+ let assist_id = self.next_assist_id.post_inc();
+
+ let buffer = editor.read(cx).buffer().clone();
+ let prepend_transaction_id = initial_insertion.and_then(|initial_insertion| {
+ buffer.update(cx, |buffer, cx| {
+ buffer.start_transaction(cx);
+ buffer.edit([(range.start..range.start, initial_insertion)], None, cx);
+ buffer.end_transaction(cx)
+ })
+ });
+
+ range.start = range.start.bias_left(&buffer.read(cx).read(cx));
+ range.end = range.end.bias_right(&buffer.read(cx).read(cx));
+
+ let codegen = cx.new_model(|cx| {
+ Codegen::new(
+ editor.read(cx).buffer().clone(),
+ range.clone(),
+ prepend_transaction_id,
+ self.telemetry.clone(),
+ cx,
+ )
+ });
+
+ let gutter_dimensions = Arc::new(Mutex::new(GutterDimensions::default()));
+ let prompt_editor = cx.new_view(|cx| {
+ PromptEditor::new(
+ assist_id,
+ gutter_dimensions.clone(),
+ self.prompt_history.clone(),
+ prompt_buffer.clone(),
+ codegen.clone(),
+ editor,
+ assistant_panel,
+ workspace.clone(),
+ self.fs.clone(),
+ cx,
+ )
+ });
+
+ let [prompt_block_id, end_block_id] =
+ self.insert_assist_blocks(editor, &range, &prompt_editor, cx);
+
+ let editor_assists = self
+ .assists_by_editor
+ .entry(editor.downgrade())
+ .or_insert_with(|| EditorInlineAssists::new(&editor, cx));
+
+ let mut assist_group = InlineAssistGroup::new();
+ self.assists.insert(
+ assist_id,
+ InlineAssist::new(
+ assist_id,
+ assist_group_id,
+ assistant_panel.is_some(),
+ editor,
+ &prompt_editor,
+ prompt_block_id,
+ end_block_id,
+ prompt_editor.read(cx).codegen.clone(),
+ workspace.clone(),
+ cx,
+ ),
+ );
+ assist_group.assist_ids.push(assist_id);
+ editor_assists.assist_ids.push(assist_id);
+ self.assist_groups.insert(assist_group_id, assist_group);
+ assist_id
+ }
+
+ fn insert_assist_blocks(
+ &self,
+ editor: &View,
+ range: &Range,
+ prompt_editor: &View,
+ cx: &mut WindowContext,
+ ) -> [BlockId; 2] {
+ let assist_blocks = vec![
+ BlockProperties {
+ style: BlockStyle::Sticky,
+ position: range.start,
+ height: prompt_editor.read(cx).height_in_lines,
+ render: build_assist_editor_renderer(prompt_editor),
+ disposition: BlockDisposition::Above,
+ },
+ BlockProperties {
+ style: BlockStyle::Sticky,
+ position: range.end,
+ height: 1,
+ render: Box::new(|cx| {
+ v_flex()
+ .h_full()
+ .w_full()
+ .border_t_1()
+ .border_color(cx.theme().status().info_border)
+ .into_any_element()
+ }),
+ disposition: BlockDisposition::Below,
+ },
+ ];
+
+ editor.update(cx, |editor, cx| {
+ let block_ids = editor.insert_blocks(assist_blocks, None, cx);
+ [block_ids[0], block_ids[1]]
+ })
+ }
+
fn handle_prompt_editor_focus_in(&mut self, assist_id: InlineAssistId, cx: &mut WindowContext) {
let assist = &self.assists[&assist_id];
let Some(decorations) = assist.decorations.as_ref() else {
@@ -379,6 +485,14 @@ impl InlineAssistant {
cx.propagate();
}
+ fn handle_editor_release(&mut self, editor: WeakView, cx: &mut WindowContext) {
+ if let Some(editor_assists) = self.assists_by_editor.get_mut(&editor) {
+ for assist_id in editor_assists.assist_ids.clone() {
+ self.finish_assist(assist_id, true, cx);
+ }
+ }
+ }
+
fn handle_editor_change(&mut self, editor: View, cx: &mut WindowContext) {
let Some(editor_assists) = self.assists_by_editor.get(&editor.downgrade()) else {
return;
@@ -698,7 +812,7 @@ impl InlineAssistant {
assist_group.assist_ids.clone()
}
- fn start_assist(&mut self, assist_id: InlineAssistId, cx: &mut WindowContext) {
+ pub fn start_assist(&mut self, assist_id: InlineAssistId, cx: &mut WindowContext) {
let assist = if let Some(assist) = self.assists.get_mut(&assist_id) {
assist
} else {
@@ -727,16 +841,26 @@ impl InlineAssistant {
self.prompt_history.pop_front();
}
- assist.codegen.update(cx, |codegen, cx| codegen.undo(cx));
let codegen = assist.codegen.clone();
- let request = self.request_for_inline_assist(assist_id, cx);
-
- cx.spawn(|mut cx| async move {
- let request = request.await?;
- codegen.update(&mut cx, |codegen, cx| codegen.start(request, cx))?;
- anyhow::Ok(())
- })
- .detach_and_log_err(cx);
+ let telemetry_id = CompletionProvider::global(cx).model().telemetry_id();
+ let chunks: LocalBoxFuture>>> =
+ if user_prompt.trim().to_lowercase() == "delete" {
+ async { Ok(stream::empty().boxed()) }.boxed_local()
+ } else {
+ let request = self.request_for_inline_assist(assist_id, cx);
+ let mut cx = cx.to_async();
+ async move {
+ let request = request.await?;
+ let chunks = cx
+ .update(|cx| CompletionProvider::global(cx).stream_completion(request, cx))?
+ .await?;
+ Ok(chunks.boxed())
+ }
+ .boxed_local()
+ };
+ codegen.update(cx, |codegen, cx| {
+ codegen.start(telemetry_id, chunks, cx);
+ });
}
fn request_for_inline_assist(
@@ -855,7 +979,7 @@ impl InlineAssistant {
})
}
- fn stop_assist(&mut self, assist_id: InlineAssistId, cx: &mut WindowContext) {
+ pub fn stop_assist(&mut self, assist_id: InlineAssistId, cx: &mut WindowContext) {
let assist = if let Some(assist) = self.assists.get_mut(&assist_id) {
assist
} else {
@@ -1074,6 +1198,14 @@ impl EditorInlineAssists {
}
}),
_subscriptions: vec![
+ cx.observe_release(editor, {
+ let editor = editor.downgrade();
+ |_, cx| {
+ InlineAssistant::update_global(cx, |this, cx| {
+ this.handle_editor_release(editor, cx);
+ })
+ }
+ }),
cx.observe(editor, move |editor, cx| {
InlineAssistant::update_global(cx, |this, cx| {
this.handle_editor_change(editor, cx)
@@ -1138,7 +1270,7 @@ fn build_assist_editor_renderer(editor: &View) -> RenderBlock {
}
#[derive(Copy, Clone, Default, Debug, PartialEq, Eq, Hash)]
-struct InlineAssistId(usize);
+pub struct InlineAssistId(usize);
impl InlineAssistId {
fn post_inc(&mut self) -> InlineAssistId {
@@ -1882,7 +2014,8 @@ pub struct Codegen {
range: Range,
edit_position: Anchor,
last_equal_ranges: Vec>,
- transaction_id: Option,
+ prepend_transaction_id: Option,
+ generation_transaction_id: Option,
status: CodegenStatus,
generation: Task<()>,
diff: Diff,
@@ -1911,6 +2044,7 @@ impl Codegen {
pub fn new(
buffer: Model,
range: Range,
+ prepend_transaction_id: Option,
telemetry: Option>,
cx: &mut ModelContext,
) -> Self {
@@ -1943,7 +2077,8 @@ impl Codegen {
range,
snapshot,
last_equal_ranges: Default::default(),
- transaction_id: Default::default(),
+ prepend_transaction_id,
+ generation_transaction_id: None,
status: CodegenStatus::Idle,
generation: Task::ready(()),
diff: Diff::default(),
@@ -1959,8 +2094,13 @@ impl Codegen {
cx: &mut ModelContext,
) {
if let multi_buffer::Event::TransactionUndone { transaction_id } = event {
- if self.transaction_id == Some(*transaction_id) {
- self.transaction_id = None;
+ if self.generation_transaction_id == Some(*transaction_id) {
+ self.generation_transaction_id = None;
+ self.generation = Task::ready(());
+ cx.emit(CodegenEvent::Undone);
+ } else if self.prepend_transaction_id == Some(*transaction_id) {
+ self.prepend_transaction_id = None;
+ self.generation_transaction_id = None;
self.generation = Task::ready(());
cx.emit(CodegenEvent::Undone);
}
@@ -1971,7 +2111,12 @@ impl Codegen {
&self.last_equal_ranges
}
- pub fn start(&mut self, prompt: LanguageModelRequest, cx: &mut ModelContext) {
+ pub fn start(
+ &mut self,
+ telemetry_id: String,
+ stream: impl 'static + Future