1050 lines · 35.8 KB · Rust
RawDownload
use crate::{Keep, KeepAll, Reject, RejectAll, Thread, ThreadEvent};use anyhow::Result;use buffer_diff::DiffHunkStatus;use collections::HashSet;use editor::{    Direction, Editor, EditorEvent, MultiBuffer, ToPoint,    actions::{GoToHunk, GoToPreviousHunk},    scroll::Autoscroll,};use gpui::{    Action, AnyElement, AnyView, App, Entity, EventEmitter, FocusHandle, Focusable, SharedString,    Subscription, Task, WeakEntity, Window, prelude::*,};use language::{Capability, DiskState, OffsetRangeExt, Point};use multi_buffer::PathKey;use project::{Project, ProjectPath};use std::{    any::{Any, TypeId},    ops::Range,    sync::Arc,};use ui::{IconButtonShape, KeyBinding, Tooltip, prelude::*};use workspace::{    Item, ItemHandle, ItemNavHistory, ToolbarItemEvent, ToolbarItemLocation, ToolbarItemView,    Workspace,    item::{BreadcrumbText, ItemEvent, TabContentParams},    searchable::SearchableItemHandle,};use zed_actions::assistant::ToggleFocus; pub struct AgentDiff {    multibuffer: Entity<MultiBuffer>,    editor: Entity<Editor>,    thread: Entity<Thread>,    focus_handle: FocusHandle,    workspace: WeakEntity<Workspace>,    title: SharedString,    _subscriptions: Vec<Subscription>,} impl AgentDiff {    pub fn deploy(        thread: Entity<Thread>,        workspace: WeakEntity<Workspace>,        window: &mut Window,        cx: &mut App,    ) -> Result<Entity<Self>> {        workspace.update(cx, |workspace, cx| {            Self::deploy_in_workspace(thread, workspace, window, cx)        })    }     pub fn deploy_in_workspace(        thread: Entity<Thread>,        workspace: &mut Workspace,        window: &mut Window,        cx: &mut Context<Workspace>,    ) -> Entity<Self> {        let existing_diff = workspace            .items_of_type::<AgentDiff>(cx)            .find(|diff| diff.read(cx).thread == thread);        if let Some(existing_diff) = existing_diff {            workspace.activate_item(&existing_diff, true, true, window, cx);            existing_diff        } else {            let agent_diff =                cx.new(|cx| AgentDiff::new(thread.clone(), workspace.weak_handle(), window, cx));            workspace.add_item_to_center(Box::new(agent_diff.clone()), window, cx);            agent_diff        }    }     pub fn new(        thread: Entity<Thread>,        workspace: WeakEntity<Workspace>,        window: &mut Window,        cx: &mut Context<Self>,    ) -> Self {        let focus_handle = cx.focus_handle();        let multibuffer = cx.new(|_| MultiBuffer::new(Capability::ReadWrite));         let project = thread.read(cx).project().clone();        let render_diff_hunk_controls = Arc::new({            let agent_diff = cx.entity();            move |row,                  status: &DiffHunkStatus,                  hunk_range,                  is_created_file,                  line_height,                  editor: &Entity<Editor>,                  window: &mut Window,                  cx: &mut App| {                render_diff_hunk_controls(                    row,                    status,                    hunk_range,                    is_created_file,                    line_height,                    &agent_diff,                    editor,                    window,                    cx,                )            }        });        let editor = cx.new(|cx| {            let mut editor =                Editor::for_multibuffer(multibuffer.clone(), Some(project.clone()), window, cx);            editor.disable_inline_diagnostics();            editor.set_expand_all_diff_hunks(cx);            editor.set_render_diff_hunk_controls(render_diff_hunk_controls, cx);            editor.register_addon(AgentDiffAddon);            editor        });         let action_log = thread.read(cx).action_log().clone();        let mut this = Self {            _subscriptions: vec![                cx.observe_in(&action_log, window, |this, _action_log, window, cx| {                    this.update_excerpts(window, cx)                }),                cx.subscribe(&thread, |this, _thread, event, cx| {                    this.handle_thread_event(event, cx)                }),            ],            title: SharedString::default(),            multibuffer,            editor,            thread,            focus_handle,            workspace,        };        this.update_excerpts(window, cx);        this.update_title(cx);        this    }     fn update_excerpts(&mut self, window: &mut Window, cx: &mut Context<Self>) {        let thread = self.thread.read(cx);        let changed_buffers = thread.action_log().read(cx).changed_buffers(cx);        let mut paths_to_delete = self.multibuffer.read(cx).paths().collect::<HashSet<_>>();         for (buffer, diff_handle) in changed_buffers {            if buffer.read(cx).file().is_none() {                continue;            }             let path_key = PathKey::for_buffer(&buffer, cx);            paths_to_delete.remove(&path_key);             let snapshot = buffer.read(cx).snapshot();            let diff = diff_handle.read(cx);             let diff_hunk_ranges = diff                .hunks_intersecting_range(                    language::Anchor::MIN..language::Anchor::MAX,                    &snapshot,                    cx,                )                .map(|diff_hunk| diff_hunk.buffer_range.to_point(&snapshot))                .collect::<Vec<_>>();             let (was_empty, is_excerpt_newly_added) =                self.multibuffer.update(cx, |multibuffer, cx| {                    let was_empty = multibuffer.is_empty();                    let (_, is_excerpt_newly_added) = multibuffer.set_excerpts_for_path(                        path_key.clone(),                        buffer.clone(),                        diff_hunk_ranges,                        editor::DEFAULT_MULTIBUFFER_CONTEXT,                        cx,                    );                    multibuffer.add_diff(diff_handle, cx);                    (was_empty, is_excerpt_newly_added)                });             self.editor.update(cx, |editor, cx| {                if was_empty {                    let first_hunk = editor                        .diff_hunks_in_ranges(                            &[editor::Anchor::min()..editor::Anchor::max()],                            &self.multibuffer.read(cx).read(cx),                        )                        .next();                     if let Some(first_hunk) = first_hunk {                        let first_hunk_start = first_hunk.multi_buffer_range().start;                        editor.change_selections(                            Some(Autoscroll::fit()),                            window,                            cx,                            |selections| {                                selections                                    .select_anchor_ranges([first_hunk_start..first_hunk_start]);                            },                        )                    }                }                 if is_excerpt_newly_added                    && buffer                        .read(cx)                        .file()                        .map_or(false, |file| file.disk_state() == DiskState::Deleted)                {                    editor.fold_buffer(snapshot.text.remote_id(), cx)                }            });        }         self.multibuffer.update(cx, |multibuffer, cx| {            for path in paths_to_delete {                multibuffer.remove_excerpts_for_path(path, cx);            }        });         if self.multibuffer.read(cx).is_empty()            && self                .editor                .read(cx)                .focus_handle(cx)                .contains_focused(window, cx)        {            self.focus_handle.focus(window);        } else if self.focus_handle.is_focused(window) && !self.multibuffer.read(cx).is_empty() {            self.editor.update(cx, |editor, cx| {                editor.focus_handle(cx).focus(window);            });        }    }     fn update_title(&mut self, cx: &mut Context<Self>) {        let new_title = self            .thread            .read(cx)            .summary()            .unwrap_or("Assistant Changes".into());        if new_title != self.title {            self.title = new_title;            cx.emit(EditorEvent::TitleChanged);        }    }     fn handle_thread_event(&mut self, event: &ThreadEvent, cx: &mut Context<Self>) {        match event {            ThreadEvent::SummaryGenerated => self.update_title(cx),            _ => {}        }    }     pub fn move_to_path(&mut self, path_key: PathKey, window: &mut Window, cx: &mut Context<Self>) {        if let Some(position) = self.multibuffer.read(cx).location_for_path(&path_key, cx) {            self.editor.update(cx, |editor, cx| {                let first_hunk = editor                    .diff_hunks_in_ranges(                        &[position..editor::Anchor::max()],                        &self.multibuffer.read(cx).read(cx),                    )                    .next();                 if let Some(first_hunk) = first_hunk {                    let first_hunk_start = first_hunk.multi_buffer_range().start;                    editor.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {                        selections.select_anchor_ranges([first_hunk_start..first_hunk_start]);                    })                }            });        }    }     fn keep(&mut self, _: &crate::Keep, window: &mut Window, cx: &mut Context<Self>) {        let ranges = self            .editor            .read(cx)            .selections            .disjoint_anchor_ranges()            .collect::<Vec<_>>();        self.keep_edits_in_ranges(ranges, window, cx);    }     fn reject(&mut self, _: &crate::Reject, window: &mut Window, cx: &mut Context<Self>) {        let ranges = self            .editor            .read(cx)            .selections            .disjoint_anchor_ranges()            .collect::<Vec<_>>();        self.reject_edits_in_ranges(ranges, window, cx);    }     fn reject_all(&mut self, _: &crate::RejectAll, window: &mut Window, cx: &mut Context<Self>) {        self.reject_edits_in_ranges(            vec![editor::Anchor::min()..editor::Anchor::max()],            window,            cx,        );    }     fn keep_all(&mut self, _: &crate::KeepAll, _window: &mut Window, cx: &mut Context<Self>) {        self.thread            .update(cx, |thread, cx| thread.keep_all_edits(cx));    }     fn keep_edits_in_ranges(        &mut self,        ranges: Vec<Range<editor::Anchor>>,        window: &mut Window,        cx: &mut Context<Self>,    ) {        let snapshot = self.multibuffer.read(cx).snapshot(cx);        let diff_hunks_in_ranges = self            .editor            .read(cx)            .diff_hunks_in_ranges(&ranges, &snapshot)            .collect::<Vec<_>>();        let newest_cursor = self.editor.update(cx, |editor, cx| {            editor.selections.newest::<Point>(cx).head()        });        if diff_hunks_in_ranges.iter().any(|hunk| {            hunk.row_range                .contains(&multi_buffer::MultiBufferRow(newest_cursor.row))        }) {            self.update_selection(&diff_hunks_in_ranges, window, cx);        }         for hunk in &diff_hunks_in_ranges {            let buffer = self.multibuffer.read(cx).buffer(hunk.buffer_id);            if let Some(buffer) = buffer {                self.thread.update(cx, |thread, cx| {                    thread.keep_edits_in_range(buffer, hunk.buffer_range.clone(), cx)                });            }        }    }     fn reject_edits_in_ranges(        &mut self,        ranges: Vec<Range<editor::Anchor>>,        window: &mut Window,        cx: &mut Context<Self>,    ) {        let snapshot = self.multibuffer.read(cx).snapshot(cx);        let diff_hunks_in_ranges = self            .editor            .read(cx)            .diff_hunks_in_ranges(&ranges, &snapshot)            .collect::<Vec<_>>();        let newest_cursor = self.editor.update(cx, |editor, cx| {            editor.selections.newest::<Point>(cx).head()        });        if diff_hunks_in_ranges.iter().any(|hunk| {            hunk.row_range                .contains(&multi_buffer::MultiBufferRow(newest_cursor.row))        }) {            self.update_selection(&diff_hunks_in_ranges, window, cx);        }         for hunk in &diff_hunks_in_ranges {            let buffer = self.multibuffer.read(cx).buffer(hunk.buffer_id);            if let Some(buffer) = buffer {                self.thread                    .update(cx, |thread, cx| {                        thread.reject_edits_in_range(buffer, hunk.buffer_range.clone(), cx)                    })                    .detach_and_log_err(cx);            }        }    }     fn update_selection(        &mut self,        diff_hunks: &[multi_buffer::MultiBufferDiffHunk],        window: &mut Window,        cx: &mut Context<Self>,    ) {        let snapshot = self.multibuffer.read(cx).snapshot(cx);        let target_hunk = diff_hunks            .last()            .and_then(|last_kept_hunk| {                let last_kept_hunk_end = last_kept_hunk.multi_buffer_range().end;                self.editor                    .read(cx)                    .diff_hunks_in_ranges(&[last_kept_hunk_end..editor::Anchor::max()], &snapshot)                    .skip(1)                    .next()            })            .or_else(|| {                let first_kept_hunk = diff_hunks.first()?;                let first_kept_hunk_start = first_kept_hunk.multi_buffer_range().start;                self.editor                    .read(cx)                    .diff_hunks_in_ranges(                        &[editor::Anchor::min()..first_kept_hunk_start],                        &snapshot,                    )                    .next()            });         if let Some(target_hunk) = target_hunk {            self.editor.update(cx, |editor, cx| {                editor.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {                    let next_hunk_start = target_hunk.multi_buffer_range().start;                    selections.select_anchor_ranges([next_hunk_start..next_hunk_start]);                })            });        }    }} impl EventEmitter<EditorEvent> for AgentDiff {} impl Focusable for AgentDiff {    fn focus_handle(&self, cx: &App) -> FocusHandle {        if self.multibuffer.read(cx).is_empty() {            self.focus_handle.clone()        } else {            self.editor.focus_handle(cx)        }    }} impl Item for AgentDiff {    type Event = EditorEvent;     fn tab_icon(&self, _window: &Window, _cx: &App) -> Option<Icon> {        Some(Icon::new(IconName::ZedAssistant).color(Color::Muted))    }     fn to_item_events(event: &EditorEvent, f: impl FnMut(ItemEvent)) {        Editor::to_item_events(event, f)    }     fn deactivated(&mut self, window: &mut Window, cx: &mut Context<Self>) {        self.editor            .update(cx, |editor, cx| editor.deactivated(window, cx));    }     fn navigate(        &mut self,        data: Box<dyn Any>,        window: &mut Window,        cx: &mut Context<Self>,    ) -> bool {        self.editor            .update(cx, |editor, cx| editor.navigate(data, window, cx))    }     fn tab_tooltip_text(&self, _: &App) -> Option<SharedString> {        Some("Agent Diff".into())    }     fn tab_content(&self, params: TabContentParams, _window: &Window, cx: &App) -> AnyElement {        let summary = self            .thread            .read(cx)            .summary()            .unwrap_or("Assistant Changes".into());        Label::new(format!("Review: {}", summary))            .color(if params.selected {                Color::Default            } else {                Color::Muted            })            .into_any_element()    }     fn telemetry_event_text(&self) -> Option<&'static str> {        Some("Assistant Diff Opened")    }     fn as_searchable(&self, _: &Entity<Self>) -> Option<Box<dyn SearchableItemHandle>> {        Some(Box::new(self.editor.clone()))    }     fn for_each_project_item(        &self,        cx: &App,        f: &mut dyn FnMut(gpui::EntityId, &dyn project::ProjectItem),    ) {        self.editor.for_each_project_item(cx, f)    }     fn is_singleton(&self, _: &App) -> bool {        false    }     fn set_nav_history(        &mut self,        nav_history: ItemNavHistory,        _: &mut Window,        cx: &mut Context<Self>,    ) {        self.editor.update(cx, |editor, _| {            editor.set_nav_history(Some(nav_history));        });    }     fn clone_on_split(        &self,        _workspace_id: Option<workspace::WorkspaceId>,

Lines 1–500 of 1050.