3375 lines · 127.1 KB · Rust
RawDownload
use crate::{    assistant_settings::AssistantSettings, humanize_token_count, prompts::PromptBuilder,    AssistantPanel, AssistantPanelEvent, CharOperation, LineDiff, LineOperation, ModelSelector,    StreamingDiff,};use anyhow::{anyhow, Context as _, Result};use client::{telemetry::Telemetry, ErrorExt};use collections::{hash_map, HashMap, HashSet, VecDeque};use editor::{    actions::{MoveDown, MoveUp, SelectAll},    display_map::{        BlockContext, BlockDisposition, BlockProperties, BlockStyle, CustomBlockId, RenderBlock,        ToDisplayPoint,    },    Anchor, AnchorRangeExt, Editor, EditorElement, EditorEvent, EditorMode, EditorStyle,    ExcerptRange, GutterDimensions, MultiBuffer, MultiBufferSnapshot, ToOffset, ToPoint,};use feature_flags::{FeatureFlagAppExt as _, ZedPro};use fs::Fs;use futures::{    channel::mpsc,    future::{BoxFuture, LocalBoxFuture},    join,    stream::{self, BoxStream},    SinkExt, Stream, StreamExt,};use gpui::{    anchored, deferred, point, AppContext, ClickEvent, EventEmitter, FocusHandle, FocusableView,    FontWeight, Global, HighlightStyle, Model, ModelContext, Subscription, Task, TextStyle,    UpdateGlobal, View, ViewContext, WeakView, WindowContext,};use language::{Buffer, IndentKind, Point, Selection, TransactionId};use language_model::{    LanguageModelRegistry, LanguageModelRequest, LanguageModelRequestMessage, Role,};use multi_buffer::MultiBufferRow;use parking_lot::Mutex;use rope::Rope;use settings::{Settings, SettingsStore};use smol::future::FutureExt;use std::{    cmp,    future::{self, Future},    mem,    ops::{Range, RangeInclusive},    pin::Pin,    sync::Arc,    task::{self, Poll},    time::{Duration, Instant},};use terminal_view::terminal_panel::TerminalPanel;use theme::ThemeSettings;use ui::{prelude::*, CheckboxWithLabel, IconButtonShape, Popover, Tooltip};use util::{RangeExt, ResultExt};use workspace::{notifications::NotificationId, Toast, Workspace}; pub fn init(    fs: Arc<dyn Fs>,    prompt_builder: Arc<PromptBuilder>,    telemetry: Arc<Telemetry>,    cx: &mut AppContext,) {    cx.set_global(InlineAssistant::new(fs, prompt_builder, telemetry));    cx.observe_new_views(|_, cx| {        let workspace = cx.view().clone();        InlineAssistant::update_global(cx, |inline_assistant, cx| {            inline_assistant.register_workspace(&workspace, cx)        })    })    .detach();} const PROMPT_HISTORY_MAX_LEN: usize = 20; pub struct InlineAssistant {    next_assist_id: InlineAssistId,    next_assist_group_id: InlineAssistGroupId,    assists: HashMap<InlineAssistId, InlineAssist>,    assists_by_editor: HashMap<WeakView<Editor>, EditorInlineAssists>,    assist_groups: HashMap<InlineAssistGroupId, InlineAssistGroup>,    assist_observations: HashMap<        InlineAssistId,        (            async_watch::Sender<AssistStatus>,            async_watch::Receiver<AssistStatus>,        ),    >,    confirmed_assists: HashMap<InlineAssistId, Model<Codegen>>,    prompt_history: VecDeque<String>,    prompt_builder: Arc<PromptBuilder>,    telemetry: Option<Arc<Telemetry>>,    fs: Arc<dyn Fs>,} pub enum AssistStatus {    Idle,    Started,    Stopped,    Finished,} impl AssistStatus {    pub fn is_done(&self) -> bool {        matches!(self, Self::Stopped | Self::Finished)    }} impl Global for InlineAssistant {} impl InlineAssistant {    pub fn new(        fs: Arc<dyn Fs>,        prompt_builder: Arc<PromptBuilder>,        telemetry: Arc<Telemetry>,    ) -> Self {        Self {            next_assist_id: InlineAssistId::default(),            next_assist_group_id: InlineAssistGroupId::default(),            assists: HashMap::default(),            assists_by_editor: HashMap::default(),            assist_groups: HashMap::default(),            assist_observations: HashMap::default(),            confirmed_assists: HashMap::default(),            prompt_history: VecDeque::default(),            prompt_builder,            telemetry: Some(telemetry),            fs,        }    }     pub fn register_workspace(&mut self, workspace: &View<Workspace>, cx: &mut WindowContext) {        cx.subscribe(workspace, |_, event, cx| {            Self::update_global(cx, |this, cx| this.handle_workspace_event(event, cx));        })        .detach();         let workspace = workspace.downgrade();        cx.observe_global::<SettingsStore>(move |cx| {            let Some(workspace) = workspace.upgrade() else {                return;            };            let Some(terminal_panel) = workspace.read(cx).panel::<TerminalPanel>(cx) else {                return;            };            let enabled = AssistantSettings::get_global(cx).enabled;            terminal_panel.update(cx, |terminal_panel, cx| {                terminal_panel.asssistant_enabled(enabled, cx)            });        })        .detach();    }     fn handle_workspace_event(&mut self, event: &workspace::Event, cx: &mut WindowContext) {        // When the user manually saves an editor, automatically accepts all finished transformations.        if let workspace::Event::UserSavedItem { item, .. } = event {            if let Some(editor) = item.upgrade().and_then(|item| item.act_as::<Editor>(cx)) {                if let Some(editor_assists) = self.assists_by_editor.get(&editor.downgrade()) {                    for assist_id in editor_assists.assist_ids.clone() {                        let assist = &self.assists[&assist_id];                        if let CodegenStatus::Done = &assist.codegen.read(cx).status {                            self.finish_assist(assist_id, false, cx)                        }                    }                }            }        }    }     pub fn assist(        &mut self,        editor: &View<Editor>,        workspace: Option<WeakView<Workspace>>,        assistant_panel: Option<&View<AssistantPanel>>,        initial_prompt: Option<String>,        cx: &mut WindowContext,    ) {        let snapshot = editor.read(cx).buffer().read(cx).snapshot(cx);         let mut selections = Vec::<Selection<Point>>::new();        let mut newest_selection = None;        for mut selection in editor.read(cx).selections.all::<Point>(cx) {            if selection.end > selection.start {                selection.start.column = 0;                // If the selection ends at the start of the line, we don't want to include it.                if selection.end.column == 0 {                    selection.end.row -= 1;                }                selection.end.column = snapshot.line_len(MultiBufferRow(selection.end.row));            }             if let Some(prev_selection) = selections.last_mut() {                if selection.start <= prev_selection.end {                    prev_selection.end = selection.end;                    continue;                }            }             let latest_selection = newest_selection.get_or_insert_with(|| selection.clone());            if selection.id > latest_selection.id {                *latest_selection = selection.clone();            }            selections.push(selection);        }        let newest_selection = newest_selection.unwrap();         let mut codegen_ranges = Vec::new();        for (excerpt_id, buffer, buffer_range) in            snapshot.excerpts_in_ranges(selections.iter().map(|selection| {                snapshot.anchor_before(selection.start)..snapshot.anchor_after(selection.end)            }))        {            let start = Anchor {                buffer_id: Some(buffer.remote_id()),                excerpt_id,                text_anchor: buffer.anchor_before(buffer_range.start),            };            let end = Anchor {                buffer_id: Some(buffer.remote_id()),                excerpt_id,                text_anchor: buffer.anchor_after(buffer_range.end),            };            codegen_ranges.push(start..end);        }         let assist_group_id = self.next_assist_group_id.post_inc();        let prompt_buffer =            cx.new_model(|cx| Buffer::local(initial_prompt.unwrap_or_default(), cx));        let prompt_buffer = cx.new_model(|cx| MultiBuffer::singleton(prompt_buffer, cx));         let mut assists = Vec::new();        let mut assist_to_focus = None;        for range in codegen_ranges {            let assist_id = self.next_assist_id.post_inc();            let codegen = cx.new_model(|cx| {                Codegen::new(                    editor.read(cx).buffer().clone(),                    range.clone(),                    None,                    self.telemetry.clone(),                    self.prompt_builder.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,                )            });             if assist_to_focus.is_none() {                let focus_assist = if newest_selection.reversed {                    range.start.to_point(&snapshot) == newest_selection.start                } else {                    range.end.to_point(&snapshot) == newest_selection.end                };                if focus_assist {                    assist_to_focus = Some(assist_id);                }            }             let [prompt_block_id, end_block_id] =                self.insert_assist_blocks(editor, &range, &prompt_editor, cx);             assists.push((                assist_id,                range,                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, range, prompt_editor, prompt_block_id, end_block_id) in assists {            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,                    range,                    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);         if let Some(assist_id) = assist_to_focus {            self.focus_assist(assist_id, cx);        }    }     #[allow(clippy::too_many_arguments)]    pub fn suggest_assist(        &mut self,        editor: &View<Editor>,        mut range: Range<Anchor>,        initial_prompt: String,        initial_transaction_id: Option<TransactionId>,        workspace: Option<WeakView<Workspace>>,        assistant_panel: Option<&View<AssistantPanel>>,        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 snapshot = buffer.read(cx).read(cx);            range.start = range.start.bias_left(&snapshot);            range.end = range.end.bias_right(&snapshot);        }         let codegen = cx.new_model(|cx| {            Codegen::new(                editor.read(cx).buffer().clone(),                range.clone(),                initial_transaction_id,                self.telemetry.clone(),                self.prompt_builder.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,                range,                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<Editor>,        range: &Range<Anchor>,        prompt_editor: &View<PromptEditor>,        cx: &mut WindowContext,    ) -> [CustomBlockId; 2] {        let prompt_editor_height = prompt_editor.update(cx, |prompt_editor, cx| {            prompt_editor                .editor                .update(cx, |editor, cx| editor.max_point(cx).row().0 + 1 + 2)        });        let assist_blocks = vec![            BlockProperties {                style: BlockStyle::Sticky,                position: range.start,                height: prompt_editor_height,                render: build_assist_editor_renderer(prompt_editor),                disposition: BlockDisposition::Above,                priority: 0,            },            BlockProperties {                style: BlockStyle::Sticky,                position: range.end,                height: 0,                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,                priority: 0,            },        ];         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 {            return;        };        let assist_group = self.assist_groups.get_mut(&assist.group_id).unwrap();        let editor_assists = self.assists_by_editor.get_mut(&assist.editor).unwrap();         assist_group.active_assist_id = Some(assist_id);        if assist_group.linked {            for assist_id in &assist_group.assist_ids {                if let Some(decorations) = self.assists[assist_id].decorations.as_ref() {                    decorations.prompt_editor.update(cx, |prompt_editor, cx| {                        prompt_editor.set_show_cursor_when_unfocused(true, cx)                    });                }            }        }         assist            .editor            .update(cx, |editor, cx| {                let scroll_top = editor.scroll_position(cx).y;                let scroll_bottom = scroll_top + editor.visible_line_count().unwrap_or(0.);                let prompt_row = editor                    .row_for_block(decorations.prompt_block_id, cx)                    .unwrap()                    .0 as f32;                 if (scroll_top..scroll_bottom).contains(&prompt_row) {                    editor_assists.scroll_lock = Some(InlineAssistScrollLock {                        assist_id,                        distance_from_top: prompt_row - scroll_top,                    });                } else {                    editor_assists.scroll_lock = None;                }            })            .ok();    }     fn handle_prompt_editor_focus_out(        &mut self,        assist_id: InlineAssistId,        cx: &mut WindowContext,    ) {        let assist = &self.assists[&assist_id];        let assist_group = self.assist_groups.get_mut(&assist.group_id).unwrap();        if assist_group.active_assist_id == Some(assist_id) {            assist_group.active_assist_id = None;            if assist_group.linked {                for assist_id in &assist_group.assist_ids {                    if let Some(decorations) = self.assists[assist_id].decorations.as_ref() {                        decorations.prompt_editor.update(cx, |prompt_editor, cx| {                            prompt_editor.set_show_cursor_when_unfocused(false, cx)                        });                    }                }            }

Lines 1–500 of 3375.