Skip to main content

kitchen_shell/
changes.rs

1//! The Changes panel: the files that say what a project is and how its analysis was done
2//! (`session.json`, `pipeline.json`, `project.json`), watched, and what changed in them shown as
3//! git-style diffs (kitchen-ui's `DiffView`): added lines green, removed red, compared by key
4//! (reordered keys are not changes) with long arrays as one summary line (`cells: 2,539 →
5//! 2,712`).
6//!
7//! - **Compared against** ([`Baseline`]): the last save (the default; the app calls
8//!   [`ChangesPanel::mark_saved`] when it saves), the start of the agent session ("everything
9//!   this session did", [`ChangesPanel::start_session`]), or the last git commit when the
10//!   project folder is a repository.
11//! - **Review**: an agent's proposed change ([`ChangesPanel::propose`]) shows as a diff with
12//!   Accept / Reject per hunk; [`ChangesPanel::apply_proposal`] writes the accepted hunks.
13//! - **Badge**: [`ChangesPanel::changed_lines`] counts the changed lines (the app shows it on the
14//!   panel's icon); [`ChangesEvent`] tells it when the count moves.
15
16use std::path::PathBuf;
17use std::time::SystemTime;
18
19use gpui_kit::assets::IconName;
20use gpui_kit::component::button::{Button, ButtonVariants as _};
21use gpui_kit::component::{Disableable as _, Sizable as _, h_flex, v_flex};
22use gpui_kit::prelude::FluentBuilder as _;
23use gpui_kit::{
24    AppContext as _, Context, Entity, EventEmitter, FontWeight, InteractiveElement as _, IntoElement,
25    ParentElement as _, Render, SharedString, StatefulInteractiveElement as _, Styled as _, Window, div, px,
26};
27use kitchen_ui::diff::{ARRAY_SUMMARY, CONTEXT, Diff};
28use kitchen_ui::theme::{self, color};
29use kitchen_ui::widgets::{DiffView, EmptyState, MenuSelect};
30
31pub use kitchen_services::changes::{Baseline, git_head};
32use kitchen_services::changes::{is_json, normalise, read};
33
34/// What the panel tells its owner.
35#[derive(Clone, Debug, PartialEq, Eq)]
36pub enum ChangesEvent {
37    /// The count of changed lines moved (the badge).
38    Changed(usize),
39    /// A proposal was applied to `file` (its accepted hunks written).
40    Applied {
41        /// The file written.
42        file: PathBuf,
43        /// Hunks accepted.
44        accepted: usize,
45        /// Hunks rejected.
46        rejected: usize,
47    },
48}
49
50/// One watched file.
51struct Watched {
52    path: PathBuf,
53    name: SharedString,
54    current: String,
55    modified: Option<SystemTime>,
56    saved: String,
57    session: String,
58    head: Option<String>,
59    diff: Diff,
60    view: Entity<DiffView>,
61}
62
63/// An agent's proposed change to a file, under review.
64struct Proposal {
65    file: usize,
66    /// The file's text and the proposal, both normalised (pretty JSON, sorted keys) when JSON.
67    old: String,
68    new: String,
69    view: Entity<DiffView>,
70}
71
72/// The Changes panel.
73pub struct ChangesPanel {
74    files: Vec<Watched>,
75    baseline: Baseline,
76    proposal: Option<Proposal>,
77    message: Option<(bool, String)>,
78    last_count: usize,
79}
80
81impl EventEmitter<ChangesEvent> for ChangesPanel {}
82
83impl ChangesPanel {
84    /// Watches `files` (each read now: that is the last save and the session's start until the
85    /// app says otherwise), checking them for changes every second.
86    pub fn new(files: Vec<PathBuf>, cx: &mut Context<Self>) -> Self {
87        let files = files
88            .into_iter()
89            .enumerate()
90            .map(|(i, path)| {
91                let (current, modified) = read(&path);
92                let name: SharedString =
93                    path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default().into();
94                let view = cx.new(|_| {
95                    DiffView::new(SharedString::from(format!("changes-{i}")), Diff::default()).title(name.clone())
96                });
97                Watched {
98                    saved: current.clone(),
99                    session: current.clone(),
100                    head: None,
101                    diff: Diff::default(),
102                    current,
103                    modified,
104                    path,
105                    name,
106                    view,
107                }
108            })
109            .collect();
110        let mut panel = Self { files, baseline: Baseline::LastSave, proposal: None, message: None, last_count: 0 };
111        panel.recompute(cx);
112        cx.spawn(async move |this, cx| {
113            loop {
114                cx.background_executor().timer(std::time::Duration::from_secs(1)).await;
115                if this.update(cx, |p, cx| p.refresh(cx)).is_err() {
116                    break;
117                }
118            }
119        })
120        .detach();
121        panel
122    }
123
124    /// Reads again the files that changed on disk.
125    pub fn refresh(&mut self, cx: &mut Context<Self>) {
126        let mut any = false;
127        for f in &mut self.files {
128            let (text, modified) = read(&f.path);
129            if modified != f.modified || text != f.current {
130                f.current = text;
131                f.modified = modified;
132                any = true;
133            }
134        }
135        if any {
136            self.recompute(cx);
137        }
138    }
139
140    fn base<'a>(&self, f: &'a Watched) -> &'a str {
141        match self.baseline {
142            Baseline::LastSave => &f.saved,
143            Baseline::SessionStart => &f.session,
144            Baseline::GitHead => f.head.as_deref().unwrap_or(""),
145        }
146    }
147
148    fn recompute(&mut self, cx: &mut Context<Self>) {
149        for i in 0..self.files.len() {
150            let f = &self.files[i];
151            let base = self.base(f).to_string();
152            let diff = if is_json(&f.path) {
153                Diff::json(&base, &f.current, CONTEXT, ARRAY_SUMMARY)
154            } else {
155                Diff::text(&base, &f.current, CONTEXT)
156            };
157            if diff != self.files[i].diff {
158                self.files[i].view.update(cx, |v, cx| v.set_diff(diff.clone(), cx));
159                self.files[i].diff = diff;
160            }
161        }
162        let count = self.changed_lines();
163        if count != self.last_count {
164            self.last_count = count;
165            cx.emit(ChangesEvent::Changed(count));
166        }
167        cx.notify();
168    }
169
170    /// Changed lines over every watched file (added and removed): the badge.
171    pub fn changed_lines(&self) -> usize {
172        self.files.iter().map(|f| f.diff.added() + f.diff.removed()).sum()
173    }
174
175    /// The diff of the watched file `name` against the baseline.
176    pub fn diff_of(&self, name: &str) -> Option<&Diff> {
177        self.files.iter().find(|f| f.name == name).map(|f| &f.diff)
178    }
179
180    /// What the files are compared against.
181    pub fn baseline(&self) -> Baseline {
182        self.baseline
183    }
184
185    /// Compares against `baseline`; the last commit is refused, with the reason, when no watched
186    /// file is in a git repository.
187    pub fn set_baseline(&mut self, baseline: Baseline, cx: &mut Context<Self>) -> Result<(), String> {
188        if baseline == Baseline::GitHead {
189            for f in &mut self.files {
190                f.head = git_head(&f.path);
191            }
192            if self.files.iter().all(|f| f.head.is_none()) {
193                let e = "The project folder is not a git repository (or its files are not committed)".to_string();
194                self.message = Some((true, e.clone()));
195                cx.notify();
196                return Err(e);
197            }
198        }
199        self.baseline = baseline;
200        self.message = None;
201        self.recompute(cx);
202        Ok(())
203    }
204
205    /// The files as they are now are the last save (the app calls this when it saves).
206    pub fn mark_saved(&mut self, cx: &mut Context<Self>) {
207        self.refresh(cx);
208        for f in &mut self.files {
209            f.saved = f.current.clone();
210        }
211        self.recompute(cx);
212    }
213
214    /// The files as they are now are the session's start (an agent session begins).
215    pub fn start_session(&mut self, cx: &mut Context<Self>) {
216        self.refresh(cx);
217        for f in &mut self.files {
218            f.session = f.current.clone();
219        }
220        self.recompute(cx);
221    }
222
223    /// Shows `new_text` proposed for the watched file `name` as a diff with Accept / Reject per
224    /// hunk. JSON is compared as pretty JSON with sorted keys, so the accepted hunks make a valid
225    /// file.
226    pub fn propose(&mut self, name: &str, new_text: &str, cx: &mut Context<Self>) -> Result<usize, String> {
227        self.refresh(cx);
228        let file = self.files.iter().position(|f| f.name == name).ok_or_else(|| format!("{name} is not watched"))?;
229        let f = &self.files[file];
230        let json = is_json(&f.path);
231        if json {
232            serde_json::from_str::<serde_json::Value>(new_text)
233                .map_err(|e| format!("the proposed {name} is not JSON: {e}"))?;
234        }
235        let (old, new) = (normalise(&f.current, json), normalise(new_text, json));
236        let diff = Diff::text(&old, &new, CONTEXT);
237        let hunks = diff.hunks.len();
238        let view = cx.new(|_| {
239            DiffView::new("proposal", diff).title(SharedString::from(format!("Proposed: {name}"))).reviewable(true)
240        });
241        cx.observe(&view, |_, _, cx| cx.notify()).detach();
242        self.proposal = Some(Proposal { file, old, new, view });
243        self.message = None;
244        cx.notify();
245        Ok(hunks)
246    }
247
248    /// The proposal's diff view, while one is under review.
249    pub fn proposal(&self) -> Option<Entity<DiffView>> {
250        self.proposal.as_ref().map(|p| p.view.clone())
251    }
252
253    /// Writes the proposal's accepted hunks to its file (undecided hunks count as rejected) and
254    /// closes it; returns how many were accepted.
255    pub fn apply_proposal(&mut self, cx: &mut Context<Self>) -> Result<usize, String> {
256        let p = self.proposal.take().ok_or("no proposal under review")?;
257        let decisions: Vec<bool> = p.view.read(cx).decisions().iter().map(|d| d.unwrap_or(false)).collect();
258        let accepted = decisions.iter().filter(|d| **d).count();
259        let path = self.files[p.file].path.clone();
260        let diff = Diff::text(&p.old, &p.new, CONTEXT);
261        let text = diff.apply(&decisions).ok_or("the proposal cannot be applied")?;
262        if accepted > 0 {
263            std::fs::write(&path, &text).map_err(|e| format!("{}: {e}", path.display()))?;
264        }
265        let rejected = decisions.len() - accepted;
266        self.message =
267            Some((false, format!("{}: {accepted} change(s) applied, {rejected} rejected", self.files[p.file].name)));
268        cx.emit(ChangesEvent::Applied { file: path, accepted, rejected });
269        self.refresh(cx);
270        cx.notify();
271        Ok(accepted)
272    }
273
274    /// Drops the proposal without writing anything.
275    pub fn discard_proposal(&mut self, cx: &mut Context<Self>) {
276        if let Some(p) = self.proposal.take() {
277            self.message = Some((false, format!("Proposal to {} discarded", self.files[p.file].name)));
278        }
279        cx.notify();
280    }
281}
282
283impl Render for ChangesPanel {
284    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
285        let count = self.changed_lines();
286        let me = cx.entity().downgrade();
287        let baseline = MenuSelect::new(
288            "changes-baseline",
289            Baseline::ALL.iter().map(|b| SharedString::from(b.title())).collect(),
290            Baseline::ALL.iter().position(|b| *b == self.baseline),
291            move |i, _, cx| {
292                let _ = me.update(cx, |p, cx| {
293                    let _ = p.set_baseline(Baseline::ALL[i], cx);
294                });
295            },
296        );
297        let badge = div()
298            .px(px(theme::SM))
299            .rounded(px(theme::RADIUS_SM))
300            .bg(if count > 0 { color::accent() } else { color::control() })
301            .text_color(if count > 0 { color::on_accent() } else { color::text_muted() })
302            .text_xs()
303            .font_weight(FontWeight::SEMIBOLD)
304            .child(count.to_string());
305        let header = h_flex()
306            .flex_none()
307            .gap(px(theme::SM))
308            .items_center()
309            .flex_wrap()
310            .child(div().text_base().font_weight(FontWeight::SEMIBOLD).child("Changes"))
311            .child(badge)
312            .child(div().flex_1())
313            .child(div().w(px(220.)).child(baseline));
314        let proposal = self.proposal.as_ref().map(|p| {
315            let decided = p.view.read(cx).decisions().iter().filter(|d| d.is_some()).count();
316            let total = p.view.read(cx).decisions().len();
317            v_flex()
318                .gap(px(theme::SM))
319                .p(px(theme::MD))
320                .rounded(px(theme::RADIUS_LG))
321                .border_1()
322                .border_color(color::accent_mark())
323                .child(
324                    div()
325                        .text_sm()
326                        .font_weight(FontWeight::SEMIBOLD)
327                        .child(format!("An agent proposes a change to {}", self.files[p.file].name)),
328                )
329                .child(
330                    div()
331                        .text_xs()
332                        .text_color(color::text_muted())
333                        .child(format!("{decided} of {total} hunks decided; undecided hunks are not applied.")),
334                )
335                .child(p.view.clone())
336                .child(
337                    h_flex()
338                        .gap(px(theme::SM))
339                        .child(
340                            Button::new("proposal-apply")
341                                .small()
342                                .primary()
343                                .icon(IconName::Check)
344                                .label("Apply accepted")
345                                .disabled(decided == 0)
346                                .on_click(cx.listener(|p, _, _, cx| {
347                                    if let Err(e) = p.apply_proposal(cx) {
348                                        p.message = Some((true, e));
349                                    }
350                                })),
351                        )
352                        .child(
353                            Button::new("proposal-discard")
354                                .small()
355                                .outline()
356                                .label("Discard")
357                                .on_click(cx.listener(|p, _, _, cx| p.discard_proposal(cx))),
358                        ),
359                )
360        });
361        let changed: Vec<_> = self.files.iter().filter(|f| !f.diff.is_empty()).map(|f| f.view.clone()).collect();
362        let unchanged: Vec<SharedString> =
363            self.files.iter().filter(|f| f.diff.is_empty()).map(|f| f.name.clone()).collect();
364        let body = if changed.is_empty() && self.proposal.is_none() {
365            div()
366                .h(px(220.))
367                .child(EmptyState::new(
368                    IconName::GitCompare,
369                    "No changes",
370                    format!("{} match {}.", unchanged.join(", "), self.baseline.title().to_lowercase()),
371                ))
372                .into_any_element()
373        } else {
374            v_flex()
375                .gap(px(theme::MD))
376                .children(changed)
377                .when(!unchanged.is_empty(), |d| {
378                    d.child(
379                        div()
380                            .text_xs()
381                            .text_color(color::text_muted())
382                            .child(format!("Unchanged: {}", unchanged.join(", "))),
383                    )
384                })
385                .into_any_element()
386        };
387        v_flex()
388            .id("changes")
389            .size_full()
390            .overflow_y_scroll()
391            .p(px(theme::LG))
392            .gap(px(theme::MD))
393            .child(header)
394            .children(self.message.clone().map(|(err, m)| {
395                div().text_sm().text_color(if err { color::danger() } else { color::text_muted() }).child(m)
396            }))
397            .children(proposal)
398            .child(body)
399    }
400}