BlueGit

ict rusty-teams

Files

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

rewrite.rs

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