BlueGit

ict rusty-teams

Files

rusty-teams / crates / app / src / views / composer / rewrite.rs

rewrite.rs

chore: cargo fmt the workspace
metis Daniel Däschle · pushed by metis · 2 weeks ago
a6592765 History
rewrite.rs 19.0 KiB Download Raw
1use gpui_kit::component::fluent::{
2 MENU_ITEM_GAP, MENU_ITEM_HEIGHT, MENU_ITEM_PADDING_X, MENU_LIST_PADDING,
3};
4use gpui_kit::component::input::{Input, InputContent, InputEvent, InputState};
5use gpui_kit::component::tooltip::PopupTriggerTooltip as _;
6use gpui_kit::component::{h_flex, v_flex};
7use gpui_kit::prelude::FluentBuilder as _;
8use gpui_kit::*;
9use teams_core::{ComposeAction, ComposeAdjustment, Draft, OBJECT_MARK, TABLE_MARK, html_to_spans};
10
11use super::{COMPOSER_BUTTON_SIZE, COMPOSER_ICON_SIZE, Composer};
12use crate::runtime;
13use crate::theme::{self, ElevatedSurface as _};
14use crate::views::widgets::symbol;
15use app_ui_kit::spinner::spinner;
16
17pub const REWRITE_BUTTON_TAG: &str = "composer/actions/copilot";
18pub const REWRITE_PANEL_TAG: &str = "composer/copilot";
19const BUTTON_LABEL: &str = "Write with Copilot";
20const CLOSE_LABEL: &str = "Close";
21const ADJUST_LABEL: &str = "Adjust";
22const CUSTOM_LABEL: &str = "Customised";
23const CUSTOM_PLACEHOLDER: &str = "Describe how to adjust it, e.g. make it sound friendlier";
24const REPLACE_LABEL: &str = "Replace";
25const DISCLAIMER: &str = "AI-generated content may be incorrect";
26const WORKING: &str = "Copilot is writing ...";
27const FAILED: &str = "Copilot could not rewrite this:";
28const EMPTY_DRAFT: &str = "Type a message first, then let Copilot rewrite it.";
29const TEXT_ONLY: &str =
30 "Copilot rewrites text only. Move images and tables out of the message first.";
31const BUTTON_ICON: &str = "auto_fix_high";
32const PANEL_WIDTH: f32 = 600.;
33const PANEL_PADDING: f32 = 16.;
34const PANEL_RADIUS: f32 = 10.;
35const CARD_RADIUS: f32 = 8.;
36const CHIP_HEIGHT: f32 = 32.;
37const CHIP_ICON: f32 = 16.;
38const ADJUST_MENU_WIDTH: f32 = 200.;
39const BUTTON_MIN_COMPOSER_WIDTH: f32 = 320.;
40const DEMO_DELAY: std::time::Duration = std::time::Duration::from_millis(700);
41
42#[derive(Default)]
43pub(super) struct RewritePanel {
44 open: bool,
45 adjust_menu: bool,
46 result: Option<RewriteResult>,
47 generation: u64,
48 custom_input: Option<Entity<InputState>>,
49 custom_open: bool,
50 _custom_events: Option<Subscription>,
51}
52
53impl RewritePanel {
54 pub(super) fn input_focused(&self, window: &Window, cx: &App) -> bool {
55 self.custom_input
56 .as_ref()
57 .is_some_and(|input| input.read(cx).focus_handle(cx).is_focused(window))
58 }
59}
60
61struct RewriteResult {
62 action: ComposeAction,
63 answer: RewriteAnswer,
64}
65
66enum RewriteAnswer {
67 Waiting,
68 Ready(Draft),
69 Failed(String),
70}
71
72#[derive(Clone, Copy, PartialEq, Eq)]
73enum Choice {
74 Rewrite,
75 Proofread,
76}
77
78impl Composer {
79 fn rewrite_available(&self, cx: &App) -> bool {
80 let state = self.app.read(cx);
81 self.editing.is_none()
82 && (state.mode.demo || state.engine.is_some())
83 && self
84 .conversation_id
85 .as_deref()
86 .is_some_and(|conversation_id| {
87 state
88 .sidebar
89 .chats
90 .iter()
91 .any(|chat| chat.id == conversation_id)
92 })
93 }
94
95 pub(super) fn render_rewrite_button(&self, cx: &mut Context<Self>) -> Option<Stateful<Div>> {
96 let fits = self
97 .composer_bounds
98 .get()
99 .is_none_or(|bounds| f32::from(bounds.size.width) >= BUTTON_MIN_COMPOSER_WIDTH);
100 if !fits || !self.rewrite_available(cx) {
101 return None;
102 }
103 let open = self.rewrite.open;
104 Some(
105 div()
106 .id("composer-copilot")
107 .debug_selector(|| REWRITE_BUTTON_TAG.into())
108 .size(px(COMPOSER_BUTTON_SIZE))
109 .flex_none()
110 .flex()
111 .items_center()
112 .justify_center()
113 .rounded(px(8.))
114 .cursor_pointer()
115 .when(open, |button| button.bg(theme::popup_hover()))
116 .hover(|button| button.bg(theme::popup_hover()))
117 .popup_trigger_tooltip_text(open, BUTTON_LABEL)
118 .child(symbol(
119 BUTTON_ICON,
120 COMPOSER_ICON_SIZE,
121 if open {
122 theme::accent_text()
123 } else {
124 theme::text_muted()
125 },
126 ))
127 .on_mouse_down(MouseButton::Left, |_, window, cx| {
128 window.prevent_default();
129 cx.stop_propagation();
130 })
131 .on_click(cx.listener(|this, _, _, cx| {
132 this.rewrite.open = !this.rewrite.open;
133 this.rewrite.adjust_menu = false;
134 cx.notify();
135 })),
136 )
137 }
138
139 pub(super) fn close_rewrite(&mut self) -> bool {
140 let was_open = self.rewrite.open;
141 self.rewrite.open = false;
142 self.rewrite.adjust_menu = false;
143 self.rewrite.custom_open = false;
144 self.rewrite.result = None;
145 self.rewrite.generation += 1;
146 was_open
147 }
148
149 fn request_rewrite(&mut self, action: ComposeAction, cx: &mut Context<Self>) {
150 self.rewrite.adjust_menu = false;
151 self.rewrite.generation += 1;
152 let generation = self.rewrite.generation;
153 let draft = self.current_draft(cx);
154 let demo = self.app.read(cx).mode.demo;
155 let engine = self.app.read(cx).engine.clone();
156 let Some(chat_id) = self.conversation_id.clone() else {
157 return;
158 };
159 let refusal = if draft.is_blank() {
160 Some(EMPTY_DRAFT)
161 } else if draft.text().contains([OBJECT_MARK, TABLE_MARK]) {
162 Some(TEXT_ONLY)
163 } else {
164 None
165 };
166 if let Some(refusal) = refusal {
167 self.rewrite.result = Some(RewriteResult {
168 action,
169 answer: RewriteAnswer::Failed(refusal.to_owned()),
170 });
171 cx.notify();
172 return;
173 }
174 self.rewrite.result = Some(RewriteResult {
175 action: action.clone(),
176 answer: RewriteAnswer::Waiting,
177 });
178 cx.notify();
179 let user_html = draft.to_html();
180 let receiver = (!demo).then_some(engine).flatten().map(|engine| {
181 runtime::spawn(async move { engine.rewrite_draft(&chat_id, &user_html, action).await })
182 });
183 let demo_answer = demo_rewrite(&draft.plain_text());
184 cx.spawn(async move |this, cx| {
185 let answer = match receiver {
186 None => {
187 cx.background_executor().timer(DEMO_DELAY).await;
188 RewriteAnswer::Ready(Draft::from_markdown(&demo_answer))
189 }
190 Some(receiver) => match receiver.await {
191 Ok(Ok(html)) => {
192 RewriteAnswer::Ready(Draft::from_spans(&html_to_spans(&html)).trimmed())
193 }
194 Ok(Err(error)) => RewriteAnswer::Failed(format!("{FAILED} {error}")),
195 Err(error) => RewriteAnswer::Failed(format!("{FAILED} {error}")),
196 },
197 };
198 this.update(cx, |this, cx| {
199 if this.rewrite.generation == generation
200 && let Some(result) = this.rewrite.result.as_mut()
201 {
202 result.answer = answer;
203 cx.notify();
204 }
205 })
206 .ok();
207 })
208 .detach();
209 }
210
211 fn replace_with_rewrite(&mut self, window: &mut Window, cx: &mut Context<Self>) {
212 let Some(RewriteAnswer::Ready(draft)) =
213 self.rewrite.result.as_ref().map(|result| &result.answer)
214 else {
215 return;
216 };
217 let draft = draft.clone();
218 self.close_rewrite();
219 self.load_draft(
220 draft.clone(),
221 InputContent::new(draft.text().to_owned()),
222 window,
223 cx,
224 );
225 self.mention_inputs.clear();
226 self.schedule_draft_save(cx);
227 self.focus(window, cx);
228 cx.notify();
229 }
230
231 fn open_custom(&mut self, window: &mut Window, cx: &mut Context<Self>) {
232 self.rewrite.adjust_menu = false;
233 self.rewrite.custom_open = true;
234 if self.rewrite.custom_input.is_none() {
235 let input = cx.new(|cx| InputState::new(window, cx).placeholder(CUSTOM_PLACEHOLDER));
236 let subscription = cx.subscribe_in(
237 &input,
238 window,
239 |this, input, event: &InputEvent, window, cx| {
240 if matches!(event, InputEvent::PressEnter { .. }) {
241 let prompt = input.read(cx).value().trim().to_owned();
242 if !prompt.is_empty() {
243 input.update(cx, |input, cx| input.set_value("", window, cx));
244 this.rewrite.custom_open = false;
245 this.request_rewrite(ComposeAction::Custom(prompt), cx);
246 }
247 }
248 },
249 );
250 self.rewrite.custom_input = Some(input);
251 self.rewrite._custom_events = Some(subscription);
252 }
253 if let Some(input) = &self.rewrite.custom_input {
254 input.update(cx, |input, cx| input.focus(window, cx));
255 }
256 cx.notify();
257 }
258
259 pub(super) fn render_rewrite_panel(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
260 if !self.rewrite.open || !self.rewrite_available(cx) {
261 return None;
262 }
263 let busy = matches!(
264 self.rewrite.result.as_ref().map(|result| &result.answer),
265 Some(RewriteAnswer::Waiting)
266 );
267 let chips = h_flex()
268 .w_full()
269 .gap(px(8.))
270 .items_center()
271 .child(self.choice_chip(Choice::Rewrite, busy, cx))
272 .child(self.choice_chip(Choice::Proofread, busy, cx))
273 .child(
274 div()
275 .relative()
276 .child(self.adjust_chip(busy, cx))
277 .children(self.render_adjust_menu(cx)),
278 )
279 .child(div().flex_1())
280 .child(
281 div()
282 .id("composer-copilot-close")
283 .size(px(CHIP_HEIGHT))
284 .flex()
285 .items_center()
286 .justify_center()
287 .rounded(px(6.))
288 .cursor_pointer()
289 .hover(|button| button.bg(theme::popup_hover()))
290 .popup_trigger_tooltip_text(false, CLOSE_LABEL)
291 .child(symbol("close", CHIP_ICON, theme::text_soft()))
292 .on_click(cx.listener(|this, _, _, cx| {
293 this.close_rewrite();
294 cx.notify();
295 })),
296 );
297 let custom = self
298 .rewrite
299 .custom_open
300 .then(|| self.rewrite.custom_input.clone())
301 .flatten()
302 .map(|input| {
303 div()
304 .w_full()
305 .px(px(12.))
306 .py(px(8.))
307 .rounded(px(CARD_RADIUS))
308 .bg(theme::surface_raised())
309 .child(Input::new(&input).appearance(false).bordered(false))
310 });
311 Some(
312 v_flex()
313 .id(REWRITE_PANEL_TAG)
314 .debug_selector(|| REWRITE_PANEL_TAG.into())
315 .absolute()
316 .bottom(relative(1.))
317 .right_0()
318 .mb(px(6.))
319 .w(px(PANEL_WIDTH))
320 .max_w(relative(1.))
321 .p(px(PANEL_PADDING))
322 .gap(px(12.))
323 .rounded(px(PANEL_RADIUS))
324 .flyout_surface()
325 .occlude()
326 .child(chips)
327 .children(custom)
328 .children(self.render_rewrite_result(cx))
329 .into_any_element(),
330 )
331 }
332
333 fn chip(
334 id: &'static str,
335 icon: &'static str,
336 label: &'static str,
337 busy: bool,
338 ) -> Stateful<Div> {
339 h_flex()
340 .id(id)
341 .h(px(CHIP_HEIGHT))
342 .px(px(12.))
343 .gap(px(6.))
344 .items_center()
345 .rounded(px(6.))
346 .bg(theme::surface_raised())
347 .text_size(px(13.))
348 .font_weight(FontWeight::SEMIBOLD)
349 .text_color(theme::text())
350 .child(symbol(icon, CHIP_ICON, theme::text_soft()))
351 .child(label)
352 .when(busy, |chip| chip.opacity(0.5))
353 .when(!busy, |chip| {
354 chip.cursor_pointer()
355 .hover(|chip| chip.bg(theme::popup_hover()))
356 })
357 }
358
359 fn choice_chip(&self, choice: Choice, busy: bool, cx: &mut Context<Self>) -> Stateful<Div> {
360 let (id, icon, action) = match choice {
361 Choice::Rewrite => (
362 "composer-copilot-rewrite",
363 BUTTON_ICON,
364 ComposeAction::Rewrite,
365 ),
366 Choice::Proofread => (
367 "composer-copilot-proofread",
368 "spellcheck",
369 ComposeAction::Proofread,
370 ),
371 };
372 let label = match choice {
373 Choice::Rewrite => "Rewrite",
374 Choice::Proofread => "Proofread",
375 };
376 Self::chip(id, icon, label, busy).when(!busy, |chip| {
377 chip.on_click(
378 cx.listener(move |this, _, _, cx| this.request_rewrite(action.clone(), cx)),
379 )
380 })
381 }
382
383 fn adjust_chip(&self, busy: bool, cx: &mut Context<Self>) -> Stateful<Div> {
384 Self::chip("composer-copilot-adjust", "more_horiz", ADJUST_LABEL, busy)
385 .child(symbol("keyboard_arrow_down", CHIP_ICON, theme::text_soft()))
386 .when(!busy, |chip| {
387 chip.on_click(cx.listener(|this, _, _, cx| {
388 this.rewrite.adjust_menu = !this.rewrite.adjust_menu;
389 cx.notify();
390 }))
391 })
392 }
393
394 fn render_adjust_menu(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
395 if !self.rewrite.adjust_menu {
396 return None;
397 }
398 let item = |id: &'static str, label: &'static str| {
399 div()
400 .id(id)
401 .w_full()
402 .h(MENU_ITEM_HEIGHT)
403 .px(MENU_ITEM_PADDING_X)
404 .flex()
405 .items_center()
406 .rounded(px(6.))
407 .cursor_pointer()
408 .hover(|row| row.bg(theme::popup_hover()))
409 .text_size(px(13.))
410 .text_color(theme::text())
411 .child(label)
412 };
413 let custom = item("composer-copilot-custom", CUSTOM_LABEL)
414 .on_click(cx.listener(|this, _, window, cx| this.open_custom(window, cx)));
415 let adjustments = ComposeAdjustment::ALL.into_iter().map(|adjustment| {
416 item(adjustment.label(), adjustment.label()).on_click(cx.listener(
417 move |this, _, _, cx| this.request_rewrite(ComposeAction::Adjust(adjustment), cx),
418 ))
419 });
420 Some(
421 v_flex()
422 .id("composer-copilot-adjust-menu")
423 .absolute()
424 .bottom(relative(1.))
425 .left_0()
426 .mb(px(4.))
427 .w(px(ADJUST_MENU_WIDTH))
428 .p(MENU_LIST_PADDING)
429 .gap(MENU_ITEM_GAP)
430 .rounded(px(10.))
431 .flyout_surface()
432 .occlude()
433 .on_mouse_down_out(cx.listener(|this, _, _, cx| {
434 this.rewrite.adjust_menu = false;
435 cx.notify();
436 }))
437 .child(custom)
438 .children(adjustments)
439 .into_any_element(),
440 )
441 }
442
443 fn render_rewrite_result(&self, cx: &mut Context<Self>) -> Option<Div> {
444 let result = self.rewrite.result.as_ref()?;
445 let card = v_flex()
446 .w_full()
447 .p(px(PANEL_PADDING))
448 .gap(px(12.))
449 .rounded(px(CARD_RADIUS))
450 .bg(theme::surface_raised())
451 .child(
452 div()
453 .text_size(px(12.))
454 .text_color(theme::text_soft())
455 .child(result.action.label().to_owned()),
456 );
457 Some(match &result.answer {
458 RewriteAnswer::Waiting => card.child(
459 h_flex()
460 .gap(px(8.))
461 .items_center()
462 .child(spinner(16.))
463 .child(
464 div()
465 .text_size(px(14.))
466 .text_color(theme::text_soft())
467 .child(WORKING),
468 ),
469 ),
470 RewriteAnswer::Failed(reason) => card.child(
471 div()
472 .text_size(px(14.))
473 .text_color(theme::text_soft())
474 .child(reason.clone()),
475 ),
476 RewriteAnswer::Ready(draft) => card
477 .child(
478 div()
479 .text_size(px(14.))
480 .text_color(theme::text())
481 .child(draft.plain_text()),
482 )
483 .child(
484 h_flex()
485 .w_full()
486 .items_center()
487 .justify_between()
488 .child(
489 div()
490 .id("composer-copilot-replace")
491 .h(px(CHIP_HEIGHT))
492 .px(px(24.))
493 .flex()
494 .items_center()
495 .rounded(px(6.))
496 .bg(theme::accent())
497 .text_color(theme::on_accent())
498 .text_size(px(14.))
499 .font_weight(FontWeight::SEMIBOLD)
500 .cursor_pointer()
501 .hover(|button| button.opacity(0.85))
502 .child(REPLACE_LABEL)
503 .on_click(cx.listener(|this, _, window, cx| {
504 this.replace_with_rewrite(window, cx)
505 })),
506 )
507 .child(
508 div()
509 .text_size(px(11.))
510 .text_color(theme::text_muted())
511 .child(DISCLAIMER),
512 ),
513 ),
514 })
515 }
516}
517
518fn demo_rewrite(text: &str) -> String {
519 let trimmed = text.trim().trim_end_matches(['.', '!', '?']);
520 let mut characters = trimmed.chars();
521 let capitalized: String = characters
522 .next()
523 .map(|first| first.to_uppercase().chain(characters).collect())
524 .unwrap_or_default();
525 format!("{capitalized}.")
526}
527
528#[cfg(test)]
529mod tests {
530 use super::demo_rewrite;
531
532 #[test]
533 fn the_demo_answer_tidies_the_draft() {
534 assert_eq!(demo_rewrite(" hallo zusammen!! "), "Hallo zusammen.");
535 }
536}