1use 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#[derive(Clone, Debug, PartialEq, Eq)]
36pub enum ChangesEvent {
37 Changed(usize),
39 Applied {
41 file: PathBuf,
43 accepted: usize,
45 rejected: usize,
47 },
48}
49
50struct 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
63struct Proposal {
65 file: usize,
66 old: String,
68 new: String,
69 view: Entity<DiffView>,
70}
71
72pub 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 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 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 pub fn changed_lines(&self) -> usize {
172 self.files.iter().map(|f| f.diff.added() + f.diff.removed()).sum()
173 }
174
175 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 pub fn baseline(&self) -> Baseline {
182 self.baseline
183 }
184
185 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 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 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 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 pub fn proposal(&self) -> Option<Entity<DiffView>> {
250 self.proposal.as_ref().map(|p| p.view.clone())
251 }
252
253 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 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}