Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
Add experimental Sweep edit prediction provider (#42927)
Agus Zubiaga0386f240a9f3
diff --git a/Cargo.lock b/Cargo.lockindex 9aa674cbb69..c0f6ef03c29 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -5314,6 +5314,7 @@ dependencies = ["serde_json","settings","supermaven",+ "sweep_ai","telemetry","theme","ui",@@ -16590,6 +16591,33 @@ dependencies = ["zeno",]+[[package]]+name = "sweep_ai"+version = "0.1.0"+dependencies = [+ "anyhow",+ "arrayvec",+ "brotli",+ "client",+ "collections",+ "edit_prediction",+ "feature_flags",+ "futures 0.3.31",+ "gpui",+ "http_client",+ "indoc",+ "language",+ "project",+ "release_channel",+ "reqwest_client",+ "serde",+ "serde_json",+ "tree-sitter-rust",+ "util",+ "workspace",+ "zlog",+]+[[package]]name = "symphonia"version = "0.5.5"@@ -21316,6 +21344,7 @@ dependencies = ["snippets_ui","supermaven","svg_preview",+ "sweep_ai","sysinfo 0.37.2","system_specs","tab_switcher",diff --git a/Cargo.toml b/Cargo.tomlindex be56964f753..e74647c6320 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -165,6 +165,7 @@ members = ["crates/sum_tree","crates/supermaven","crates/supermaven_api",+ "crates/sweep_ai","crates/codestral","crates/svg_preview","crates/system_specs",@@ -398,6 +399,7 @@ streaming_diff = { path = "crates/streaming_diff" }sum_tree = { path = "crates/sum_tree" }supermaven = { path = "crates/supermaven" }supermaven_api = { path = "crates/supermaven_api" }+sweep_ai = { path = "crates/sweep_ai" }codestral = { path = "crates/codestral" }system_specs = { path = "crates/system_specs" }tab_switcher = { path = "crates/tab_switcher" }@@ -478,6 +480,7 @@ bitflags = "2.6.0"blade-graphics = { version = "0.7.0" }blade-macros = { version = "0.3.0" }blade-util = { version = "0.3.0" }+brotli = "8.0.2"bytes = "1.0"cargo_metadata = "0.19"cargo_toml = "0.21"diff --git a/assets/icons/sweep_ai.svg b/assets/icons/sweep_ai.svgnew file mode 100644index 00000000000..c78d12727d7--- /dev/null+++ b/assets/icons/sweep_ai.svg@@ -0,0 +1 @@+<svg xmlns="http://www.w3.org/2000/svg" width="245" height="356" fill="none" viewBox="0 0 245 356"><mask id="a" fill="#fff"><path fill-rule="evenodd" d="M121.403 121.347c12.011.485 22.683-.041 32.093-1.216-3.749 32.028-12.757 63.693-27.191 93.644a70 70 0 0 1-9.028-5.996 70 70 0 0 1-11.234-11.008 113.3 113.3 0 0 1 9.195 24.423c-9.531 11.874-20.982 21.327-33.56 28.264-35.608-12.781-60.408-42.701-60.408-85.952 0-24.619 8.035-47.284 21.524-65.312 11.625 8.466 36.132 21.436 78.609 23.153m7.652 135.012c53.428-1.187 89.924-20.315 115.945-92.853-28.875 0-35.859-20.92-43.633-44.208-1.321-3.955-2.664-7.979-4.141-11.98-7.188 3.737-17.309 7.818-30.709 10.644-3.859 34.443-13.793 68.49-30.009 100.463a69.5 69.5 0 0 0 26.003 4.081 112.5 112.5 0 0 0-34.691 24.8q.73 4.512 1.235 9.053m-41.909-97.323c0-6.311 5.116-11.427 11.427-11.427S110 152.725 110 159.036v12.255c0 6.311-5.116 11.427-11.427 11.427-6.31 0-11.427-5.116-11.427-11.427zM52.83 147.609c-5.762 0-10.433 4.671-10.433 10.433v14.243c0 5.762 4.67 10.433 10.433 10.433 5.762 0 10.433-4.671 10.433-10.433v-14.243c0-5.762-4.67-10.433-10.433-10.433" clip-rule="evenodd"/></mask><path fill="#fff" fill-rule="evenodd" d="M121.403 121.347c12.011.485 22.683-.041 32.093-1.216-3.749 32.028-12.757 63.693-27.191 93.644a70 70 0 0 1-9.028-5.996 70 70 0 0 1-11.234-11.008 113.3 113.3 0 0 1 9.195 24.423c-9.531 11.874-20.982 21.327-33.56 28.264-35.608-12.781-60.408-42.701-60.408-85.952 0-24.619 8.035-47.284 21.524-65.312 11.625 8.466 36.132 21.436 78.609 23.153m7.652 135.012c53.428-1.187 89.924-20.315 115.945-92.853-28.875 0-35.859-20.92-43.633-44.208-1.321-3.955-2.664-7.979-4.141-11.98-7.188 3.737-17.309 7.818-30.709 10.644-3.859 34.443-13.793 68.49-30.009 100.463a69.5 69.5 0 0 0 26.003 4.081 112.5 112.5 0 0 0-34.691 24.8q.73 4.512 1.235 9.053m-41.909-97.323c0-6.311 5.116-11.427 11.427-11.427S110 152.725 110 159.036v12.255c0 6.311-5.116 11.427-11.427 11.427-6.31 0-11.427-5.116-11.427-11.427zM52.83 147.609c-5.762 0-10.433 4.671-10.433 10.433v14.243c0 5.762 4.67 10.433 10.433 10.433 5.762 0 10.433-4.671 10.433-10.433v-14.243c0-5.762-4.67-10.433-10.433-10.433" clip-rule="evenodd"/><path fill="#fff" d="m153.496 120.131 4.061.475.606-5.178-5.174.646zm-32.093 1.216.165-4.086zm4.902 92.428-1.991 3.571 3.791 2.114 1.884-3.91zm-9.028-5.996-2.517 3.222zm-11.234-11.008 3.174-2.579-6.808 4.451zm9.195 24.423 3.188 2.559 1.27-1.582-.492-1.968zm-33.56 28.264-1.38 3.848 1.738.624 1.617-.892zM21.27 163.506h-4.089zm21.524-65.312L45.2 94.89l-3.262-2.376-2.418 3.232zm86.261 158.165-4.063.453.414 3.718 3.74-.083zM245 163.506l3.848 1.38 1.962-5.469H245zm-43.633-44.208-3.879 1.295zm-4.141-11.98 3.835-1.416-1.606-4.352-4.116 2.14zm-30.709 10.644-.843-4.001-2.891.61-.329 2.935zm-30.009 100.463-3.647-1.849-2.092 4.124 4.35 1.571zm26.003 4.081 1.705 3.716-1.845-7.802zm-34.691 24.8-2.963-2.817-1.396 1.469.323 2.001zm25.169-131.232c-9.181 1.146-19.627 1.664-31.421 1.187l-.331 8.171c12.23.494 23.126-.041 32.765-1.244zm-23 99.476c14.634-30.368 23.767-62.473 27.568-94.944l-8.122-.95c-3.697 31.586-12.58 62.81-26.813 92.344zm-1.692-5.346a66 66 0 0 1-8.503-5.647l-5.034 6.444a74 74 0 0 0 9.554 6.345zm-8.503-5.647a65.8 65.8 0 0 1-10.577-10.365l-6.347 5.157a74 74 0 0 0 11.89 11.652zm-17.385-5.914a109.2 109.2 0 0 1 8.862 23.542l7.933-1.982a117.3 117.3 0 0 0-9.526-25.305zm9.64 19.992c-9.19 11.449-20.226 20.559-32.345 27.242l3.95 7.161c13.036-7.19 24.902-16.987 34.772-29.285zm-94.868-55.129c0 45.115 26.017 76.484 63.116 89.8l2.763-7.697c-34.118-12.245-57.701-40.715-57.701-82.103zM39.52 95.745c-14.008 18.721-22.339 42.242-22.339 67.761h8.178c0-23.719 7.738-45.528 20.708-62.862zm82.048 21.516c-41.657-1.684-65.386-14.376-76.368-22.372l-4.813 6.611c12.27 8.934 37.554 22.182 80.85 23.932zm7.578 143.186c27.167-.604 50.592-5.78 70.58-20.463 19.952-14.657 35.959-38.404 49.122-75.098l-7.697-2.761c-12.858 35.845-28.109 57.931-46.267 71.269-18.122 13.313-39.659 18.294-65.92 18.878zM245 159.417c-13.218 0-20.975-4.68-26.501-11.791-5.813-7.479-9.304-17.791-13.254-29.622l-7.757 2.589c3.825 11.456 7.713 23.248 14.554 32.051 7.127 9.17 17.3 14.95 32.958 14.95zm-39.755-41.413c-1.317-3.946-2.681-8.031-4.184-12.102l-7.671 2.832c1.451 3.931 2.775 7.894 4.098 11.859zm-9.906-14.314c-6.87 3.573-16.641 7.525-29.665 10.271l1.687 8.001c13.776-2.904 24.247-7.114 31.751-11.017zm-32.885 13.816c-3.805 33.968-13.602 67.542-29.593 99.07l7.293 3.699c16.442-32.418 26.514-66.938 30.427-101.858zm-.083 100.914a65.5 65.5 0 0 1-24.475-3.84l-2.777 7.691a73.6 73.6 0 0 0 27.532 4.321zm-31.587 31.703a108.5 108.5 0 0 1 33.432-23.901l-3.41-7.432a116.6 116.6 0 0 0-35.949 25.699zm2.335 5.784a189 189 0 0 0-1.262-9.254l-8.073 1.306q.713 4.41 1.208 8.853zM98.573 143.52c-8.569 0-15.515 6.947-15.515 15.516h8.177a7.34 7.34 0 0 1 7.338-7.339zm15.516 15.516c0-8.569-6.947-15.516-15.516-15.516v8.177a7.34 7.34 0 0 1 7.339 7.339zm0 12.255v-12.255h-8.177v12.255zm-15.516 15.516c8.569 0 15.516-6.947 15.516-15.516h-8.177a7.34 7.34 0 0 1-7.339 7.338zm-15.515-15.516c0 8.569 6.946 15.516 15.515 15.516v-8.178a7.34 7.34 0 0 1-7.338-7.338zm0-12.255v12.255h8.177v-12.255zm-36.574-.994a6.345 6.345 0 0 1 6.345-6.345v-8.177c-8.02 0-14.522 6.502-14.522 14.522zm0 14.243v-14.243h-8.177v14.243zm6.345 6.344a6.344 6.344 0 0 1-6.345-6.344h-8.177c0 8.02 6.502 14.522 14.522 14.522zm6.345-6.344a6.344 6.344 0 0 1-6.345 6.344v8.178c8.02 0 14.522-6.502 14.522-14.522zm0-14.243v14.243h8.177v-14.243zm-6.345-6.345a6.345 6.345 0 0 1 6.345 6.345h8.177c0-8.02-6.502-14.522-14.522-14.522z" mask="url(#a)"/><path fill="#fff" fill-rule="evenodd" d="M99.84 332.862a128 128 0 0 0 6.312-17.123c4.241-14.635 5.728-29.415 4.766-43.785a127.4 127.4 0 0 1-4.699 26.02c-3.507 12.102-8.659 23.28-15.141 33.363 2.906.625 5.83 1.133 8.763 1.525" clip-rule="evenodd"/><path fill="#fff" d="M165.798 158.877a20.794 20.794 0 1 0 0 41.588v-41.588"/><mask id="b" width="178.263" height="188.092" x="55.131" y="38.105" fill="#000" maskUnits="userSpaceOnUse"><path fill="#fff" d="M55.131 38.105h178.263v188.092H55.131z"/><path fill-rule="evenodd" d="M166.745 53.908c5.809 55.53-3.978 112.744-30.238 164.518a69 69 0 0 1-10.202-4.651c25.079-52.041 33.779-109.257 26.969-164.564a69 69 0 0 0 13.471 4.697" clip-rule="evenodd"/></mask><path fill="#fff" d="m136.507 218.426 2.765 1.402-1.24 2.444-2.577-.931zm30.238-164.518.714-3.016 2.14.506.229 2.188zm-40.44 159.867-1.509 2.707-2.55-1.422 1.267-2.63zm26.969-164.564-3.076.379-.686-5.569 5.079 2.384zm-19.531 167.813c25.982-51.227 35.669-107.84 29.92-162.793l6.165-.645c5.869 56.106-4.019 113.92-30.556 166.242zm-5.928-5.956a66 66 0 0 0 9.745 4.443l-2.105 5.83a72 72 0 0 1-10.659-4.859zM156.35 48.832c6.88 55.881-1.908 113.697-27.253 166.289l-5.584-2.691c24.814-51.491 33.424-108.107 26.685-162.84zm9.682 8.093a72.3 72.3 0 0 1-14.075-4.908l2.634-5.612a66 66 0 0 0 12.868 4.487z" mask="url(#b)"/><path fill="#fff" fill-rule="evenodd" d="m208.815 50.075-4.33-1.78-1.301 4.498 4.034 1.167a746 746 0 0 0-4.035-1.165l-.001.003-.002.007-.006.02-.019.069a52 52 0 0 0-.293 1.106 78 78 0 0 0-.722 3.127 93 93 0 0 0-1.589 10.524c-.751 8.246-.548 19.212 4.121 28.112.314.597.39 1.164.345 1.534-.037.31-.134.406-.226.474-5.4 3.95-17.538 11.317-37.814 15.795a296 296 0 0 1-.459 4.396c21.679-4.572 34.776-12.429 40.753-16.802 2.294-1.678 2.441-4.83 1.12-7.348-6.117-11.662-3.749-28.143-2.159-35.733.538-2.569.986-4.119.986-4.119q.972.399 1.954.565c12.266 2.107 25.24-21.913 30.603-33.18 1.419-2.982-.152-6.382-3.365-7.146C204.942 6.713 57.706-22.077 34.89 88.235c-.331 1.606.1 3.335 1.282 4.474 6.526 6.29 31.502 26.466 85.231 28.638 12.011.485 22.683-.041 32.093-1.216q.25-2.146.471-4.295c-9.422 1.235-20.19 1.807-32.395 1.314-52.622-2.127-76.642-21.833-82.485-27.465a.35.35 0 0 1-.075-.156 1 1 0 0 1-.008-.444c5.494-26.566 18.395-44.535 35.04-56.61 16.745-12.146 37.522-18.493 58.902-21.267 42.82-5.556 86.893 3.366 102.492 7.077.341.08.505.26.588.436.086.183.126.463-.043.818-2.789 5.859-7.56 14.98-13.086 21.924-2.777 3.49-5.537 6.163-8.104 7.67-2.489 1.459-4.367 1.604-5.978.942" clip-rule="evenodd"/><mask id="c" fill="#fff"><path fill-rule="evenodd" d="M127.821 247.306a112.5 112.5 0 0 1 34.69-24.8c-15.775.541-31.822-4.249-45.234-14.727a70 70 0 0 1-11.233-11.008 113.4 113.4 0 0 1 9.194 24.423C89.042 253.831 48.335 268.185 9.6 262.231c7.163 18.17 19.123 34.725 35.628 47.618 22.479 17.56 49.508 25.296 75.915 23.842 9.185-28.106 11.305-57.766 6.678-86.385" clip-rule="evenodd"/></mask><path fill="#fff" d="m162.511 222.506-.177-5.163 2.331 9.858zm-34.69 24.8-5.1.825-.409-2.528 1.764-1.855zm-21.777-50.535-4.593 2.365 8.602-5.623zm9.194 24.423 5.011-1.252.621 2.487-1.604 1.998zM9.6 262.231l-4.806 1.895-3.298-8.367 8.889 1.367zm111.543 71.46 4.91 1.605-1.097 3.359-3.529.194zm43.522-106.49a107.4 107.4 0 0 0-33.1 23.664l-7.489-7.117a117.7 117.7 0 0 1 36.281-25.937zm-44.208-23.493c12.421 9.704 27.269 14.136 41.877 13.635l.354 10.326c-16.943.58-34.188-4.567-48.591-15.819zm-10.404-10.195a64.7 64.7 0 0 0 10.404 10.195l-6.36 8.142a75 75 0 0 1-12.063-11.822zm.173 28.933a108 108 0 0 0-8.775-23.31l9.185-4.731a118.4 118.4 0 0 1 9.613 25.537zm-99.841 34.68c36.984 5.684 75.828-8.023 100.824-39.166l8.057 6.467C91.87 258.56 49.302 273.56 8.816 267.337zm31.663 56.794c-17.251-13.476-29.762-30.79-37.254-49.794l9.612-3.789c6.834 17.336 18.243 33.131 34.002 45.442zm79.379 24.929c-27.607 1.52-55.878-6.57-79.38-24.929l6.36-8.141c21.458 16.761 47.245 24.142 72.452 22.754zm11.493-92.367c4.756 29.416 2.579 59.91-6.867 88.814l-9.82-3.21c8.925-27.308 10.986-56.135 6.488-83.955z" mask="url(#c)"/></svg>diff --git a/crates/agent_ui/src/agent_ui.rs b/crates/agent_ui/src/agent_ui.rsindex da1543a2790..6396b68cbc5 100644--- a/crates/agent_ui/src/agent_ui.rs+++ b/crates/agent_ui/src/agent_ui.rs@@ -346,7 +346,9 @@ fn update_command_palette_filter(cx: &mut App) {filter.show_namespace("supermaven");filter.show_action_types(edit_prediction_actions.iter());}- EditPredictionProvider::Zed | EditPredictionProvider::Codestral => {+ EditPredictionProvider::Zed+ | EditPredictionProvider::Codestral+ | EditPredictionProvider::Experimental(_) => {filter.show_namespace("edit_prediction");filter.hide_namespace("copilot");filter.hide_namespace("supermaven");diff --git a/crates/edit_prediction_button/Cargo.toml b/crates/edit_prediction_button/Cargo.tomlindex 189db7f7bac..3ed3d941151 100644--- a/crates/edit_prediction_button/Cargo.toml+++ b/crates/edit_prediction_button/Cargo.toml@@ -18,18 +18,19 @@ client.workspace = truecloud_llm_client.workspace = truecodestral.workspace = truecopilot.workspace = true+edit_prediction.workspace = trueeditor.workspace = truefeature_flags.workspace = truefs.workspace = truegpui.workspace = trueindoc.workspace = true-edit_prediction.workspace = truelanguage.workspace = truepaths.workspace = trueproject.workspace = trueregex.workspace = truesettings.workspace = truesupermaven.workspace = true+sweep_ai.workspace = truetelemetry.workspace = trueui.workspace = trueworkspace.workspace = truediff --git a/crates/edit_prediction_button/src/edit_prediction_button.rs b/crates/edit_prediction_button/src/edit_prediction_button.rsindex 685d4082058..51f228db76a 100644--- a/crates/edit_prediction_button/src/edit_prediction_button.rs+++ b/crates/edit_prediction_button/src/edit_prediction_button.rs@@ -18,12 +18,15 @@ use language::{};use project::DisableAiSettings;use regex::Regex;-use settings::{Settings, SettingsStore, update_settings_file};+use settings::{+ EXPERIMENTAL_SWEEP_EDIT_PREDICTION_PROVIDER_NAME, Settings, SettingsStore, update_settings_file,+};use std::{sync::{Arc, LazyLock},time::Duration,};use supermaven::{AccountStatus, Supermaven};+use sweep_ai::SweepFeatureFlag;use ui::{Clickable, ContextMenu, ContextMenuEntry, DocumentationEdge, DocumentationSide, IconButton,IconButtonShape, Indicator, PopoverMenu, PopoverMenuHandle, ProgressBar, Tooltip, prelude::*,@@ -78,7 +81,7 @@ impl Render for EditPredictionButton {let all_language_settings = all_language_settings(None, cx);- match all_language_settings.edit_predictions.provider {+ match &all_language_settings.edit_predictions.provider {EditPredictionProvider::None => div().hidden(),EditPredictionProvider::Copilot => {@@ -297,6 +300,15 @@ impl Render for EditPredictionButton {.with_handle(self.popover_menu_handle.clone()),)}+ EditPredictionProvider::Experimental(provider_name) => {+ if *provider_name == EXPERIMENTAL_SWEEP_EDIT_PREDICTION_PROVIDER_NAME+ && cx.has_flag::<SweepFeatureFlag>()+ {+ div().child(Icon::new(IconName::SweepAi))+ } else {+ div()+ }+ }EditPredictionProvider::Zed => {let enabled = self.editor_enabled.unwrap_or(true);@@ -525,7 +537,7 @@ impl EditPredictionButton {set_completion_provider(fs.clone(), cx, provider);})}- EditPredictionProvider::None => continue,+ EditPredictionProvider::None | EditPredictionProvider::Experimental(_) => continue,};}}diff --git a/crates/icons/src/icons.rs b/crates/icons/src/icons.rsindex a0865773ac3..da3b298751d 100644--- a/crates/icons/src/icons.rs+++ b/crates/icons/src/icons.rs@@ -217,6 +217,7 @@ pub enum IconName {SupermavenError,SupermavenInit,SwatchBook,+ SweepAi,Tab,Terminal,TerminalAlt,diff --git a/crates/reqwest_client/src/reqwest_client.rs b/crates/reqwest_client/src/reqwest_client.rsindex c2a58877b32..4213a239ec8 100644--- a/crates/reqwest_client/src/reqwest_client.rs+++ b/crates/reqwest_client/src/reqwest_client.rs@@ -80,20 +80,22 @@ impl ReqwestClient {}}+pub fn runtime() -> &'static tokio::runtime::Runtime {+ RUNTIME.get_or_init(|| {+ tokio::runtime::Builder::new_multi_thread()+ // Since we now have two executors, let's try to keep our footprint small+ .worker_threads(1)+ .enable_all()+ .build()+ .expect("Failed to initialize HTTP client")+ })+}+impl From<reqwest::Client> for ReqwestClient {fn from(client: reqwest::Client) -> Self {let handle = tokio::runtime::Handle::try_current().unwrap_or_else(|_| {log::debug!("no tokio runtime found, creating one for Reqwest...");- let runtime = RUNTIME.get_or_init(|| {- tokio::runtime::Builder::new_multi_thread()- // Since we now have two executors, let's try to keep our footprint small- .worker_threads(1)- .enable_all()- .build()- .expect("Failed to initialize HTTP client")- });-- runtime.handle().clone()+ runtime().handle().clone()});Self {client,diff --git a/crates/settings/src/settings_content/language.rs b/crates/settings/src/settings_content/language.rsindex fc11dd4956a..ed70116862b 100644--- a/crates/settings/src/settings_content/language.rs+++ b/crates/settings/src/settings_content/language.rs@@ -3,7 +3,7 @@ use std::num::NonZeroU32;use collections::{HashMap, HashSet};use gpui::{Modifiers, SharedString};use schemars::JsonSchema;-use serde::{Deserialize, Serialize};+use serde::{Deserialize, Serialize, de::Error as _};use serde_with::skip_serializing_none;use settings_macros::MergeFrom;use std::sync::Arc;@@ -68,9 +68,7 @@ pub struct FeaturesContent {}/// The provider that supplies edit predictions.-#[derive(- Copy, Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize, JsonSchema, MergeFrom,-)]+#[derive(Copy, Clone, Debug, Default, Eq, PartialEq, Serialize, JsonSchema, MergeFrom)]#[serde(rename_all = "snake_case")]pub enum EditPredictionProvider {None,@@ -79,6 +77,47 @@ pub enum EditPredictionProvider {Supermaven,Zed,Codestral,+ Experimental(&'static str),+}++pub const EXPERIMENTAL_SWEEP_EDIT_PREDICTION_PROVIDER_NAME: &str = "sweep";++impl<'de> Deserialize<'de> for EditPredictionProvider {+ fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>+ where+ D: serde::Deserializer<'de>,+ {+ #[derive(Deserialize)]+ #[serde(rename_all = "snake_case")]+ pub enum Content {+ None,+ Copilot,+ Supermaven,+ Zed,+ Codestral,+ Experimental(String),+ }++ Ok(match Content::deserialize(deserializer)? {+ Content::None => EditPredictionProvider::None,+ Content::Copilot => EditPredictionProvider::Copilot,+ Content::Supermaven => EditPredictionProvider::Supermaven,+ Content::Zed => EditPredictionProvider::Zed,+ Content::Codestral => EditPredictionProvider::Codestral,+ Content::Experimental(name) => {+ if name == EXPERIMENTAL_SWEEP_EDIT_PREDICTION_PROVIDER_NAME {+ EditPredictionProvider::Experimental(+ EXPERIMENTAL_SWEEP_EDIT_PREDICTION_PROVIDER_NAME,+ )+ } else {+ return Err(D::Error::custom(format!(+ "Unknown experimental edit prediction provider: {}",+ name+ )));+ }+ }+ })+ }}impl EditPredictionProvider {@@ -88,7 +127,8 @@ impl EditPredictionProvider {EditPredictionProvider::None| EditPredictionProvider::Copilot| EditPredictionProvider::Supermaven- | EditPredictionProvider::Codestral => false,+ | EditPredictionProvider::Codestral+ | EditPredictionProvider::Experimental(_) => false,}}}diff --git a/crates/sweep_ai/Cargo.toml b/crates/sweep_ai/Cargo.tomlnew file mode 100644index 00000000000..4edf7ea1bb6--- /dev/null+++ b/crates/sweep_ai/Cargo.toml@@ -0,0 +1,43 @@+[package]+name = "sweep_ai"+version = "0.1.0"+edition.workspace = true+publish.workspace = true+license = "GPL-3.0-or-later"+exclude = ["fixtures"]++[lints]+workspace = true++[lib]+path = "src/sweep_ai.rs"+doctest = false++[dependencies]+anyhow.workspace = true+arrayvec.workspace = true+brotli.workspace = true+client.workspace = true+collections.workspace = true+edit_prediction.workspace = true+feature_flags.workspace = true+futures.workspace = true+gpui.workspace = true+http_client.workspace = true+language.workspace = true+project.workspace = true+release_channel.workspace = true+serde.workspace = true+serde_json.workspace = true+util.workspace = true+workspace.workspace = true++[dev-dependencies]+gpui = { workspace = true, features = ["test-support"] }+http_client = { workspace = true, features = ["test-support"] }+indoc.workspace = true+language = { workspace = true, features = ["test-support"] }+reqwest_client = { workspace = true, features = ["test-support"] }+tree-sitter-rust.workspace = true+workspace = { workspace = true, features = ["test-support"] }+zlog.workspace = truediff --git a/crates/sweep_ai/LICENSE-GPL b/crates/sweep_ai/LICENSE-GPLnew file mode 120000index 00000000000..89e542f750c--- /dev/null+++ b/crates/sweep_ai/LICENSE-GPL@@ -0,0 +1 @@+../../LICENSE-GPL\ No newline at end of filediff --git a/crates/sweep_ai/src/api.rs b/crates/sweep_ai/src/api.rsnew file mode 100644index 00000000000..edb392885e4--- /dev/null+++ b/crates/sweep_ai/src/api.rs@@ -0,0 +1,90 @@+use std::{path::Path, sync::Arc};++use serde::{Deserialize, Serialize};++#[derive(Debug, Clone, Serialize)]+pub struct AutocompleteRequest {+ pub debug_info: Arc<str>,+ pub repo_name: String,+ pub branch: Option<String>,+ pub file_path: Arc<Path>,+ pub file_contents: String,+ pub recent_changes: String,+ pub cursor_position: usize,+ pub original_file_contents: String,+ pub file_chunks: Vec<FileChunk>,+ pub retrieval_chunks: Vec<RetrievalChunk>,+ pub recent_user_actions: Vec<UserAction>,+ pub multiple_suggestions: bool,+ pub privacy_mode_enabled: bool,+ pub changes_above_cursor: bool,+}++#[derive(Debug, Clone, Serialize)]+pub struct FileChunk {+ pub file_path: String,+ pub start_line: usize,+ pub end_line: usize,+ pub content: String,+ pub timestamp: Option<u64>,+}++#[derive(Debug, Clone, Serialize)]+pub struct RetrievalChunk {+ pub file_path: String,+ pub start_line: usize,+ pub end_line: usize,+ pub content: String,+ pub timestamp: u64,+}++#[derive(Debug, Clone, Serialize)]+pub struct UserAction {+ pub action_type: ActionType,+ pub line_number: usize,+ pub offset: usize,+ pub file_path: String,+ pub timestamp: u64,+}++#[allow(dead_code)]+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]+#[serde(rename_all = "SCREAMING_SNAKE_CASE")]+pub enum ActionType {+ CursorMovement,+ InsertChar,+ DeleteChar,+ InsertSelection,+ DeleteSelection,+}++#[derive(Debug, Clone, Deserialize)]+pub struct AutocompleteResponse {+ pub autocomplete_id: String,+ pub start_index: usize,+ pub end_index: usize,+ pub completion: String,+ #[allow(dead_code)]+ pub confidence: f64,+ #[allow(dead_code)]+ pub logprobs: Option<serde_json::Value>,+ #[allow(dead_code)]+ pub finish_reason: Option<String>,+ #[allow(dead_code)]+ pub elapsed_time_ms: u64,+ #[allow(dead_code)]+ #[serde(default, rename = "completions")]+ pub additional_completions: Vec<AdditionalCompletion>,+}++#[allow(dead_code)]+#[derive(Debug, Clone, Deserialize)]+pub struct AdditionalCompletion {+ pub start_index: usize,+ pub end_index: usize,+ pub completion: String,+ pub confidence: f64,+ pub autocomplete_id: String,+ pub logprobs: Option<serde_json::Value>,+ pub finish_reason: Option<String>,+}diff --git a/crates/sweep_ai/src/sweep_ai.rs b/crates/sweep_ai/src/sweep_ai.rsnew file mode 100644index 00000000000..e8a2522c0b3--- /dev/null+++ b/crates/sweep_ai/src/sweep_ai.rs@@ -0,0 +1,776 @@+mod api;++use anyhow::{Context as _, Result};+use arrayvec::ArrayVec;+use client::telemetry;+use collections::HashMap;+use feature_flags::FeatureFlag;+use futures::AsyncReadExt as _;+use gpui::{App, AppContext, Context, Entity, EntityId, Global, Task, WeakEntity};+use http_client::{AsyncBody, Method};+use language::{Anchor, Buffer, BufferSnapshot, EditPreview, ToOffset as _, ToPoint, text_diff};+use project::Project;+use release_channel::{AppCommitSha, AppVersion};+use std::collections::{VecDeque, hash_map};+use std::fmt::{self, Display};+use std::mem;+use std::{+ cmp,+ fmt::Write,+ ops::Range,+ path::Path,+ sync::Arc,+ time::{Duration, Instant},+};+use util::ResultExt;+use util::rel_path::RelPath;+use workspace::Workspace;++use crate::api::{AutocompleteRequest, AutocompleteResponse, FileChunk};++const BUFFER_CHANGE_GROUPING_INTERVAL: Duration = Duration::from_secs(1);+const MAX_EVENT_COUNT: usize = 16;++const SWEEP_API_URL: &str = "https://autocomplete.sweep.dev/backend/next_edit_autocomplete";++pub struct SweepFeatureFlag;++impl FeatureFlag for SweepFeatureFlag {+ const NAME: &str = "sweep-ai";++ fn enabled_for_staff() -> bool {+ false+ }+}++#[derive(Clone)]+struct SweepAiGlobal(Entity<SweepAi>);++impl Global for SweepAiGlobal {}++#[derive(Clone)]+pub struct EditPrediction {+ id: EditPredictionId,+ path: Arc<Path>,+ edits: Arc<[(Range<Anchor>, Arc<str>)]>,+ snapshot: BufferSnapshot,+ edit_preview: EditPreview,+}++impl EditPrediction {+ fn interpolate(&self, new_snapshot: &BufferSnapshot) -> Option<Vec<(Range<Anchor>, Arc<str>)>> {+ edit_prediction::interpolate_edits(&self.snapshot, new_snapshot, &self.edits)+ }+}++impl fmt::Debug for EditPrediction {+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {+ f.debug_struct("EditPrediction")+ .field("path", &self.path)+ .field("edits", &self.edits)+ .finish_non_exhaustive()+ }+}++#[derive(Clone, Default, Debug, PartialEq, Eq, Hash)]+pub struct EditPredictionId(String);++impl Display for EditPredictionId {+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {+ write!(f, "{}", self.0)+ }+}++pub struct SweepAi {+ projects: HashMap<EntityId, SweepAiProject>,+ debug_info: Arc<str>,+}++struct SweepAiProject {+ events: VecDeque<Event>,+ registered_buffers: HashMap<gpui::EntityId, RegisteredBuffer>,+}++impl SweepAi {+ pub fn global(cx: &mut App) -> Option<Entity<Self>> {+ cx.try_global::<SweepAiGlobal>()+ .map(|global| global.0.clone())+ }++ pub fn register(cx: &mut App) -> Entity<Self> {+ Self::global(cx).unwrap_or_else(|| {+ let entity = cx.new(|cx| Self::new(cx));+ cx.set_global(SweepAiGlobal(entity.clone()));+ entity+ })+ }++ pub fn clear_history(&mut self) {+ for sweep_ai_project in self.projects.values_mut() {+ sweep_ai_project.events.clear();+ }+ }++ fn new(cx: &mut Context<Self>) -> Self {+ Self {+ projects: HashMap::default(),+ debug_info: format!(+ "Zed v{version} ({sha}) - OS: {os} - Zed v{version}",+ version = AppVersion::global(cx),+ sha = AppCommitSha::try_global(cx).map_or("unknown".to_string(), |sha| sha.full()),+ os = telemetry::os_name(),+ )+ .into(),+ }+ }++ fn get_or_init_sweep_ai_project(+ &mut self,+ project: &Entity<Project>,+ cx: &mut Context<Self>,+ ) -> &mut SweepAiProject {+ let project_id = project.entity_id();+ match self.projects.entry(project_id) {+ hash_map::Entry::Occupied(entry) => entry.into_mut(),+ hash_map::Entry::Vacant(entry) => {+ cx.observe_release(project, move |this, _, _cx| {+ this.projects.remove(&project_id);+ })+ .detach();+ entry.insert(SweepAiProject {+ events: VecDeque::with_capacity(MAX_EVENT_COUNT),+ registered_buffers: HashMap::default(),+ })+ }+ }+ }++ fn push_event(sweep_ai_project: &mut SweepAiProject, event: Event) {+ let events = &mut sweep_ai_project.events;++ if let Some(Event::BufferChange {+ new_snapshot: last_new_snapshot,+ timestamp: last_timestamp,+ ..+ }) = events.back_mut()+ {+ // Coalesce edits for the same buffer when they happen one after the other.+ let Event::BufferChange {+ old_snapshot,+ new_snapshot,+ timestamp,+ } = &event;++ if timestamp.duration_since(*last_timestamp) <= BUFFER_CHANGE_GROUPING_INTERVAL+ && old_snapshot.remote_id() == last_new_snapshot.remote_id()+ && old_snapshot.version == last_new_snapshot.version+ {+ *last_new_snapshot = new_snapshot.clone();+ *last_timestamp = *timestamp;+ return;+ }+ }++ if events.len() >= MAX_EVENT_COUNT {+ // These are halved instead of popping to improve prompt caching.+ events.drain(..MAX_EVENT_COUNT / 2);+ }++ events.push_back(event);+ }++ pub fn register_buffer(+ &mut self,+ buffer: &Entity<Buffer>,+ project: &Entity<Project>,+ cx: &mut Context<Self>,+ ) {+ let sweep_ai_project = self.get_or_init_sweep_ai_project(project, cx);+ Self::register_buffer_impl(sweep_ai_project, buffer, project, cx);+ }++ fn register_buffer_impl<'a>(+ sweep_ai_project: &'a mut SweepAiProject,+ buffer: &Entity<Buffer>,+ project: &Entity<Project>,+ cx: &mut Context<Self>,+ ) -> &'a mut RegisteredBuffer {+ let buffer_id = buffer.entity_id();+ match sweep_ai_project.registered_buffers.entry(buffer_id) {+ hash_map::Entry::Occupied(entry) => entry.into_mut(),+ hash_map::Entry::Vacant(entry) => {+ let snapshot = buffer.read(cx).snapshot();+ let project_entity_id = project.entity_id();+ entry.insert(RegisteredBuffer {+ snapshot,+ _subscriptions: [+ cx.subscribe(buffer, {+ let project = project.downgrade();+ move |this, buffer, event, cx| {+ if let language::BufferEvent::Edited = event+ && let Some(project) = project.upgrade()+ {+ this.report_changes_for_buffer(&buffer, &project, cx);+ }+ }+ }),+ cx.observe_release(buffer, move |this, _buffer, _cx| {+ let Some(sweep_ai_project) = this.projects.get_mut(&project_entity_id)+ else {+ return;+ };+ sweep_ai_project.registered_buffers.remove(&buffer_id);+ }),+ ],+ })+ }+ }+ }++ pub fn request_completion(+ &mut self,+ workspace: &WeakEntity<Workspace>,+ project: &Entity<Project>,+ active_buffer: &Entity<Buffer>,+ position: language::Anchor,+ cx: &mut Context<Self>,+ ) -> Task<Result<Option<EditPrediction>>> {+ let snapshot = active_buffer.read(cx).snapshot();+ let debug_info = self.debug_info.clone();+ let full_path: Arc<Path> = snapshot+ .file()+ .map(|file| file.full_path(cx))+ .unwrap_or_else(|| "untitled".into())+ .into();++ let project_file = project::File::from_dyn(snapshot.file());+ let repo_name = project_file+ .map(|file| file.worktree.read(cx).root_name_str())+ .unwrap_or("untitled")+ .into();+ let offset = position.to_offset(&snapshot);++ let project_state = self.get_or_init_sweep_ai_project(project, cx);+ let events = project_state.events.clone();+ let http_client = cx.http_client();++ let Some(recent_buffers) = workspace+ .read_with(cx, |workspace, cx| {+ workspace+ .recent_navigation_history_iter(cx)+ .filter_map(|(project_path, _)| {+ let buffer = project.read(cx).get_open_buffer(&project_path, cx)?;++ if active_buffer == &buffer {+ None+ } else {+ Some(buffer.read(cx).snapshot())+ }+ })+ .take(3)+ .collect::<Vec<_>>()+ })+ .log_err()+ else {+ return Task::ready(Ok(None));+ };++ let result = cx.background_spawn({+ let full_path = full_path.clone();+ async move {+ let text = snapshot.text();++ let mut recent_changes = String::new();++ for event in events {+ writeln!(&mut recent_changes, "{event}")?;+ }++ let file_chunks = recent_buffers+ .into_iter()+ .map(|snapshot| {+ let end_point = language::Point::new(30, 0).min(snapshot.max_point());+ FileChunk {+ content: snapshot+ .text_for_range(language::Point::zero()..end_point)+ .collect(),+ file_path: snapshot+ .file()+ .map(|f| f.path().as_unix_str())+ .unwrap_or("untitled")+ .to_string(),+ start_line: 0,+ end_line: end_point.row as usize,+ timestamp: snapshot.file().and_then(|file| {+ Some(+ file.disk_state()+ .mtime()?+ .to_seconds_and_nanos_for_persistence()?+ .0,+ )+ }),+ }+ })+ .collect();++ let request_body = AutocompleteRequest {+ debug_info,+ repo_name,+ file_path: full_path.clone(),+ file_contents: text.clone(),+ original_file_contents: text,+ cursor_position: offset,+ recent_changes: recent_changes.clone(),+ changes_above_cursor: true,+ multiple_suggestions: false,+ branch: None,+ file_chunks,+ retrieval_chunks: vec![],+ recent_user_actions: vec![],+ // TODO+ privacy_mode_enabled: false,+ };++ let mut buf: Vec<u8> = Vec::new();+ let writer = brotli::CompressorWriter::new(&mut buf, 4096, 11, 22);+ serde_json::to_writer(writer, &request_body)?;+ let body: AsyncBody = buf.into();++ let request = http_client::Request::builder()+ .uri(SWEEP_API_URL)+ .header("Content-Type", "application/json")+ .header(+ "Authorization",+ format!("Bearer {}", std::env::var("SWEEP_TOKEN").unwrap()),+ )+ .header("Connection", "keep-alive")+ .header("Content-Encoding", "br")+ .method(Method::POST)+ .body(body)?;++ let mut response = http_client.send(request).await?;++ let mut body: Vec<u8> = Vec::new();+ response.body_mut().read_to_end(&mut body).await?;++ if !response.status().is_success() {+ anyhow::bail!(+ "Request failed with status: {:?}\nBody: {}",+ response.status(),+ String::from_utf8_lossy(&body),+ );+ };++ let response: AutocompleteResponse = serde_json::from_slice(&body)?;++ let old_text = snapshot+ .text_for_range(response.start_index..response.end_index)+ .collect::<String>();+ let edits = text_diff(&old_text, &response.completion)+ .into_iter()+ .map(|(range, text)| {+ (+ snapshot.anchor_after(response.start_index + range.start)+ ..snapshot.anchor_before(response.start_index + range.end),+ text,+ )+ })+ .collect::<Vec<_>>();++ anyhow::Ok((response.autocomplete_id, edits, snapshot))+ }+ });++ let buffer = active_buffer.clone();++ cx.spawn(async move |_, cx| {+ let (id, edits, old_snapshot) = result.await?;++ if edits.is_empty() {+ return anyhow::Ok(None);+ }++ let Some((edits, new_snapshot, preview_task)) =+ buffer.read_with(cx, |buffer, cx| {+ let new_snapshot = buffer.snapshot();++ let edits: Arc<[(Range<Anchor>, Arc<str>)]> =+ edit_prediction::interpolate_edits(&old_snapshot, &new_snapshot, &edits)?+ .into();+ let preview_task = buffer.preview_edits(edits.clone(), cx);++ Some((edits, new_snapshot, preview_task))+ })?+ else {+ return anyhow::Ok(None);+ };++ let prediction = EditPrediction {+ id: EditPredictionId(id),+ path: full_path,+ edits,+ snapshot: new_snapshot,+ edit_preview: preview_task.await,+ };++ anyhow::Ok(Some(prediction))+ })+ }++ fn report_changes_for_buffer(+ &mut self,+ buffer: &Entity<Buffer>,+ project: &Entity<Project>,+ cx: &mut Context<Self>,+ ) -> BufferSnapshot {+ let sweep_ai_project = self.get_or_init_sweep_ai_project(project, cx);+ let registered_buffer = Self::register_buffer_impl(sweep_ai_project, buffer, project, cx);++ let new_snapshot = buffer.read(cx).snapshot();+ if new_snapshot.version != registered_buffer.snapshot.version {+ let old_snapshot = mem::replace(&mut registered_buffer.snapshot, new_snapshot.clone());+ Self::push_event(+ sweep_ai_project,+ Event::BufferChange {+ old_snapshot,+ new_snapshot: new_snapshot.clone(),+ timestamp: Instant::now(),+ },+ );+ }++ new_snapshot+ }+}++struct RegisteredBuffer {+ snapshot: BufferSnapshot,+ _subscriptions: [gpui::Subscription; 2],+}++#[derive(Clone)]+pub enum Event {+ BufferChange {+ old_snapshot: BufferSnapshot,+ new_snapshot: BufferSnapshot,+ timestamp: Instant,+ },+}++impl Display for Event {+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {+ match self {+ Event::BufferChange {+ old_snapshot,+ new_snapshot,+ ..+ } => {+ let old_path = old_snapshot+ .file()+ .map(|f| f.path().as_ref())+ .unwrap_or(RelPath::unix("untitled").unwrap());+ let new_path = new_snapshot+ .file()+ .map(|f| f.path().as_ref())+ .unwrap_or(RelPath::unix("untitled").unwrap());+ if old_path != new_path {+ // TODO confirm how to do this for sweep+ // writeln!(f, "User renamed {:?} to {:?}\n", old_path, new_path)?;+ }++ let diff = language::unified_diff(&old_snapshot.text(), &new_snapshot.text());+ if !diff.is_empty() {+ write!(+ f,+ "File: {}:\n{}\n",+ new_path.display(util::paths::PathStyle::Posix),+ diff+ )?+ }++ fmt::Result::Ok(())+ }+ }+ }+}++#[derive(Debug, Clone)]+struct CurrentEditPrediction {+ buffer_id: EntityId,+ completion: EditPrediction,+}++impl CurrentEditPrediction {+ fn should_replace_completion(&self, old_completion: &Self, snapshot: &BufferSnapshot) -> bool {+ if self.buffer_id != old_completion.buffer_id {+ return true;+ }++ let Some(old_edits) = old_completion.completion.interpolate(snapshot) else {+ return true;+ };+ let Some(new_edits) = self.completion.interpolate(snapshot) else {+ return false;+ };++ if old_edits.len() == 1 && new_edits.len() == 1 {+ let (old_range, old_text) = &old_edits[0];+ let (new_range, new_text) = &new_edits[0];+ new_range == old_range && new_text.starts_with(old_text.as_ref())+ } else {+ true+ }+ }+}++struct PendingCompletion {+ id: usize,+ _task: Task<()>,+}++pub struct SweepAiEditPredictionProvider {+ workspace: WeakEntity<Workspace>,+ sweep_ai: Entity<SweepAi>,+ pending_completions: ArrayVec<PendingCompletion, 2>,+ next_pending_completion_id: usize,+ current_completion: Option<CurrentEditPrediction>,+ last_request_timestamp: Instant,+ project: Entity<Project>,+}++impl SweepAiEditPredictionProvider {+ pub const THROTTLE_TIMEOUT: Duration = Duration::from_millis(300);++ pub fn new(+ sweep_ai: Entity<SweepAi>,+ workspace: WeakEntity<Workspace>,+ project: Entity<Project>,+ ) -> Self {+ Self {+ sweep_ai,+ pending_completions: ArrayVec::new(),+ next_pending_completion_id: 0,+ current_completion: None,+ last_request_timestamp: Instant::now(),+ project,+ workspace,+ }+ }+}++impl edit_prediction::EditPredictionProvider for SweepAiEditPredictionProvider {+ fn name() -> &'static str {+ "zed-predict"+ }++ fn display_name() -> &'static str {+ "Zed's Edit Predictions"+ }++ fn show_completions_in_menu() -> bool {+ true+ }++ fn show_tab_accept_marker() -> bool {+ true+ }++ fn is_enabled(+ &self,+ _buffer: &Entity<Buffer>,+ _cursor_position: language::Anchor,+ _cx: &App,+ ) -> bool {+ true+ }++ fn is_refreshing(&self) -> bool {+ !self.pending_completions.is_empty()+ }++ fn refresh(+ &mut self,+ buffer: Entity<Buffer>,+ position: language::Anchor,+ _debounce: bool,+ cx: &mut Context<Self>,+ ) {+ if let Some(current_completion) = self.current_completion.as_ref() {+ let snapshot = buffer.read(cx).snapshot();+ if current_completion+ .completion+ .interpolate(&snapshot)+ .is_some()+ {+ return;+ }+ }++ let pending_completion_id = self.next_pending_completion_id;+ self.next_pending_completion_id += 1;+ let last_request_timestamp = self.last_request_timestamp;++ let project = self.project.clone();+ let workspace = self.workspace.clone();+ let task = cx.spawn(async move |this, cx| {+ if let Some(timeout) = (last_request_timestamp + Self::THROTTLE_TIMEOUT)+ .checked_duration_since(Instant::now())+ {+ cx.background_executor().timer(timeout).await;+ }++ let completion_request = this.update(cx, |this, cx| {+ this.last_request_timestamp = Instant::now();+ this.sweep_ai.update(cx, |sweep_ai, cx| {+ sweep_ai.request_completion(&workspace, &project, &buffer, position, cx)+ })+ });++ let completion = match completion_request {+ Ok(completion_request) => {+ let completion_request = completion_request.await;+ completion_request.map(|c| {+ c.map(|completion| CurrentEditPrediction {+ buffer_id: buffer.entity_id(),+ completion,+ })+ })+ }+ Err(error) => Err(error),+ };++ let Some(new_completion) = completion+ .context("edit prediction failed")+ .log_err()+ .flatten()+ else {+ this.update(cx, |this, cx| {+ if this.pending_completions[0].id == pending_completion_id {+ this.pending_completions.remove(0);+ } else {+ this.pending_completions.clear();+ }++ cx.notify();+ })+ .ok();+ return;+ };++ this.update(cx, |this, cx| {+ if this.pending_completions[0].id == pending_completion_id {+ this.pending_completions.remove(0);+ } else {+ this.pending_completions.clear();+ }++ if let Some(old_completion) = this.current_completion.as_ref() {+ let snapshot = buffer.read(cx).snapshot();+ if new_completion.should_replace_completion(old_completion, &snapshot) {+ this.current_completion = Some(new_completion);+ }+ } else {+ this.current_completion = Some(new_completion);+ }++ cx.notify();+ })+ .ok();+ });++ // We always maintain at most two pending completions. When we already+ // have two, we replace the newest one.+ if self.pending_completions.len() <= 1 {+ self.pending_completions.push(PendingCompletion {+ id: pending_completion_id,+ _task: task,+ });+ } else if self.pending_completions.len() == 2 {+ self.pending_completions.pop();+ self.pending_completions.push(PendingCompletion {+ id: pending_completion_id,+ _task: task,+ });+ }+ }++ fn cycle(+ &mut self,+ _buffer: Entity<Buffer>,+ _cursor_position: language::Anchor,+ _direction: edit_prediction::Direction,+ _cx: &mut Context<Self>,+ ) {+ // Right now we don't support cycling.+ }++ fn accept(&mut self, _cx: &mut Context<Self>) {+ self.pending_completions.clear();+ }++ fn discard(&mut self, _cx: &mut Context<Self>) {+ self.pending_completions.clear();+ self.current_completion.take();+ }++ fn suggest(+ &mut self,+ buffer: &Entity<Buffer>,+ cursor_position: language::Anchor,+ cx: &mut Context<Self>,+ ) -> Option<edit_prediction::EditPrediction> {+ let CurrentEditPrediction {+ buffer_id,+ completion,+ ..+ } = self.current_completion.as_mut()?;++ // Invalidate previous completion if it was generated for a different buffer.+ if *buffer_id != buffer.entity_id() {+ self.current_completion.take();+ return None;+ }++ let buffer = buffer.read(cx);+ let Some(edits) = completion.interpolate(&buffer.snapshot()) else {+ self.current_completion.take();+ return None;+ };++ let cursor_row = cursor_position.to_point(buffer).row;+ let (closest_edit_ix, (closest_edit_range, _)) =+ edits.iter().enumerate().min_by_key(|(_, (range, _))| {+ let distance_from_start = cursor_row.abs_diff(range.start.to_point(buffer).row);+ let distance_from_end = cursor_row.abs_diff(range.end.to_point(buffer).row);+ cmp::min(distance_from_start, distance_from_end)+ })?;++ let mut edit_start_ix = closest_edit_ix;+ for (range, _) in edits[..edit_start_ix].iter().rev() {+ let distance_from_closest_edit =+ closest_edit_range.start.to_point(buffer).row - range.end.to_point(buffer).row;+ if distance_from_closest_edit <= 1 {+ edit_start_ix -= 1;+ } else {+ break;+ }+ }++ let mut edit_end_ix = closest_edit_ix + 1;+ for (range, _) in &edits[edit_end_ix..] {+ let distance_from_closest_edit =+ range.start.to_point(buffer).row - closest_edit_range.end.to_point(buffer).row;+ if distance_from_closest_edit <= 1 {+ edit_end_ix += 1;+ } else {+ break;+ }+ }++ Some(edit_prediction::EditPrediction::Local {+ id: Some(completion.id.to_string().into()),+ edits: edits[edit_start_ix..edit_end_ix].to_vec(),+ edit_preview: Some(completion.edit_preview.clone()),+ })+ }+}diff --git a/crates/zed/Cargo.toml b/crates/zed/Cargo.tomlindex ca81955e33b..79892fefdd7 100644--- a/crates/zed/Cargo.toml+++ b/crates/zed/Cargo.toml@@ -133,6 +133,7 @@ snippet_provider.workspace = truesnippets_ui.workspace = truesupermaven.workspace = truesvg_preview.workspace = true+sweep_ai.workspace = truesysinfo.workspace = truetab_switcher.workspace = truetask.workspace = truediff --git a/crates/zed/src/zed/edit_prediction_registry.rs b/crates/zed/src/zed/edit_prediction_registry.rsindex 74b6687f62c..1723ca91f14 100644--- a/crates/zed/src/zed/edit_prediction_registry.rs+++ b/crates/zed/src/zed/edit_prediction_registry.rs@@ -7,9 +7,10 @@ use feature_flags::FeatureFlagAppExt;use gpui::{AnyWindowHandle, App, AppContext as _, Context, Entity, WeakEntity};use language::language_settings::{EditPredictionProvider, all_language_settings};use language_models::MistralLanguageModelProvider;-use settings::SettingsStore;+use settings::{EXPERIMENTAL_SWEEP_EDIT_PREDICTION_PROVIDER_NAME, SettingsStore};use std::{cell::RefCell, rc::Rc, sync::Arc};use supermaven::{Supermaven, SupermavenCompletionProvider};+use sweep_ai::{SweepAiEditPredictionProvider, SweepFeatureFlag};use ui::Window;use zeta::ZetaEditPredictionProvider;use zeta2::Zeta2FeatureFlag;@@ -202,6 +203,38 @@ fn assign_edit_prediction_provider(let provider = cx.new(|_| CodestralCompletionProvider::new(http_client));editor.set_edit_prediction_provider(Some(provider), window, cx);}+ EditPredictionProvider::Experimental(name) => {+ if name == EXPERIMENTAL_SWEEP_EDIT_PREDICTION_PROVIDER_NAME+ && cx.has_flag::<SweepFeatureFlag>()+ {+ if let Some(project) = editor.project()+ && let Some(workspace) = editor.workspace()+ {+ let sweep_ai = sweep_ai::SweepAi::register(cx);++ if let Some(buffer) = &singleton_buffer+ && buffer.read(cx).file().is_some()+ {+ sweep_ai.update(cx, |sweep_ai, cx| {+ sweep_ai.register_buffer(buffer, project, cx);+ });+ }++ let provider = cx.new(|_| {+ sweep_ai::SweepAiEditPredictionProvider::new(+ sweep_ai,+ workspace.downgrade(),+ project.clone(),+ )+ });+ editor.set_edit_prediction_provider(Some(provider), window, cx);+ }+ } else {+ editor.set_edit_prediction_provider::<SweepAiEditPredictionProvider>(+ None, window, cx,+ );+ }+ }EditPredictionProvider::Zed => {if user_store.read(cx).current_user().is_some() {let mut worktree = None;