BlueGit

ict rusty-teams

feat(composer): Write with Copilot (Rewrite, Proofread, Adjust) like Teams

- AugLoop session over a page WebSocket, token stays in the page (session AugloopExchange)
- chatsvc::compose_copilot sends the Teams rewrite signal: tone/length per action, customPrompt for Customised
- composer button and panel: Rewrite, Proofread, Adjust menu, result card with Replace
- chats only; text-only drafts; hidden in a narrow composer

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

metis Daniel Däschle · pushed by metis

Authored 2026-11-09 · 3 weeks ago

Hash
ce2236f4c03d68cd63c9ef517dcbb07a364db97f
Parent
192f2deb
15 files changed +990 −2
crates/app-base/src/assets.rs +3 −1
@@ -8,7 +8,7 @@ macro_rules! symbols {
8 8 };
9 9 }
10 10
11 const SYMBOLS: [(&str, &[u8]); 206] = symbols![
11 const SYMBOLS: [(&str, &[u8]); 208] = symbols![
12 12 "account_circle",
13 13 "add",
14 14 "alarm",
@@ -22,6 +22,7 @@ const SYMBOLS: [(&str, &[u8]); 206] = symbols![
22 22 "asterisk",
23 23 "attach_file",
24 24 "attach_money",
25 "auto_fix_high",
25 26 "back_hand",
26 27 "backspace",
27 28 "bar_chart",
@@ -174,6 +175,7 @@ const SYMBOLS: [(&str, &[u8]); 206] = symbols![
174 175 "shield",
175 176 "smart_toy",
176 177 "smart_toy_fill",
178 "spellcheck",
177 179 "spinner_arc",
178 180 "spinner_track",
179 181 "star",
@@ -8,7 +8,7 @@ macro_rules! symbols {
8 };
8 };
9}
9}
10
10
11const SYMBOLS: [(&str, &[u8]); 206] = symbols![
11const SYMBOLS: [(&str, &[u8]); 208] = symbols![
12 "account_circle",
12 "account_circle",
13 "add",
13 "add",
14 "alarm",
14 "alarm",
@@ -22,6 +22,7 @@ const SYMBOLS: [(&str, &[u8]); 206] = symbols![
22 "asterisk",
22 "asterisk",
23 "attach_file",
23 "attach_file",
24 "attach_money",
24 "attach_money",
25 "auto_fix_high",
25 "back_hand",
26 "back_hand",
26 "backspace",
27 "backspace",
27 "bar_chart",
28 "bar_chart",
@@ -174,6 +175,7 @@ const SYMBOLS: [(&str, &[u8]); 206] = symbols![
174 "shield",
175 "shield",
175 "smart_toy",
176 "smart_toy",
176 "smart_toy_fill",
177 "smart_toy_fill",
178 "spellcheck",
177 "spinner_arc",
179 "spinner_arc",
178 "spinner_track",
180 "spinner_track",
179 "star",
181 "star",
crates/app/assets/symbols/auto_fix_high.svg added +1 −0
@@ -0,0 +1 @@
1 <svg xmlns="http://www.w3.org/2000/svg" height="20" viewBox="0 -960 960 960" width="20"><path d="m782.77-678.92-32.37-73.02-73.01-32.37 73.01-33.37 32.37-72.01 32.37 72.01 73.01 33.37-73.01 32.37-32.37 73.02Zm-446 0-32.37-73.02-73.01-32.37 73.01-33.37 32.37-72.01 32.37 72.01 73.01 33.37-73.01 32.37-32.37 73.02Zm446 442-32.37-73.02-73.01-32.37 73.01-33.37 32.37-72.01 32.37 72.01 73.01 33.37-73.01 32.37-32.37 73.02Zm-569.23 101.3-80.46-79.46q-12.46-12.59-12.46-30.6t12.46-30.47l399.23-398.46q12.59-12.46 30.6-12.46t30.47 12.46l79.46 80.46q12.47 12.59 12.47 30.6t-12.47 30.47L274.61-135.62q-12.59 12.46-30.6 12.46t-30.47-12.46ZM243.69-178l291.77-291-68-68-291 291.77L243.69-178Z"/></svg>
@@ -0,0 +1 @@
1<svg xmlns="http://www.w3.org/2000/svg" height="20" viewBox="0 -960 960 960" width="20"><path d="m782.77-678.92-32.37-73.02-73.01-32.37 73.01-33.37 32.37-72.01 32.37 72.01 73.01 33.37-73.01 32.37-32.37 73.02Zm-446 0-32.37-73.02-73.01-32.37 73.01-33.37 32.37-72.01 32.37 72.01 73.01 33.37-73.01 32.37-32.37 73.02Zm446 442-32.37-73.02-73.01-32.37 73.01-33.37 32.37-72.01 32.37 72.01 73.01 33.37-73.01 32.37-32.37 73.02Zm-569.23 101.3-80.46-79.46q-12.46-12.59-12.46-30.6t12.46-30.47l399.23-398.46q12.59-12.46 30.6-12.46t30.47 12.46l79.46 80.46q12.47 12.59 12.47 30.6t-12.47 30.47L274.61-135.62q-12.59 12.46-30.6 12.46t-30.47-12.46ZM243.69-178l291.77-291-68-68-291 291.77L243.69-178Z"/></svg>
crates/app/assets/symbols/spellcheck.svg added +1 −0
@@ -0,0 +1 @@
1 <svg xmlns="http://www.w3.org/2000/svg" height="20" viewBox="0 -960 960 960" width="20"><path d="M544-157.85 388.85-314 426-351.15l118 119 221.77-221.77 37.15 37.15L544-157.85ZM159.39-384l177.69-480h61.38l176.92 480h-59.92l-45.07-133H267.92l-47.84 133h-60.69ZM286-566h165.31L369-796.54h-3.23L286-566Z"/></svg>
@@ -0,0 +1 @@
1<svg xmlns="http://www.w3.org/2000/svg" height="20" viewBox="0 -960 960 960" width="20"><path d="M544-157.85 388.85-314 426-351.15l118 119 221.77-221.77 37.15 37.15L544-157.85ZM159.39-384l177.69-480h61.38l176.92 480h-59.92l-45.07-133H267.92l-47.84 133h-60.69ZM286-566h165.31L369-796.54h-3.23L286-566Z"/></svg>
crates/app/src/views/composer.rs +11 −0
@@ -35,6 +35,7 @@ mod drafts;
35 35 mod format_menus;
36 36 pub(crate) mod plus_menu;
37 37 mod post;
38 mod rewrite;
38 39 pub use post::{
39 40 POST_ANNOUNCEMENT_TAG, POST_ANNOUNCEMENT_TOGGLE_TAG, POST_AUDIENCE_TAG, POST_CARD_DIVIDER_TAG,
40 41 POST_CARD_FOOTER_TAG, POST_CARD_HEADER_TAG, POST_CARD_SEND_TAG, POST_CARD_SUBJECT_TAG,
@@ -258,6 +259,7 @@ pub struct Composer {
258 259 caret_before_table: usize,
259 260 caret_text: String,
260 261 importance: store::MessageImportance,
262 rewrite: rewrite::RewritePanel,
261 263 delivery_menu: bool,
262 264 plus_menu: bool,
263 265 _subscriptions: [Subscription; 4],
@@ -530,6 +532,7 @@ impl Composer {
530 532 caret_before_table: 0,
531 533 caret_text: String::new(),
532 534 importance: store::MessageImportance::Normal,
535 rewrite: rewrite::RewritePanel::default(),
533 536 delivery_menu: false,
534 537 plus_menu: false,
535 538 _subscriptions: [subscription, observer, image_observer, picker_subscription],
@@ -1774,6 +1777,7 @@ impl Composer {
1774 1777 self.saved_images = None;
1775 1778 let carry = self.carry_images_into.take().as_deref() == Some(conversation_id);
1776 1779 self.conversation_id = Some(conversation_id.to_owned());
1780 self.close_rewrite();
1777 1781 self.cancel_uploads();
1778 1782 let dropped = if carry {
1779 1783 self.tray.keep_images_only()
@@ -2994,6 +2998,7 @@ impl Render for Composer {
2994 2998 .children(format_toggle)
2995 2999 .children(fun)
2996 3000 .children(attach)
3001 .children(self.render_rewrite_button(cx))
2997 3002 .children(self.render_plus_button(cx));
2998 3003 let (row_actions, post_footer) = if post_layout {
2999 3004 (None, Some(self.render_post_footer(actions, can_send, cx)))
@@ -3374,6 +3379,11 @@ impl Render for Composer {
3374 3379 cx.stop_propagation();
3375 3380 return;
3376 3381 }
3382 if this.close_rewrite() {
3383 cx.notify();
3384 cx.stop_propagation();
3385 return;
3386 }
3377 3387 if this.toolbar_requested(cx) && !this.format_bar_open() {
3378 3388 this.toolbar_dismissed = Some(this.selection(cx));
3379 3389 cx.notify();
@@ -3413,6 +3423,7 @@ impl Render for Composer {
3413 3423 .children(self.render_schedule(cx))
3414 3424 .children(self.render_delivery_menu(cx))
3415 3425 .children(self.render_plus_menu(cx))
3426 .children(self.render_rewrite_panel(cx))
3416 3427 .child(
3417 3428 v_flex()
3418 3429 .debug_selector(|| COMPOSER_BOX_TAG.into())
@@ -35,6 +35,7 @@ mod drafts;
35mod format_menus;
35mod format_menus;
36pub(crate) mod plus_menu;
36pub(crate) mod plus_menu;
37mod post;
37mod post;
38mod rewrite;
38pub use post::{
39pub use post::{
39 POST_ANNOUNCEMENT_TAG, POST_ANNOUNCEMENT_TOGGLE_TAG, POST_AUDIENCE_TAG, POST_CARD_DIVIDER_TAG,
40 POST_ANNOUNCEMENT_TAG, POST_ANNOUNCEMENT_TOGGLE_TAG, POST_AUDIENCE_TAG, POST_CARD_DIVIDER_TAG,
40 POST_CARD_FOOTER_TAG, POST_CARD_HEADER_TAG, POST_CARD_SEND_TAG, POST_CARD_SUBJECT_TAG,
41 POST_CARD_FOOTER_TAG, POST_CARD_HEADER_TAG, POST_CARD_SEND_TAG, POST_CARD_SUBJECT_TAG,
@@ -258,6 +259,7 @@ pub struct Composer {
258 caret_before_table: usize,
259 caret_before_table: usize,
259 caret_text: String,
260 caret_text: String,
260 importance: store::MessageImportance,
261 importance: store::MessageImportance,
262 rewrite: rewrite::RewritePanel,
261 delivery_menu: bool,
263 delivery_menu: bool,
262 plus_menu: bool,
264 plus_menu: bool,
263 _subscriptions: [Subscription; 4],
265 _subscriptions: [Subscription; 4],
@@ -530,6 +532,7 @@ impl Composer {
530 caret_before_table: 0,
532 caret_before_table: 0,
531 caret_text: String::new(),
533 caret_text: String::new(),
532 importance: store::MessageImportance::Normal,
534 importance: store::MessageImportance::Normal,
535 rewrite: rewrite::RewritePanel::default(),
533 delivery_menu: false,
536 delivery_menu: false,
534 plus_menu: false,
537 plus_menu: false,
535 _subscriptions: [subscription, observer, image_observer, picker_subscription],
538 _subscriptions: [subscription, observer, image_observer, picker_subscription],
@@ -1774,6 +1777,7 @@ impl Composer {
1774 self.saved_images = None;
1777 self.saved_images = None;
1775 let carry = self.carry_images_into.take().as_deref() == Some(conversation_id);
1778 let carry = self.carry_images_into.take().as_deref() == Some(conversation_id);
1776 self.conversation_id = Some(conversation_id.to_owned());
1779 self.conversation_id = Some(conversation_id.to_owned());
1780 self.close_rewrite();
1777 self.cancel_uploads();
1781 self.cancel_uploads();
1778 let dropped = if carry {
1782 let dropped = if carry {
1779 self.tray.keep_images_only()
1783 self.tray.keep_images_only()
@@ -2994,6 +2998,7 @@ impl Render for Composer {
2994 .children(format_toggle)
2998 .children(format_toggle)
2995 .children(fun)
2999 .children(fun)
2996 .children(attach)
3000 .children(attach)
3001 .children(self.render_rewrite_button(cx))
2997 .children(self.render_plus_button(cx));
3002 .children(self.render_plus_button(cx));
2998 let (row_actions, post_footer) = if post_layout {
3003 let (row_actions, post_footer) = if post_layout {
2999 (None, Some(self.render_post_footer(actions, can_send, cx)))
3004 (None, Some(self.render_post_footer(actions, can_send, cx)))
@@ -3374,6 +3379,11 @@ impl Render for Composer {
3374 cx.stop_propagation();
3379 cx.stop_propagation();
3375 return;
3380 return;
3376 }
3381 }
3382 if this.close_rewrite() {
3383 cx.notify();
3384 cx.stop_propagation();
3385 return;
3386 }
3377 if this.toolbar_requested(cx) && !this.format_bar_open() {
3387 if this.toolbar_requested(cx) && !this.format_bar_open() {
3378 this.toolbar_dismissed = Some(this.selection(cx));
3388 this.toolbar_dismissed = Some(this.selection(cx));
3379 cx.notify();
3389 cx.notify();
@@ -3413,6 +3423,7 @@ impl Render for Composer {
3413 .children(self.render_schedule(cx))
3423 .children(self.render_schedule(cx))
3414 .children(self.render_delivery_menu(cx))
3424 .children(self.render_delivery_menu(cx))
3415 .children(self.render_plus_menu(cx))
3425 .children(self.render_plus_menu(cx))
3426 .children(self.render_rewrite_panel(cx))
3416 .child(
3427 .child(
3417 v_flex()
3428 v_flex()
3418 .debug_selector(|| COMPOSER_BOX_TAG.into())
3429 .debug_selector(|| COMPOSER_BOX_TAG.into())
crates/app/src/views/composer/rewrite.rs added +463 −0
@@ -0,0 +1,463 @@
1 use gpui_kit::component::fluent::{
2 MENU_ITEM_GAP, MENU_ITEM_HEIGHT, MENU_ITEM_PADDING_X, MENU_LIST_PADDING,
3 };
4 use gpui_kit::component::input::{Input, InputContent, InputEvent, InputState};
5 use gpui_kit::component::tooltip::PopupTriggerTooltip as _;
6 use gpui_kit::component::{h_flex, v_flex};
7 use gpui_kit::prelude::FluentBuilder as _;
8 use gpui_kit::*;
9 use teams_core::{ComposeAction, ComposeAdjustment, Draft, OBJECT_MARK, TABLE_MARK, html_to_spans};
10
11 use super::{COMPOSER_BUTTON_SIZE, COMPOSER_ICON_SIZE, Composer};
12 use crate::runtime;
13 use app_ui_kit::spinner::spinner;
14 use crate::theme::{self, ElevatedSurface as _};
15 use crate::views::widgets::symbol;
16
17 pub const REWRITE_BUTTON_TAG: &str = "composer/actions/copilot";
18 pub const REWRITE_PANEL_TAG: &str = "composer/copilot";
19 const BUTTON_LABEL: &str = "Write with Copilot";
20 const CLOSE_LABEL: &str = "Close";
21 const ADJUST_LABEL: &str = "Adjust";
22 const CUSTOM_LABEL: &str = "Customised";
23 const CUSTOM_PLACEHOLDER: &str = "Describe how to adjust it, e.g. make it sound friendlier";
24 const REPLACE_LABEL: &str = "Replace";
25 const DISCLAIMER: &str = "AI-generated content may be incorrect";
26 const WORKING: &str = "Copilot is writing ...";
27 const FAILED: &str = "Copilot could not rewrite this:";
28 const EMPTY_DRAFT: &str = "Type a message first, then let Copilot rewrite it.";
29 const TEXT_ONLY: &str = "Copilot rewrites text only. Move images and tables out of the message first.";
30 const BUTTON_ICON: &str = "auto_fix_high";
31 const PANEL_WIDTH: f32 = 600.;
32 const PANEL_PADDING: f32 = 16.;
33 const PANEL_RADIUS: f32 = 10.;
34 const CARD_RADIUS: f32 = 8.;
35 const CHIP_HEIGHT: f32 = 32.;
36 const CHIP_ICON: f32 = 16.;
37 const ADJUST_MENU_WIDTH: f32 = 200.;
38 const BUTTON_MIN_COMPOSER_WIDTH: f32 = 320.;
39 const DEMO_DELAY: std::time::Duration = std::time::Duration::from_millis(700);
40
41 #[derive(Default)]
42 pub(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
52 struct RewriteResult {
53 action: ComposeAction,
54 answer: RewriteAnswer,
55 }
56
57 enum RewriteAnswer {
58 Waiting,
59 Ready(Draft),
60 Failed(String),
61 }
62
63 #[derive(Clone, Copy, PartialEq, Eq)]
64 enum Choice {
65 Rewrite,
66 Proofread,
67 }
68
69 impl Composer {
70 fn rewrite_available(&self, cx: &App) -> bool {
71 let state = self.app.read(cx);
72 self.editing.is_none()
73 && (state.mode.demo || state.engine.is_some())
74 && self
75 .conversation_id
76 .as_deref()
77 .is_some_and(|conversation_id| state.sidebar.chats.iter().any(|chat| chat.id == conversation_id))
78 }
79
80 pub(super) fn render_rewrite_button(&self, cx: &mut Context<Self>) -> Option<Stateful<Div>> {
81 let fits = self
82 .composer_bounds
83 .get()
84 .is_none_or(|bounds| f32::from(bounds.size.width) >= BUTTON_MIN_COMPOSER_WIDTH);
85 if !fits || !self.rewrite_available(cx) {
86 return None;
87 }
88 let open = self.rewrite.open;
89 Some(
90 div()
91 .id("composer-copilot")
92 .debug_selector(|| REWRITE_BUTTON_TAG.into())
93 .size(px(COMPOSER_BUTTON_SIZE))
94 .flex_none()
95 .flex()
96 .items_center()
97 .justify_center()
98 .rounded(px(8.))
99 .cursor_pointer()
100 .when(open, |button| button.bg(theme::popup_hover()))
101 .hover(|button| button.bg(theme::popup_hover()))
102 .popup_trigger_tooltip_text(open, BUTTON_LABEL)
103 .child(symbol(BUTTON_ICON, COMPOSER_ICON_SIZE, theme::accent_text()))
104 .on_mouse_down(MouseButton::Left, |_, window, cx| {
105 window.prevent_default();
106 cx.stop_propagation();
107 })
108 .on_click(cx.listener(|this, _, _, cx| {
109 this.rewrite.open = !this.rewrite.open;
110 this.rewrite.adjust_menu = false;
111 cx.notify();
112 })),
113 )
114 }
115
116 pub(super) fn close_rewrite(&mut self) -> bool {
117 let was_open = self.rewrite.open;
118 self.rewrite.open = false;
119 self.rewrite.adjust_menu = false;
120 self.rewrite.custom_open = false;
121 self.rewrite.result = None;
122 self.rewrite.generation += 1;
123 was_open
124 }
125
126 fn request_rewrite(&mut self, action: ComposeAction, cx: &mut Context<Self>) {
127 self.rewrite.adjust_menu = false;
128 self.rewrite.generation += 1;
129 let generation = self.rewrite.generation;
130 let draft = self.current_draft(cx);
131 let demo = self.app.read(cx).mode.demo;
132 let engine = self.app.read(cx).engine.clone();
133 let Some(chat_id) = self.conversation_id.clone() else {
134 return;
135 };
136 let refusal = if draft.is_blank() {
137 Some(EMPTY_DRAFT)
138 } else if draft.text().contains([OBJECT_MARK, TABLE_MARK]) {
139 Some(TEXT_ONLY)
140 } else {
141 None
142 };
143 if let Some(refusal) = refusal {
144 self.rewrite.result = Some(RewriteResult {
145 action,
146 answer: RewriteAnswer::Failed(refusal.to_owned()),
147 });
148 cx.notify();
149 return;
150 }
151 self.rewrite.result = Some(RewriteResult {
152 action: action.clone(),
153 answer: RewriteAnswer::Waiting,
154 });
155 cx.notify();
156 let user_html = draft.to_html();
157 let receiver = (!demo)
158 .then_some(engine)
159 .flatten()
160 .map(|engine| runtime::spawn(async move { engine.rewrite_draft(&chat_id, &user_html, action).await }));
161 let demo_answer = demo_rewrite(&draft.plain_text());
162 cx.spawn(async move |this, cx| {
163 let answer = match receiver {
164 None => {
165 cx.background_executor().timer(DEMO_DELAY).await;
166 RewriteAnswer::Ready(Draft::from_markdown(&demo_answer))
167 }
168 Some(receiver) => match receiver.await {
169 Ok(Ok(html)) => RewriteAnswer::Ready(Draft::from_spans(&html_to_spans(&html)).trimmed()),
170 Ok(Err(error)) => RewriteAnswer::Failed(format!("{FAILED} {error}")),
171 Err(error) => RewriteAnswer::Failed(format!("{FAILED} {error}")),
172 },
173 };
174 this.update(cx, |this, cx| {
175 if this.rewrite.generation == generation
176 && let Some(result) = this.rewrite.result.as_mut()
177 {
178 result.answer = answer;
179 cx.notify();
180 }
181 })
182 .ok();
183 })
184 .detach();
185 }
186
187 fn replace_with_rewrite(&mut self, window: &mut Window, cx: &mut Context<Self>) {
188 let Some(RewriteAnswer::Ready(draft)) = self.rewrite.result.as_ref().map(|result| &result.answer) else {
189 return;
190 };
191 let draft = draft.clone();
192 self.close_rewrite();
193 self.load_draft(draft.clone(), InputContent::new(draft.text().to_owned()), window, cx);
194 self.mention_inputs.clear();
195 self.schedule_draft_save(cx);
196 self.focus(window, cx);
197 cx.notify();
198 }
199
200 fn open_custom(&mut self, window: &mut Window, cx: &mut Context<Self>) {
201 self.rewrite.adjust_menu = false;
202 self.rewrite.custom_open = true;
203 if self.rewrite.custom_input.is_none() {
204 let input = cx.new(|cx| InputState::new(window, cx).placeholder(CUSTOM_PLACEHOLDER));
205 let subscription = cx.subscribe_in(&input, window, |this, input, event: &InputEvent, window, cx| {
206 if matches!(event, InputEvent::PressEnter { .. }) {
207 let prompt = input.read(cx).value().trim().to_owned();
208 if !prompt.is_empty() {
209 input.update(cx, |input, cx| input.set_value("", window, cx));
210 this.rewrite.custom_open = false;
211 this.request_rewrite(ComposeAction::Custom(prompt), cx);
212 }
213 }
214 });
215 self.rewrite.custom_input = Some(input);
216 self.rewrite._custom_events = Some(subscription);
217 }
218 if let Some(input) = &self.rewrite.custom_input {
219 input.update(cx, |input, cx| input.focus(window, cx));
220 }
221 cx.notify();
222 }
223
224 pub(super) fn render_rewrite_panel(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
225 if !self.rewrite.open || !self.rewrite_available(cx) {
226 return None;
227 }
228 let busy = matches!(
229 self.rewrite.result.as_ref().map(|result| &result.answer),
230 Some(RewriteAnswer::Waiting)
231 );
232 let chips = h_flex()
233 .w_full()
234 .gap(px(8.))
235 .items_center()
236 .child(self.choice_chip(Choice::Rewrite, busy, cx))
237 .child(self.choice_chip(Choice::Proofread, busy, cx))
238 .child(
239 div()
240 .relative()
241 .child(self.adjust_chip(busy, cx))
242 .children(self.render_adjust_menu(cx)),
243 )
244 .child(div().flex_1())
245 .child(
246 div()
247 .id("composer-copilot-close")
248 .size(px(CHIP_HEIGHT))
249 .flex()
250 .items_center()
251 .justify_center()
252 .rounded(px(6.))
253 .cursor_pointer()
254 .hover(|button| button.bg(theme::popup_hover()))
255 .popup_trigger_tooltip_text(false, CLOSE_LABEL)
256 .child(symbol("close", CHIP_ICON, theme::text_soft()))
257 .on_click(cx.listener(|this, _, _, cx| {
258 this.close_rewrite();
259 cx.notify();
260 })),
261 );
262 let custom = self
263 .rewrite
264 .custom_open
265 .then(|| self.rewrite.custom_input.clone())
266 .flatten()
267 .map(|input| {
268 div()
269 .w_full()
270 .px(px(12.))
271 .py(px(8.))
272 .rounded(px(CARD_RADIUS))
273 .bg(theme::surface_raised())
274 .child(Input::new(&input).appearance(false).bordered(false))
275 });
276 Some(
277 v_flex()
278 .id(REWRITE_PANEL_TAG)
279 .debug_selector(|| REWRITE_PANEL_TAG.into())
280 .absolute()
281 .bottom(relative(1.))
282 .right_0()
283 .mb(px(6.))
284 .w(px(PANEL_WIDTH))
285 .max_w(relative(1.))
286 .p(px(PANEL_PADDING))
287 .gap(px(12.))
288 .rounded(px(PANEL_RADIUS))
289 .flyout_surface()
290 .occlude()
291 .child(chips)
292 .children(custom)
293 .children(self.render_rewrite_result(cx))
294 .into_any_element(),
295 )
296 }
297
298 fn chip(id: &'static str, icon: &'static str, label: &'static str, busy: bool) -> Stateful<Div> {
299 h_flex()
300 .id(id)
301 .h(px(CHIP_HEIGHT))
302 .px(px(12.))
303 .gap(px(6.))
304 .items_center()
305 .rounded(px(6.))
306 .bg(theme::surface_raised())
307 .text_size(px(13.))
308 .font_weight(FontWeight::SEMIBOLD)
309 .text_color(theme::text())
310 .child(symbol(icon, CHIP_ICON, theme::text_soft()))
311 .child(label)
312 .when(busy, |chip| chip.opacity(0.5))
313 .when(!busy, |chip| chip.cursor_pointer().hover(|chip| chip.bg(theme::popup_hover())))
314 }
315
316 fn choice_chip(&self, choice: Choice, busy: bool, cx: &mut Context<Self>) -> Stateful<Div> {
317 let (id, icon, action) = match choice {
318 Choice::Rewrite => ("composer-copilot-rewrite", BUTTON_ICON, ComposeAction::Rewrite),
319 Choice::Proofread => ("composer-copilot-proofread", "spellcheck", ComposeAction::Proofread),
320 };
321 let label = match choice {
322 Choice::Rewrite => "Rewrite",
323 Choice::Proofread => "Proofread",
324 };
325 Self::chip(id, icon, label, busy).when(!busy, |chip| {
326 chip.on_click(cx.listener(move |this, _, _, cx| this.request_rewrite(action.clone(), cx)))
327 })
328 }
329
330 fn adjust_chip(&self, busy: bool, cx: &mut Context<Self>) -> Stateful<Div> {
331 Self::chip("composer-copilot-adjust", "more_horiz", ADJUST_LABEL, busy)
332 .child(symbol("keyboard_arrow_down", CHIP_ICON, theme::text_soft()))
333 .when(!busy, |chip| {
334 chip.on_click(cx.listener(|this, _, _, cx| {
335 this.rewrite.adjust_menu = !this.rewrite.adjust_menu;
336 cx.notify();
337 }))
338 })
339 }
340
341 fn render_adjust_menu(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
342 if !self.rewrite.adjust_menu {
343 return None;
344 }
345 let item = |id: &'static str, label: &'static str| {
346 div()
347 .id(id)
348 .w_full()
349 .h(MENU_ITEM_HEIGHT)
350 .px(MENU_ITEM_PADDING_X)
351 .flex()
352 .items_center()
353 .rounded(px(6.))
354 .cursor_pointer()
355 .hover(|row| row.bg(theme::popup_hover()))
356 .text_size(px(13.))
357 .text_color(theme::text())
358 .child(label)
359 };
360 let custom = item("composer-copilot-custom", CUSTOM_LABEL)
361 .on_click(cx.listener(|this, _, window, cx| this.open_custom(window, cx)));
362 let adjustments = ComposeAdjustment::ALL.into_iter().map(|adjustment| {
363 item(adjustment.label(), adjustment.label()).on_click(cx.listener(move |this, _, _, cx| {
364 this.request_rewrite(ComposeAction::Adjust(adjustment), cx)
365 }))
366 });
367 Some(
368 v_flex()
369 .id("composer-copilot-adjust-menu")
370 .absolute()
371 .bottom(relative(1.))
372 .left_0()
373 .mb(px(4.))
374 .w(px(ADJUST_MENU_WIDTH))
375 .p(MENU_LIST_PADDING)
376 .gap(MENU_ITEM_GAP)
377 .rounded(px(10.))
378 .flyout_surface()
379 .occlude()
380 .on_mouse_down_out(cx.listener(|this, _, _, cx| {
381 this.rewrite.adjust_menu = false;
382 cx.notify();
383 }))
384 .child(custom)
385 .children(adjustments)
386 .into_any_element(),
387 )
388 }
389
390 fn render_rewrite_result(&self, cx: &mut Context<Self>) -> Option<Div> {
391 let result = self.rewrite.result.as_ref()?;
392 let card = v_flex()
393 .w_full()
394 .p(px(PANEL_PADDING))
395 .gap(px(12.))
396 .rounded(px(CARD_RADIUS))
397 .bg(theme::surface_raised())
398 .child(
399 div()
400 .text_size(px(12.))
401 .text_color(theme::text_soft())
402 .child(result.action.label().to_owned()),
403 );
404 Some(match &result.answer {
405 RewriteAnswer::Waiting => card.child(
406 h_flex()
407 .gap(px(8.))
408 .items_center()
409 .child(spinner(16.))
410 .child(div().text_size(px(14.)).text_color(theme::text_soft()).child(WORKING)),
411 ),
412 RewriteAnswer::Failed(reason) => {
413 card.child(div().text_size(px(14.)).text_color(theme::text_soft()).child(reason.clone()))
414 }
415 RewriteAnswer::Ready(draft) => card
416 .child(div().text_size(px(14.)).text_color(theme::text()).child(draft.plain_text()))
417 .child(
418 h_flex()
419 .w_full()
420 .items_center()
421 .justify_between()
422 .child(
423 div()
424 .id("composer-copilot-replace")
425 .h(px(CHIP_HEIGHT))
426 .px(px(24.))
427 .flex()
428 .items_center()
429 .rounded(px(6.))
430 .bg(theme::accent())
431 .text_color(theme::on_accent())
432 .text_size(px(14.))
433 .font_weight(FontWeight::SEMIBOLD)
434 .cursor_pointer()
435 .hover(|button| button.opacity(0.85))
436 .child(REPLACE_LABEL)
437 .on_click(cx.listener(|this, _, window, cx| this.replace_with_rewrite(window, cx))),
438 )
439 .child(div().text_size(px(11.)).text_color(theme::text_muted()).child(DISCLAIMER)),
440 ),
441 })
442 }
443 }
444
445 fn demo_rewrite(text: &str) -> String {
446 let trimmed = text.trim().trim_end_matches(['.', '!', '?']);
447 let mut characters = trimmed.chars();
448 let capitalized: String = characters
449 .next()
450 .map(|first| first.to_uppercase().chain(characters).collect())
451 .unwrap_or_default();
452 format!("{capitalized}.")
453 }
454
455 #[cfg(test)]
456 mod tests {
457 use super::demo_rewrite;
458
459 #[test]
460 fn the_demo_answer_tidies_the_draft() {
461 assert_eq!(demo_rewrite(" hallo zusammen!! "), "Hallo zusammen.");
462 }
463 }
@@ -0,0 +1,463 @@
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 app_ui_kit::spinner::spinner;
14use crate::theme::{self, ElevatedSurface as _};
15use crate::views::widgets::symbol;
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 = "Copilot rewrites text only. Move images and tables out of the message first.";
30const BUTTON_ICON: &str = "auto_fix_high";
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
52struct RewriteResult {
53 action: ComposeAction,
54 answer: RewriteAnswer,
55}
56
57enum RewriteAnswer {
58 Waiting,
59 Ready(Draft),
60 Failed(String),
61}
62
63#[derive(Clone, Copy, PartialEq, Eq)]
64enum Choice {
65 Rewrite,
66 Proofread,
67}
68
69impl Composer {
70 fn rewrite_available(&self, cx: &App) -> bool {
71 let state = self.app.read(cx);
72 self.editing.is_none()
73 && (state.mode.demo || state.engine.is_some())
74 && self
75 .conversation_id
76 .as_deref()
77 .is_some_and(|conversation_id| state.sidebar.chats.iter().any(|chat| chat.id == conversation_id))
78 }
79
80 pub(super) fn render_rewrite_button(&self, cx: &mut Context<Self>) -> Option<Stateful<Div>> {
81 let fits = self
82 .composer_bounds
83 .get()
84 .is_none_or(|bounds| f32::from(bounds.size.width) >= BUTTON_MIN_COMPOSER_WIDTH);
85 if !fits || !self.rewrite_available(cx) {
86 return None;
87 }
88 let open = self.rewrite.open;
89 Some(
90 div()
91 .id("composer-copilot")
92 .debug_selector(|| REWRITE_BUTTON_TAG.into())
93 .size(px(COMPOSER_BUTTON_SIZE))
94 .flex_none()
95 .flex()
96 .items_center()
97 .justify_center()
98 .rounded(px(8.))
99 .cursor_pointer()
100 .when(open, |button| button.bg(theme::popup_hover()))
101 .hover(|button| button.bg(theme::popup_hover()))
102 .popup_trigger_tooltip_text(open, BUTTON_LABEL)
103 .child(symbol(BUTTON_ICON, COMPOSER_ICON_SIZE, theme::accent_text()))
104 .on_mouse_down(MouseButton::Left, |_, window, cx| {
105 window.prevent_default();
106 cx.stop_propagation();
107 })
108 .on_click(cx.listener(|this, _, _, cx| {
109 this.rewrite.open = !this.rewrite.open;
110 this.rewrite.adjust_menu = false;
111 cx.notify();
112 })),
113 )
114 }
115
116 pub(super) fn close_rewrite(&mut self) -> bool {
117 let was_open = self.rewrite.open;
118 self.rewrite.open = false;
119 self.rewrite.adjust_menu = false;
120 self.rewrite.custom_open = false;
121 self.rewrite.result = None;
122 self.rewrite.generation += 1;
123 was_open
124 }
125
126 fn request_rewrite(&mut self, action: ComposeAction, cx: &mut Context<Self>) {
127 self.rewrite.adjust_menu = false;
128 self.rewrite.generation += 1;
129 let generation = self.rewrite.generation;
130 let draft = self.current_draft(cx);
131 let demo = self.app.read(cx).mode.demo;
132 let engine = self.app.read(cx).engine.clone();
133 let Some(chat_id) = self.conversation_id.clone() else {
134 return;
135 };
136 let refusal = if draft.is_blank() {
137 Some(EMPTY_DRAFT)
138 } else if draft.text().contains([OBJECT_MARK, TABLE_MARK]) {
139 Some(TEXT_ONLY)
140 } else {
141 None
142 };
143 if let Some(refusal) = refusal {
144 self.rewrite.result = Some(RewriteResult {
145 action,
146 answer: RewriteAnswer::Failed(refusal.to_owned()),
147 });
148 cx.notify();
149 return;
150 }
151 self.rewrite.result = Some(RewriteResult {
152 action: action.clone(),
153 answer: RewriteAnswer::Waiting,
154 });
155 cx.notify();
156 let user_html = draft.to_html();
157 let receiver = (!demo)
158 .then_some(engine)
159 .flatten()
160 .map(|engine| runtime::spawn(async move { engine.rewrite_draft(&chat_id, &user_html, action).await }));
161 let demo_answer = demo_rewrite(&draft.plain_text());
162 cx.spawn(async move |this, cx| {
163 let answer = match receiver {
164 None => {
165 cx.background_executor().timer(DEMO_DELAY).await;
166 RewriteAnswer::Ready(Draft::from_markdown(&demo_answer))
167 }
168 Some(receiver) => match receiver.await {
169 Ok(Ok(html)) => RewriteAnswer::Ready(Draft::from_spans(&html_to_spans(&html)).trimmed()),
170 Ok(Err(error)) => RewriteAnswer::Failed(format!("{FAILED} {error}")),
171 Err(error) => RewriteAnswer::Failed(format!("{FAILED} {error}")),
172 },
173 };
174 this.update(cx, |this, cx| {
175 if this.rewrite.generation == generation
176 && let Some(result) = this.rewrite.result.as_mut()
177 {
178 result.answer = answer;
179 cx.notify();
180 }
181 })
182 .ok();
183 })
184 .detach();
185 }
186
187 fn replace_with_rewrite(&mut self, window: &mut Window, cx: &mut Context<Self>) {
188 let Some(RewriteAnswer::Ready(draft)) = self.rewrite.result.as_ref().map(|result| &result.answer) else {
189 return;
190 };
191 let draft = draft.clone();
192 self.close_rewrite();
193 self.load_draft(draft.clone(), InputContent::new(draft.text().to_owned()), window, cx);
194 self.mention_inputs.clear();
195 self.schedule_draft_save(cx);
196 self.focus(window, cx);
197 cx.notify();
198 }
199
200 fn open_custom(&mut self, window: &mut Window, cx: &mut Context<Self>) {
201 self.rewrite.adjust_menu = false;
202 self.rewrite.custom_open = true;
203 if self.rewrite.custom_input.is_none() {
204 let input = cx.new(|cx| InputState::new(window, cx).placeholder(CUSTOM_PLACEHOLDER));
205 let subscription = cx.subscribe_in(&input, window, |this, input, event: &InputEvent, window, cx| {
206 if matches!(event, InputEvent::PressEnter { .. }) {
207 let prompt = input.read(cx).value().trim().to_owned();
208 if !prompt.is_empty() {
209 input.update(cx, |input, cx| input.set_value("", window, cx));
210 this.rewrite.custom_open = false;
211 this.request_rewrite(ComposeAction::Custom(prompt), cx);
212 }
213 }
214 });
215 self.rewrite.custom_input = Some(input);
216 self.rewrite._custom_events = Some(subscription);
217 }
218 if let Some(input) = &self.rewrite.custom_input {
219 input.update(cx, |input, cx| input.focus(window, cx));
220 }
221 cx.notify();
222 }
223
224 pub(super) fn render_rewrite_panel(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
225 if !self.rewrite.open || !self.rewrite_available(cx) {
226 return None;
227 }
228 let busy = matches!(
229 self.rewrite.result.as_ref().map(|result| &result.answer),
230 Some(RewriteAnswer::Waiting)
231 );
232 let chips = h_flex()
233 .w_full()
234 .gap(px(8.))
235 .items_center()
236 .child(self.choice_chip(Choice::Rewrite, busy, cx))
237 .child(self.choice_chip(Choice::Proofread, busy, cx))
238 .child(
239 div()
240 .relative()
241 .child(self.adjust_chip(busy, cx))
242 .children(self.render_adjust_menu(cx)),
243 )
244 .child(div().flex_1())
245 .child(
246 div()
247 .id("composer-copilot-close")
248 .size(px(CHIP_HEIGHT))
249 .flex()
250 .items_center()
251 .justify_center()
252 .rounded(px(6.))
253 .cursor_pointer()
254 .hover(|button| button.bg(theme::popup_hover()))
255 .popup_trigger_tooltip_text(false, CLOSE_LABEL)
256 .child(symbol("close", CHIP_ICON, theme::text_soft()))
257 .on_click(cx.listener(|this, _, _, cx| {
258 this.close_rewrite();
259 cx.notify();
260 })),
261 );
262 let custom = self
263 .rewrite
264 .custom_open
265 .then(|| self.rewrite.custom_input.clone())
266 .flatten()
267 .map(|input| {
268 div()
269 .w_full()
270 .px(px(12.))
271 .py(px(8.))
272 .rounded(px(CARD_RADIUS))
273 .bg(theme::surface_raised())
274 .child(Input::new(&input).appearance(false).bordered(false))
275 });
276 Some(
277 v_flex()
278 .id(REWRITE_PANEL_TAG)
279 .debug_selector(|| REWRITE_PANEL_TAG.into())
280 .absolute()
281 .bottom(relative(1.))
282 .right_0()
283 .mb(px(6.))
284 .w(px(PANEL_WIDTH))
285 .max_w(relative(1.))
286 .p(px(PANEL_PADDING))
287 .gap(px(12.))
288 .rounded(px(PANEL_RADIUS))
289 .flyout_surface()
290 .occlude()
291 .child(chips)
292 .children(custom)
293 .children(self.render_rewrite_result(cx))
294 .into_any_element(),
295 )
296 }
297
298 fn chip(id: &'static str, icon: &'static str, label: &'static str, busy: bool) -> Stateful<Div> {
299 h_flex()
300 .id(id)
301 .h(px(CHIP_HEIGHT))
302 .px(px(12.))
303 .gap(px(6.))
304 .items_center()
305 .rounded(px(6.))
306 .bg(theme::surface_raised())
307 .text_size(px(13.))
308 .font_weight(FontWeight::SEMIBOLD)
309 .text_color(theme::text())
310 .child(symbol(icon, CHIP_ICON, theme::text_soft()))
311 .child(label)
312 .when(busy, |chip| chip.opacity(0.5))
313 .when(!busy, |chip| chip.cursor_pointer().hover(|chip| chip.bg(theme::popup_hover())))
314 }
315
316 fn choice_chip(&self, choice: Choice, busy: bool, cx: &mut Context<Self>) -> Stateful<Div> {
317 let (id, icon, action) = match choice {
318 Choice::Rewrite => ("composer-copilot-rewrite", BUTTON_ICON, ComposeAction::Rewrite),
319 Choice::Proofread => ("composer-copilot-proofread", "spellcheck", ComposeAction::Proofread),
320 };
321 let label = match choice {
322 Choice::Rewrite => "Rewrite",
323 Choice::Proofread => "Proofread",
324 };
325 Self::chip(id, icon, label, busy).when(!busy, |chip| {
326 chip.on_click(cx.listener(move |this, _, _, cx| this.request_rewrite(action.clone(), cx)))
327 })
328 }
329
330 fn adjust_chip(&self, busy: bool, cx: &mut Context<Self>) -> Stateful<Div> {
331 Self::chip("composer-copilot-adjust", "more_horiz", ADJUST_LABEL, busy)
332 .child(symbol("keyboard_arrow_down", CHIP_ICON, theme::text_soft()))
333 .when(!busy, |chip| {
334 chip.on_click(cx.listener(|this, _, _, cx| {
335 this.rewrite.adjust_menu = !this.rewrite.adjust_menu;
336 cx.notify();
337 }))
338 })
339 }
340
341 fn render_adjust_menu(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
342 if !self.rewrite.adjust_menu {
343 return None;
344 }
345 let item = |id: &'static str, label: &'static str| {
346 div()
347 .id(id)
348 .w_full()
349 .h(MENU_ITEM_HEIGHT)
350 .px(MENU_ITEM_PADDING_X)
351 .flex()
352 .items_center()
353 .rounded(px(6.))
354 .cursor_pointer()
355 .hover(|row| row.bg(theme::popup_hover()))
356 .text_size(px(13.))
357 .text_color(theme::text())
358 .child(label)
359 };
360 let custom = item("composer-copilot-custom", CUSTOM_LABEL)
361 .on_click(cx.listener(|this, _, window, cx| this.open_custom(window, cx)));
362 let adjustments = ComposeAdjustment::ALL.into_iter().map(|adjustment| {
363 item(adjustment.label(), adjustment.label()).on_click(cx.listener(move |this, _, _, cx| {
364 this.request_rewrite(ComposeAction::Adjust(adjustment), cx)
365 }))
366 });
367 Some(
368 v_flex()
369 .id("composer-copilot-adjust-menu")
370 .absolute()
371 .bottom(relative(1.))
372 .left_0()
373 .mb(px(4.))
374 .w(px(ADJUST_MENU_WIDTH))
375 .p(MENU_LIST_PADDING)
376 .gap(MENU_ITEM_GAP)
377 .rounded(px(10.))
378 .flyout_surface()
379 .occlude()
380 .on_mouse_down_out(cx.listener(|this, _, _, cx| {
381 this.rewrite.adjust_menu = false;
382 cx.notify();
383 }))
384 .child(custom)
385 .children(adjustments)
386 .into_any_element(),
387 )
388 }
389
390 fn render_rewrite_result(&self, cx: &mut Context<Self>) -> Option<Div> {
391 let result = self.rewrite.result.as_ref()?;
392 let card = v_flex()
393 .w_full()
394 .p(px(PANEL_PADDING))
395 .gap(px(12.))
396 .rounded(px(CARD_RADIUS))
397 .bg(theme::surface_raised())
398 .child(
399 div()
400 .text_size(px(12.))
401 .text_color(theme::text_soft())
402 .child(result.action.label().to_owned()),
403 );
404 Some(match &result.answer {
405 RewriteAnswer::Waiting => card.child(
406 h_flex()
407 .gap(px(8.))
408 .items_center()
409 .child(spinner(16.))
410 .child(div().text_size(px(14.)).text_color(theme::text_soft()).child(WORKING)),
411 ),
412 RewriteAnswer::Failed(reason) => {
413 card.child(div().text_size(px(14.)).text_color(theme::text_soft()).child(reason.clone()))
414 }
415 RewriteAnswer::Ready(draft) => card
416 .child(div().text_size(px(14.)).text_color(theme::text()).child(draft.plain_text()))
417 .child(
418 h_flex()
419 .w_full()
420 .items_center()
421 .justify_between()
422 .child(
423 div()
424 .id("composer-copilot-replace")
425 .h(px(CHIP_HEIGHT))
426 .px(px(24.))
427 .flex()
428 .items_center()
429 .rounded(px(6.))
430 .bg(theme::accent())
431 .text_color(theme::on_accent())
432 .text_size(px(14.))
433 .font_weight(FontWeight::SEMIBOLD)
434 .cursor_pointer()
435 .hover(|button| button.opacity(0.85))
436 .child(REPLACE_LABEL)
437 .on_click(cx.listener(|this, _, window, cx| this.replace_with_rewrite(window, cx))),
438 )
439 .child(div().text_size(px(11.)).text_color(theme::text_muted()).child(DISCLAIMER)),
440 ),
441 })
442 }
443}
444
445fn demo_rewrite(text: &str) -> String {
446 let trimmed = text.trim().trim_end_matches(['.', '!', '?']);
447 let mut characters = trimmed.chars();
448 let capitalized: String = characters
449 .next()
450 .map(|first| first.to_uppercase().chain(characters).collect())
451 .unwrap_or_default();
452 format!("{capitalized}.")
453}
454
455#[cfg(test)]
456mod tests {
457 use super::demo_rewrite;
458
459 #[test]
460 fn the_demo_answer_tidies_the_draft() {
461 assert_eq!(demo_rewrite(" hallo zusammen!! "), "Hallo zusammen.");
462 }
463}
crates/chatsvc/examples/compose_copilot_probe.rs added +41 −0
@@ -0,0 +1,41 @@
1 use chatsvc::compose_copilot::{Adjustment, ComposeAction, ComposeCopilot, ComposeRewrite};
2 use session::{DEFAULT_ENDPOINT, Method, Scope, Session};
3
4 const DRAFT: &str = "<p>hallo zusammen, wollte kurz fragen ob das treffen morgen noch steht oder ob wir es verschieben</p>";
5
6 #[tokio::main]
7 async fn main() {
8 let arguments: Vec<String> = std::env::args().skip(1).collect();
9 let action = match arguments.first().map(String::as_str) {
10 Some("proofread") => ComposeAction::Proofread,
11 Some("custom") => ComposeAction::Custom(arguments[1..].join(" ")),
12 Some(label) => Adjustment::ALL
13 .into_iter()
14 .find(|adjustment| adjustment.label().eq_ignore_ascii_case(label))
15 .map_or(ComposeAction::Rewrite, ComposeAction::Adjust),
16 None => ComposeAction::Rewrite,
17 };
18 let endpoint = std::env::var("CDP_ENDPOINT").unwrap_or_else(|_| DEFAULT_ENDPOINT.to_owned());
19 let session = Session::connect(&endpoint).await.expect("browser");
20 let organization = session
21 .request(
22 Method::Get,
23 "https://graph.microsoft.com/v1.0/organization?$select=id",
24 &Scope::graph("User.Read"),
25 None,
26 )
27 .await
28 .expect("organization");
29 let rewrite = ComposeRewrite {
30 tenant_id: organization.body["value"][0]["id"].as_str().expect("tenant id").to_owned(),
31 thread_id: "48:notes".to_owned(),
32 user_html: DRAFT.to_owned(),
33 action,
34 ui_language: "en-gb".to_owned(),
35 time_zone: "Europe/Berlin".to_owned(),
36 };
37 match ComposeCopilot::new(&session).rewrite(&rewrite).await {
38 Ok(answer) => println!("answer: {answer}"),
39 Err(error) => println!("error: {error}"),
40 }
41 }
@@ -0,0 +1,41 @@
1use chatsvc::compose_copilot::{Adjustment, ComposeAction, ComposeCopilot, ComposeRewrite};
2use session::{DEFAULT_ENDPOINT, Method, Scope, Session};
3
4const DRAFT: &str = "<p>hallo zusammen, wollte kurz fragen ob das treffen morgen noch steht oder ob wir es verschieben</p>";
5
6#[tokio::main]
7async fn main() {
8 let arguments: Vec<String> = std::env::args().skip(1).collect();
9 let action = match arguments.first().map(String::as_str) {
10 Some("proofread") => ComposeAction::Proofread,
11 Some("custom") => ComposeAction::Custom(arguments[1..].join(" ")),
12 Some(label) => Adjustment::ALL
13 .into_iter()
14 .find(|adjustment| adjustment.label().eq_ignore_ascii_case(label))
15 .map_or(ComposeAction::Rewrite, ComposeAction::Adjust),
16 None => ComposeAction::Rewrite,
17 };
18 let endpoint = std::env::var("CDP_ENDPOINT").unwrap_or_else(|_| DEFAULT_ENDPOINT.to_owned());
19 let session = Session::connect(&endpoint).await.expect("browser");
20 let organization = session
21 .request(
22 Method::Get,
23 "https://graph.microsoft.com/v1.0/organization?$select=id",
24 &Scope::graph("User.Read"),
25 None,
26 )
27 .await
28 .expect("organization");
29 let rewrite = ComposeRewrite {
30 tenant_id: organization.body["value"][0]["id"].as_str().expect("tenant id").to_owned(),
31 thread_id: "48:notes".to_owned(),
32 user_html: DRAFT.to_owned(),
33 action,
34 ui_language: "en-gb".to_owned(),
35 time_zone: "Europe/Berlin".to_owned(),
36 };
37 match ComposeCopilot::new(&session).rewrite(&rewrite).await {
38 Ok(answer) => println!("answer: {answer}"),
39 Err(error) => println!("error: {error}"),
40 }
41}
crates/chatsvc/src/compose_copilot.rs added +361 −0
@@ -0,0 +1,361 @@
1 use base64::Engine as _;
2 use serde_json::{Value, json};
3 use session::{AugloopExchange, AugloopStage, Request, Scope, Session};
4 use uuid::Uuid;
5
6 use crate::error::{Error, Result};
7
8 const AUGLOOP_URL: &str = "wss://augloop.office.com/";
9 const AUGLOOP_RESOURCE: &str = "https://augloop.office.com/v2";
10 const AUGLOOP_SCOPE: &str = ".default";
11 const TOKEN_PLACEHOLDER: &str = "@@augloop-token@@";
12 const DONE_MARKER: &str = "\"isCompleted\":true";
13 const ANSWER_TIMEOUT_MS: u64 = 55_000;
14 const KEEPALIVE_MS: u64 = 30_000;
15 const RUNTIME_VERSION: &str = "2.37.2676";
16 const DOCUMENT_ID: &str = "doc";
17 const INIT_MESSAGE_ID: &str = "c1";
18 const SEED_MESSAGE_ID: &str = "c2";
19 const ANNOTATION_TYPE: &str = "AugLoop_TeamsCopilot_TeamsCopilotComposeRewriteStreamingAnnotation";
20 const SIGNAL_TYPE: &str = "AugLoop_TeamsCopilot_TeamsCopilotComposeRewriteSignal";
21 const FLIGHTS: &str = "Microsoft.Teams.Augloop.EnableSendSubstrateEvents:true;Microsoft.Teams.Augloop.AllowPartialResults:true;Microsoft.Teams.Augloop.DefaultModelOverride:GPT41_ShortCo_0414;Microsoft.Teams.Augloop.FLIGHT_OMNI_MIGRATION:true;Microsoft.Teams.Augloop.EnableCopilotOrTeamsPremiumLicenseAggregation:true;Microsoft.Teams.Augloop.RingInfo:general;Microsoft.Teams.Augloop.EnableTeamsAuthSvcLicensingChecks:true;_acceptsClaimsChallengeMessages;_acceptsSeedingStatusChangeMessages";
22
23 const DEFAULT_TONE: &str = "default";
24 const PROOFREAD_TONE: &str = "PROOFREAD_SCENARIO";
25 const MEDIUM_LENGTH: &str = "medium";
26
27 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
28 pub enum Adjustment {
29 Concise,
30 Longer,
31 Casual,
32 Professional,
33 Confident,
34 Enthusiastic,
35 }
36
37 impl Adjustment {
38 pub const ALL: [Adjustment; 6] = [
39 Adjustment::Concise,
40 Adjustment::Longer,
41 Adjustment::Casual,
42 Adjustment::Professional,
43 Adjustment::Confident,
44 Adjustment::Enthusiastic,
45 ];
46
47 pub fn label(self) -> &'static str {
48 match self {
49 Adjustment::Concise => "Concise",
50 Adjustment::Longer => "Longer",
51 Adjustment::Casual => "Casual",
52 Adjustment::Professional => "Professional",
53 Adjustment::Confident => "Confident",
54 Adjustment::Enthusiastic => "Enthusiastic",
55 }
56 }
57 }
58
59 /// The "Write with Copilot" choices with the tone and length Teams sends for each.
60 #[derive(Debug, Clone, PartialEq, Eq)]
61 pub enum ComposeAction {
62 Rewrite,
63 Proofread,
64 Adjust(Adjustment),
65 Custom(String),
66 }
67
68 impl ComposeAction {
69 pub fn tone(&self) -> &'static str {
70 match self {
71 ComposeAction::Proofread => PROOFREAD_TONE,
72 ComposeAction::Adjust(Adjustment::Casual) => "casual",
73 ComposeAction::Adjust(Adjustment::Professional) => "professional",
74 ComposeAction::Adjust(Adjustment::Confident) => "confident",
75 ComposeAction::Adjust(Adjustment::Enthusiastic) => "enthusiastic",
76 _ => DEFAULT_TONE,
77 }
78 }
79
80 pub fn length(&self) -> &'static str {
81 match self {
82 ComposeAction::Adjust(Adjustment::Concise) => "short",
83 ComposeAction::Adjust(Adjustment::Longer) => "long",
84 _ => MEDIUM_LENGTH,
85 }
86 }
87
88 pub fn label(&self) -> &str {
89 match self {
90 ComposeAction::Rewrite => "Rewrite",
91 ComposeAction::Proofread => "Proofread",
92 ComposeAction::Adjust(adjustment) => adjustment.label(),
93 ComposeAction::Custom(prompt) => prompt,
94 }
95 }
96 }
97
98 #[derive(Debug, Clone, PartialEq, Eq)]
99 pub struct ComposeRewrite {
100 pub tenant_id: String,
101 pub thread_id: String,
102 pub user_html: String,
103 pub action: ComposeAction,
104 pub ui_language: String,
105 pub time_zone: String,
106 }
107
108 pub struct ComposeCopilot {
109 session: Session,
110 }
111
112 impl ComposeCopilot {
113 pub fn new(session: &Session) -> Self {
114 ComposeCopilot {
115 session: session.clone(),
116 }
117 }
118
119 pub async fn rewrite(&self, rewrite: &ComposeRewrite) -> Result<String> {
120 let request = Request::augloop(AUGLOOP_URL, exchange(rewrite, &Uuid::new_v4().to_string()));
121 let response = self
122 .session
123 .send(request, &Scope::new(AUGLOOP_RESOURCE, AUGLOOP_SCOPE))
124 .await?;
125 answer_of(&response.body)
126 }
127 }
128
129 fn correlation_vector() -> String {
130 base64::engine::general_purpose::STANDARD_NO_PAD.encode(Uuid::new_v4().as_bytes())
131 }
132
133 fn header(type_name: &str, base_types: &[&str]) -> Value {
134 json!({"T_": type_name, "B_": base_types})
135 }
136
137 pub fn exchange(rewrite: &ComposeRewrite, session_id: &str) -> AugloopExchange {
138 let vector = correlation_vector();
139 let init = json!({
140 "protocolVersion": 2,
141 "clientMetadata": {
142 "appName": "Teams",
143 "appPlatform": "Web",
144 "uiLanguage": rewrite.ui_language,
145 "flights": FLIGHTS,
146 "releaseAudienceGroup": "Production",
147 "releaseChannel": "general",
148 "sessionId": session_id,
149 "runtimeVersion": RUNTIME_VERSION,
150 "docSessionId": Uuid::new_v4().to_string(),
151 "userSystemTimezone": rewrite.time_zone,
152 },
153 "extensionConfigs": [],
154 "returnWorkflowInputTypes": true,
155 "enableRemoteExecutionNotification": false,
156 "createBlobStorageContainer": false,
157 "H_": header("AugLoop_Session_Protocol_SessionInitMessage", &["AugLoop_Session_Protocol_Message"]),
158 "cv": format!("{vector}.1"),
159 "messageId": INIT_MESSAGE_ID,
160 });
161 let seed = json!({
162 "cv": correlation_vector(),
163 "seq": 0,
164 "ops": [{
165 "parentPath": ["session"],
166 "items": [{"id": DOCUMENT_ID, "body": {
167 "isReadonly": false,
168 "H_": header("AugLoop_Core_Document", &["AugLoop_Core_TileGroup"]),
169 }}],
170 "H_": add_operation_header(),
171 }],
172 "groupId": "Seed",
173 "groupSize": 1,
174 "groupComplete": true,
175 "H_": header("AugLoop_Session_Protocol_SyncMessage", &["AugLoop_Session_Protocol_Message"]),
176 "messageId": SEED_MESSAGE_ID,
177 });
178 let activation = json!({
179 "annotationType": ANNOTATION_TYPE,
180 "token": format!("{ANNOTATION_TYPE}-0"),
181 "ignoreExistingAnnotations": false,
182 "returnAnnotationDoesNotExist": true,
183 "sendApologies": false,
184 "H_": header("AugLoop_Session_Protocol_AnnotationActivationMessage", &["AugLoop_Session_Protocol_Message"]),
185 "cv": format!("{vector}.2"),
186 "messageId": "c3",
187 });
188 let token = json!({
189 "authToken": TOKEN_PLACEHOLDER,
190 "version": 1,
191 "H_": header("AugLoop_Session_Protocol_TokenProvisionMessage", &["AugLoop_Session_Protocol_Message"]),
192 "cv": format!("{vector}.3"),
193 "messageId": "c4",
194 });
195 AugloopExchange {
196 stages: vec![
197 AugloopStage {
198 send: vec![init.to_string()],
199 await_message_id: Some(INIT_MESSAGE_ID.to_owned()),
200 },
201 AugloopStage {
202 send: vec![seed.to_string(), activation.to_string(), token.to_string()],
203 await_message_id: Some(SEED_MESSAGE_ID.to_owned()),
204 },
205 AugloopStage {
206 send: vec![signal(rewrite).to_string()],
207 await_message_id: None,
208 },
209 ],
210 placeholder: TOKEN_PLACEHOLDER.to_owned(),
211 done_marker: DONE_MARKER.to_owned(),
212 timeout_ms: ANSWER_TIMEOUT_MS,
213 keepalive_ms: KEEPALIVE_MS,
214 }
215 }
216
217 fn add_operation_header() -> Value {
218 header(
219 "AugLoop_Core_AddOperation",
220 &["AugLoop_Core_OperationWithSiblingContext", "AugLoop_Core_Operation"],
221 )
222 }
223
224 pub fn signal(rewrite: &ComposeRewrite) -> Value {
225 let mut body = json!({
226 "userText": rewrite.user_html,
227 "tone": rewrite.action.tone(),
228 "length": rewrite.action.length(),
229 "requestContext": {
230 "threadId": rewrite.thread_id,
231 "contextType": "Chat",
232 "tenantId": rewrite.tenant_id,
233 },
234 "streamResponse": true,
235 "H_": header(SIGNAL_TYPE, &["AugLoop_TeamsCopilot_TeamsCopilotBaseSignal", "AugLoop_Signals_Signal"]),
236 });
237 if let ComposeAction::Custom(prompt) = &rewrite.action {
238 body["customPrompt"] = json!(prompt);
239 }
240 json!({
241 "cv": correlation_vector(),
242 "seq": 1,
243 "ops": [{
244 "parentPath": [
245 "session",
246 DOCUMENT_ID,
247 format!("teams_compose_copilot_streaming_{}", Uuid::new_v4()),
248 Uuid::new_v4().to_string(),
249 ],
250 "items": [{"id": Uuid::new_v4().to_string(), "body": body, "contextId": "C1"}],
251 "H_": add_operation_header(),
252 }],
253 "H_": header("AugLoop_Session_Protocol_SyncMessage", &["AugLoop_Session_Protocol_Message"]),
254 "messageId": "c5",
255 })
256 }
257
258 fn annotation_bodies(received: &Value) -> impl Iterator<Item = &Value> {
259 received
260 .as_array()
261 .into_iter()
262 .flatten()
263 .filter(|message| message["annotationType"] == ANNOTATION_TYPE)
264 .flat_map(|message| message["ops"].as_array().into_iter().flatten())
265 .flat_map(|operation| operation["items"].as_array().into_iter().flatten())
266 .map(|item| &item["body"])
267 }
268
269 pub fn answer_of(received: &Value) -> Result<String> {
270 let completed = annotation_bodies(received).find(|body| body["isCompleted"] == true);
271 let Some(body) = completed else {
272 return Err(Error::UnexpectedAnswer(failure_reason(received)));
273 };
274 if body["status"].as_i64().unwrap_or(0) != 0 {
275 return Err(Error::UnexpectedAnswer(format!("Copilot status {}", body["status"])));
276 }
277 body["answer"]
278 .as_str()
279 .map(str::trim)
280 .filter(|answer| !answer.is_empty())
281 .map(str::to_owned)
282 .ok_or_else(|| Error::UnexpectedAnswer("Copilot gave no answer".to_owned()))
283 }
284
285 fn failure_reason(received: &Value) -> String {
286 received
287 .as_array()
288 .into_iter()
289 .flatten()
290 .find_map(|message| message["error"].as_str().map(str::to_owned))
291 .unwrap_or_else(|| "Copilot did not answer".to_owned())
292 }
293
294 #[cfg(test)]
295 mod tests {
296 use super::*;
297
298 fn rewrite() -> ComposeRewrite {
299 ComposeRewrite {
300 tenant_id: "tenant-1".into(),
301 thread_id: "19:chat@thread.v2".into(),
302 user_html: "<p>hallo</p>".into(),
303 action: ComposeAction::Rewrite,
304 ui_language: "en-gb".into(),
305 time_zone: "Europe/Berlin".into(),
306 }
307 }
308
309 #[test]
310 fn stages_init_then_seed_with_token_then_signal() {
311 let exchange = exchange(&rewrite(), "session-1");
312 assert_eq!(exchange.stages.len(), 3);
313 assert_eq!(exchange.stages[0].await_message_id.as_deref(), Some("c1"));
314 let init: Value = serde_json::from_str(&exchange.stages[0].send[0]).unwrap();
315 assert_eq!(init["clientMetadata"]["sessionId"], "session-1");
316 let token: Value = serde_json::from_str(&exchange.stages[1].send[2]).unwrap();
317 assert_eq!(token["authToken"], TOKEN_PLACEHOLDER);
318 let signal: Value = serde_json::from_str(&exchange.stages[2].send[0]).unwrap();
319 let body = &signal["ops"][0]["items"][0]["body"];
320 assert_eq!(body["userText"], "<p>hallo</p>");
321 assert_eq!(body["requestContext"]["threadId"], "19:chat@thread.v2");
322 assert_eq!((body["tone"].as_str(), body["length"].as_str()), (Some("default"), Some("medium")));
323 assert!(body.get("customPrompt").is_none());
324 }
325
326 #[test]
327 fn actions_send_the_tone_and_length_teams_sends() {
328 let sent = |action: ComposeAction| {
329 let body = signal(&ComposeRewrite { action, ..rewrite() })["ops"][0]["items"][0]["body"].clone();
330 (body["tone"].as_str().unwrap().to_owned(), body["length"].as_str().unwrap().to_owned(), body.get("customPrompt").cloned())
331 };
332 assert_eq!(sent(ComposeAction::Proofread), ("PROOFREAD_SCENARIO".into(), "medium".into(), None));
333 assert_eq!(sent(ComposeAction::Adjust(Adjustment::Concise)), ("default".into(), "short".into(), None));
334 assert_eq!(sent(ComposeAction::Adjust(Adjustment::Longer)), ("default".into(), "long".into(), None));
335 assert_eq!(sent(ComposeAction::Adjust(Adjustment::Confident)), ("confident".into(), "medium".into(), None));
336 assert_eq!(
337 sent(ComposeAction::Custom("as a haiku".into())),
338 ("default".into(), "medium".into(), Some(json!("as a haiku")))
339 );
340 }
341
342 #[test]
343 fn the_completed_annotation_carries_the_answer() {
344 let part = |body: Value| json!({"annotationType": ANNOTATION_TYPE, "ops": [{"items": [{"body": body}]}]});
345 let received = json!([
346 {"messageId": "c1"},
347 part(json!({"answerPart": "<p>Hallo", "isCompleted": false})),
348 part(json!({"status": 0, "answerPart": "", "answer": "<p>Hallo zusammen</p>", "isCompleted": true})),
349 ]);
350 assert_eq!(answer_of(&received).unwrap(), "<p>Hallo zusammen</p>");
351 }
352
353 #[test]
354 fn a_missing_answer_reports_the_socket_error() {
355 let received = json!([{"messageId": "c1", "error": "Unauthorized"}]);
356 assert_eq!(
357 answer_of(&received).unwrap_err().to_string(),
358 "unexpected service answer: Unauthorized"
359 );
360 }
361 }
@@ -0,0 +1,361 @@
1use base64::Engine as _;
2use serde_json::{Value, json};
3use session::{AugloopExchange, AugloopStage, Request, Scope, Session};
4use uuid::Uuid;
5
6use crate::error::{Error, Result};
7
8const AUGLOOP_URL: &str = "wss://augloop.office.com/";
9const AUGLOOP_RESOURCE: &str = "https://augloop.office.com/v2";
10const AUGLOOP_SCOPE: &str = ".default";
11const TOKEN_PLACEHOLDER: &str = "@@augloop-token@@";
12const DONE_MARKER: &str = "\"isCompleted\":true";
13const ANSWER_TIMEOUT_MS: u64 = 55_000;
14const KEEPALIVE_MS: u64 = 30_000;
15const RUNTIME_VERSION: &str = "2.37.2676";
16const DOCUMENT_ID: &str = "doc";
17const INIT_MESSAGE_ID: &str = "c1";
18const SEED_MESSAGE_ID: &str = "c2";
19const ANNOTATION_TYPE: &str = "AugLoop_TeamsCopilot_TeamsCopilotComposeRewriteStreamingAnnotation";
20const SIGNAL_TYPE: &str = "AugLoop_TeamsCopilot_TeamsCopilotComposeRewriteSignal";
21const FLIGHTS: &str = "Microsoft.Teams.Augloop.EnableSendSubstrateEvents:true;Microsoft.Teams.Augloop.AllowPartialResults:true;Microsoft.Teams.Augloop.DefaultModelOverride:GPT41_ShortCo_0414;Microsoft.Teams.Augloop.FLIGHT_OMNI_MIGRATION:true;Microsoft.Teams.Augloop.EnableCopilotOrTeamsPremiumLicenseAggregation:true;Microsoft.Teams.Augloop.RingInfo:general;Microsoft.Teams.Augloop.EnableTeamsAuthSvcLicensingChecks:true;_acceptsClaimsChallengeMessages;_acceptsSeedingStatusChangeMessages";
22
23const DEFAULT_TONE: &str = "default";
24const PROOFREAD_TONE: &str = "PROOFREAD_SCENARIO";
25const MEDIUM_LENGTH: &str = "medium";
26
27#[derive(Debug, Clone, Copy, PartialEq, Eq)]
28pub enum Adjustment {
29 Concise,
30 Longer,
31 Casual,
32 Professional,
33 Confident,
34 Enthusiastic,
35}
36
37impl Adjustment {
38 pub const ALL: [Adjustment; 6] = [
39 Adjustment::Concise,
40 Adjustment::Longer,
41 Adjustment::Casual,
42 Adjustment::Professional,
43 Adjustment::Confident,
44 Adjustment::Enthusiastic,
45 ];
46
47 pub fn label(self) -> &'static str {
48 match self {
49 Adjustment::Concise => "Concise",
50 Adjustment::Longer => "Longer",
51 Adjustment::Casual => "Casual",
52 Adjustment::Professional => "Professional",
53 Adjustment::Confident => "Confident",
54 Adjustment::Enthusiastic => "Enthusiastic",
55 }
56 }
57}
58
59/// The "Write with Copilot" choices with the tone and length Teams sends for each.
60#[derive(Debug, Clone, PartialEq, Eq)]
61pub enum ComposeAction {
62 Rewrite,
63 Proofread,
64 Adjust(Adjustment),
65 Custom(String),
66}
67
68impl ComposeAction {
69 pub fn tone(&self) -> &'static str {
70 match self {
71 ComposeAction::Proofread => PROOFREAD_TONE,
72 ComposeAction::Adjust(Adjustment::Casual) => "casual",
73 ComposeAction::Adjust(Adjustment::Professional) => "professional",
74 ComposeAction::Adjust(Adjustment::Confident) => "confident",
75 ComposeAction::Adjust(Adjustment::Enthusiastic) => "enthusiastic",
76 _ => DEFAULT_TONE,
77 }
78 }
79
80 pub fn length(&self) -> &'static str {
81 match self {
82 ComposeAction::Adjust(Adjustment::Concise) => "short",
83 ComposeAction::Adjust(Adjustment::Longer) => "long",
84 _ => MEDIUM_LENGTH,
85 }
86 }
87
88 pub fn label(&self) -> &str {
89 match self {
90 ComposeAction::Rewrite => "Rewrite",
91 ComposeAction::Proofread => "Proofread",
92 ComposeAction::Adjust(adjustment) => adjustment.label(),
93 ComposeAction::Custom(prompt) => prompt,
94 }
95 }
96}
97
98#[derive(Debug, Clone, PartialEq, Eq)]
99pub struct ComposeRewrite {
100 pub tenant_id: String,
101 pub thread_id: String,
102 pub user_html: String,
103 pub action: ComposeAction,
104 pub ui_language: String,
105 pub time_zone: String,
106}
107
108pub struct ComposeCopilot {
109 session: Session,
110}
111
112impl ComposeCopilot {
113 pub fn new(session: &Session) -> Self {
114 ComposeCopilot {
115 session: session.clone(),
116 }
117 }
118
119 pub async fn rewrite(&self, rewrite: &ComposeRewrite) -> Result<String> {
120 let request = Request::augloop(AUGLOOP_URL, exchange(rewrite, &Uuid::new_v4().to_string()));
121 let response = self
122 .session
123 .send(request, &Scope::new(AUGLOOP_RESOURCE, AUGLOOP_SCOPE))
124 .await?;
125 answer_of(&response.body)
126 }
127}
128
129fn correlation_vector() -> String {
130 base64::engine::general_purpose::STANDARD_NO_PAD.encode(Uuid::new_v4().as_bytes())
131}
132
133fn header(type_name: &str, base_types: &[&str]) -> Value {
134 json!({"T_": type_name, "B_": base_types})
135}
136
137pub fn exchange(rewrite: &ComposeRewrite, session_id: &str) -> AugloopExchange {
138 let vector = correlation_vector();
139 let init = json!({
140 "protocolVersion": 2,
141 "clientMetadata": {
142 "appName": "Teams",
143 "appPlatform": "Web",
144 "uiLanguage": rewrite.ui_language,
145 "flights": FLIGHTS,
146 "releaseAudienceGroup": "Production",
147 "releaseChannel": "general",
148 "sessionId": session_id,
149 "runtimeVersion": RUNTIME_VERSION,
150 "docSessionId": Uuid::new_v4().to_string(),
151 "userSystemTimezone": rewrite.time_zone,
152 },
153 "extensionConfigs": [],
154 "returnWorkflowInputTypes": true,
155 "enableRemoteExecutionNotification": false,
156 "createBlobStorageContainer": false,
157 "H_": header("AugLoop_Session_Protocol_SessionInitMessage", &["AugLoop_Session_Protocol_Message"]),
158 "cv": format!("{vector}.1"),
159 "messageId": INIT_MESSAGE_ID,
160 });
161 let seed = json!({
162 "cv": correlation_vector(),
163 "seq": 0,
164 "ops": [{
165 "parentPath": ["session"],
166 "items": [{"id": DOCUMENT_ID, "body": {
167 "isReadonly": false,
168 "H_": header("AugLoop_Core_Document", &["AugLoop_Core_TileGroup"]),
169 }}],
170 "H_": add_operation_header(),
171 }],
172 "groupId": "Seed",
173 "groupSize": 1,
174 "groupComplete": true,
175 "H_": header("AugLoop_Session_Protocol_SyncMessage", &["AugLoop_Session_Protocol_Message"]),
176 "messageId": SEED_MESSAGE_ID,
177 });
178 let activation = json!({
179 "annotationType": ANNOTATION_TYPE,
180 "token": format!("{ANNOTATION_TYPE}-0"),
181 "ignoreExistingAnnotations": false,
182 "returnAnnotationDoesNotExist": true,
183 "sendApologies": false,
184 "H_": header("AugLoop_Session_Protocol_AnnotationActivationMessage", &["AugLoop_Session_Protocol_Message"]),
185 "cv": format!("{vector}.2"),
186 "messageId": "c3",
187 });
188 let token = json!({
189 "authToken": TOKEN_PLACEHOLDER,
190 "version": 1,
191 "H_": header("AugLoop_Session_Protocol_TokenProvisionMessage", &["AugLoop_Session_Protocol_Message"]),
192 "cv": format!("{vector}.3"),
193 "messageId": "c4",
194 });
195 AugloopExchange {
196 stages: vec![
197 AugloopStage {
198 send: vec![init.to_string()],
199 await_message_id: Some(INIT_MESSAGE_ID.to_owned()),
200 },
201 AugloopStage {
202 send: vec![seed.to_string(), activation.to_string(), token.to_string()],
203 await_message_id: Some(SEED_MESSAGE_ID.to_owned()),
204 },
205 AugloopStage {
206 send: vec![signal(rewrite).to_string()],
207 await_message_id: None,
208 },
209 ],
210 placeholder: TOKEN_PLACEHOLDER.to_owned(),
211 done_marker: DONE_MARKER.to_owned(),
212 timeout_ms: ANSWER_TIMEOUT_MS,
213 keepalive_ms: KEEPALIVE_MS,
214 }
215}
216
217fn add_operation_header() -> Value {
218 header(
219 "AugLoop_Core_AddOperation",
220 &["AugLoop_Core_OperationWithSiblingContext", "AugLoop_Core_Operation"],
221 )
222}
223
224pub fn signal(rewrite: &ComposeRewrite) -> Value {
225 let mut body = json!({
226 "userText": rewrite.user_html,
227 "tone": rewrite.action.tone(),
228 "length": rewrite.action.length(),
229 "requestContext": {
230 "threadId": rewrite.thread_id,
231 "contextType": "Chat",
232 "tenantId": rewrite.tenant_id,
233 },
234 "streamResponse": true,
235 "H_": header(SIGNAL_TYPE, &["AugLoop_TeamsCopilot_TeamsCopilotBaseSignal", "AugLoop_Signals_Signal"]),
236 });
237 if let ComposeAction::Custom(prompt) = &rewrite.action {
238 body["customPrompt"] = json!(prompt);
239 }
240 json!({
241 "cv": correlation_vector(),
242 "seq": 1,
243 "ops": [{
244 "parentPath": [
245 "session",
246 DOCUMENT_ID,
247 format!("teams_compose_copilot_streaming_{}", Uuid::new_v4()),
248 Uuid::new_v4().to_string(),
249 ],
250 "items": [{"id": Uuid::new_v4().to_string(), "body": body, "contextId": "C1"}],
251 "H_": add_operation_header(),
252 }],
253 "H_": header("AugLoop_Session_Protocol_SyncMessage", &["AugLoop_Session_Protocol_Message"]),
254 "messageId": "c5",
255 })
256}
257
258fn annotation_bodies(received: &Value) -> impl Iterator<Item = &Value> {
259 received
260 .as_array()
261 .into_iter()
262 .flatten()
263 .filter(|message| message["annotationType"] == ANNOTATION_TYPE)
264 .flat_map(|message| message["ops"].as_array().into_iter().flatten())
265 .flat_map(|operation| operation["items"].as_array().into_iter().flatten())
266 .map(|item| &item["body"])
267}
268
269pub fn answer_of(received: &Value) -> Result<String> {
270 let completed = annotation_bodies(received).find(|body| body["isCompleted"] == true);
271 let Some(body) = completed else {
272 return Err(Error::UnexpectedAnswer(failure_reason(received)));
273 };
274 if body["status"].as_i64().unwrap_or(0) != 0 {
275 return Err(Error::UnexpectedAnswer(format!("Copilot status {}", body["status"])));
276 }
277 body["answer"]
278 .as_str()
279 .map(str::trim)
280 .filter(|answer| !answer.is_empty())
281 .map(str::to_owned)
282 .ok_or_else(|| Error::UnexpectedAnswer("Copilot gave no answer".to_owned()))
283}
284
285fn failure_reason(received: &Value) -> String {
286 received
287 .as_array()
288 .into_iter()
289 .flatten()
290 .find_map(|message| message["error"].as_str().map(str::to_owned))
291 .unwrap_or_else(|| "Copilot did not answer".to_owned())
292}
293
294#[cfg(test)]
295mod tests {
296 use super::*;
297
298 fn rewrite() -> ComposeRewrite {
299 ComposeRewrite {
300 tenant_id: "tenant-1".into(),
301 thread_id: "19:chat@thread.v2".into(),
302 user_html: "<p>hallo</p>".into(),
303 action: ComposeAction::Rewrite,
304 ui_language: "en-gb".into(),
305 time_zone: "Europe/Berlin".into(),
306 }
307 }
308
309 #[test]
310 fn stages_init_then_seed_with_token_then_signal() {
311 let exchange = exchange(&rewrite(), "session-1");
312 assert_eq!(exchange.stages.len(), 3);
313 assert_eq!(exchange.stages[0].await_message_id.as_deref(), Some("c1"));
314 let init: Value = serde_json::from_str(&exchange.stages[0].send[0]).unwrap();
315 assert_eq!(init["clientMetadata"]["sessionId"], "session-1");
316 let token: Value = serde_json::from_str(&exchange.stages[1].send[2]).unwrap();
317 assert_eq!(token["authToken"], TOKEN_PLACEHOLDER);
318 let signal: Value = serde_json::from_str(&exchange.stages[2].send[0]).unwrap();
319 let body = &signal["ops"][0]["items"][0]["body"];
320 assert_eq!(body["userText"], "<p>hallo</p>");
321 assert_eq!(body["requestContext"]["threadId"], "19:chat@thread.v2");
322 assert_eq!((body["tone"].as_str(), body["length"].as_str()), (Some("default"), Some("medium")));
323 assert!(body.get("customPrompt").is_none());
324 }
325
326 #[test]
327 fn actions_send_the_tone_and_length_teams_sends() {
328 let sent = |action: ComposeAction| {
329 let body = signal(&ComposeRewrite { action, ..rewrite() })["ops"][0]["items"][0]["body"].clone();
330 (body["tone"].as_str().unwrap().to_owned(), body["length"].as_str().unwrap().to_owned(), body.get("customPrompt").cloned())
331 };
332 assert_eq!(sent(ComposeAction::Proofread), ("PROOFREAD_SCENARIO".into(), "medium".into(), None));
333 assert_eq!(sent(ComposeAction::Adjust(Adjustment::Concise)), ("default".into(), "short".into(), None));
334 assert_eq!(sent(ComposeAction::Adjust(Adjustment::Longer)), ("default".into(), "long".into(), None));
335 assert_eq!(sent(ComposeAction::Adjust(Adjustment::Confident)), ("confident".into(), "medium".into(), None));
336 assert_eq!(
337 sent(ComposeAction::Custom("as a haiku".into())),
338 ("default".into(), "medium".into(), Some(json!("as a haiku")))
339 );
340 }
341
342 #[test]
343 fn the_completed_annotation_carries_the_answer() {
344 let part = |body: Value| json!({"annotationType": ANNOTATION_TYPE, "ops": [{"items": [{"body": body}]}]});
345 let received = json!([
346 {"messageId": "c1"},
347 part(json!({"answerPart": "<p>Hallo", "isCompleted": false})),
348 part(json!({"status": 0, "answerPart": "", "answer": "<p>Hallo zusammen</p>", "isCompleted": true})),
349 ]);
350 assert_eq!(answer_of(&received).unwrap(), "<p>Hallo zusammen</p>");
351 }
352
353 #[test]
354 fn a_missing_answer_reports_the_socket_error() {
355 let received = json!([{"messageId": "c1", "error": "Unauthorized"}]);
356 assert_eq!(
357 answer_of(&received).unwrap_err().to_string(),
358 "unexpected service answer: Unauthorized"
359 );
360 }
361}
crates/chatsvc/src/lib.rs +1 −0
@@ -10,6 +10,7 @@ pub mod chat_notifications;
10 10 pub mod chat_settings;
11 11 pub mod channel_visibility;
12 12 pub mod conversations;
13 pub mod compose_copilot;
13 14 pub mod copilot;
14 15 pub mod drafts;
15 16 pub mod emotions;
@@ -10,6 +10,7 @@ pub mod chat_notifications;
10pub mod chat_settings;
10pub mod chat_settings;
11pub mod channel_visibility;
11pub mod channel_visibility;
12pub mod conversations;
12pub mod conversations;
13pub mod compose_copilot;
13pub mod copilot;
14pub mod copilot;
14pub mod drafts;
15pub mod drafts;
15pub mod emotions;
16pub mod emotions;
crates/core/Cargo.toml +1 −0
@@ -11,6 +11,7 @@ name = "teams_core"
11 11 [dependencies]
12 12 chatsvc.workspace = true
13 13 chrono.workspace = true
14 iana-time-zone = "0.1"
14 15 futures-util.workspace = true
15 16 graph.workspace = true
16 17 percent-encoding.workspace = true
@@ -11,6 +11,7 @@ name = "teams_core"
11[dependencies]
11[dependencies]
12chatsvc.workspace = true
12chatsvc.workspace = true
13chrono.workspace = true
13chrono.workspace = true
14iana-time-zone = "0.1"
14futures-util.workspace = true
15futures-util.workspace = true
15graph.workspace = true
16graph.workspace = true
16percent-encoding.workspace = true
17percent-encoding.workspace = true
crates/core/src/copilot.rs +15 −0
@@ -1,3 +1,4 @@
1 use chatsvc::compose_copilot::{ComposeAction, ComposeRewrite};
1 2 use chatsvc::copilot::CopilotAsk;
2 3 use chrono::Local;
3 4
@@ -7,6 +8,7 @@ use crate::remote::Remote;
7 8
8 9 const COPILOT_LOCALE: &str = "en-us";
9 10 const SECONDS_PER_HOUR: i32 = 3600;
11 const FALLBACK_TIME_ZONE: &str = "UTC";
10 12
11 13 impl<R: Remote> SyncEngine<R> {
12 14 pub async fn ask_copilot(&self, chat_id: &str, prompt: &str) -> Result<String> {
@@ -20,4 +22,17 @@ impl<R: Remote> SyncEngine<R> {
20 22 };
21 23 self.remote.ask_copilot(&ask).await
22 24 }
25
26 /// Copilot's proposal for the draft as Teams HTML; the draft itself stays untouched.
27 pub async fn rewrite_draft(&self, chat_id: &str, user_html: &str, action: ComposeAction) -> Result<String> {
28 let rewrite = ComposeRewrite {
29 tenant_id: self.my_tenant_id(chat_id).await?,
30 thread_id: chat_id.to_owned(),
31 user_html: user_html.to_owned(),
32 action,
33 ui_language: COPILOT_LOCALE.to_owned(),
34 time_zone: iana_time_zone::get_timezone().unwrap_or_else(|_| FALLBACK_TIME_ZONE.to_owned()),
35 };
36 self.remote.rewrite_draft(&rewrite).await
37 }
23 38 }
@@ -1,3 +1,4 @@
1use chatsvc::compose_copilot::{ComposeAction, ComposeRewrite};
1use chatsvc::copilot::CopilotAsk;
2use chatsvc::copilot::CopilotAsk;
2use chrono::Local;
3use chrono::Local;
3
4
@@ -7,6 +8,7 @@ use crate::remote::Remote;
7
8
8const COPILOT_LOCALE: &str = "en-us";
9const COPILOT_LOCALE: &str = "en-us";
9const SECONDS_PER_HOUR: i32 = 3600;
10const SECONDS_PER_HOUR: i32 = 3600;
11const FALLBACK_TIME_ZONE: &str = "UTC";
10
12
11impl<R: Remote> SyncEngine<R> {
13impl<R: Remote> SyncEngine<R> {
12 pub async fn ask_copilot(&self, chat_id: &str, prompt: &str) -> Result<String> {
14 pub async fn ask_copilot(&self, chat_id: &str, prompt: &str) -> Result<String> {
@@ -20,4 +22,17 @@ impl<R: Remote> SyncEngine<R> {
20 };
22 };
21 self.remote.ask_copilot(&ask).await
23 self.remote.ask_copilot(&ask).await
22 }
24 }
25
26 /// Copilot's proposal for the draft as Teams HTML; the draft itself stays untouched.
27 pub async fn rewrite_draft(&self, chat_id: &str, user_html: &str, action: ComposeAction) -> Result<String> {
28 let rewrite = ComposeRewrite {
29 tenant_id: self.my_tenant_id(chat_id).await?,
30 thread_id: chat_id.to_owned(),
31 user_html: user_html.to_owned(),
32 action,
33 ui_language: COPILOT_LOCALE.to_owned(),
34 time_zone: iana_time_zone::get_timezone().unwrap_or_else(|_| FALLBACK_TIME_ZONE.to_owned()),
35 };
36 self.remote.rewrite_draft(&rewrite).await
37 }
23}
38}
crates/core/src/lib.rs +1 −0
@@ -113,6 +113,7 @@ pub use card_widgets::{
113 113 };
114 114 pub use card_width::{TargetWidth, WidthClass};
115 115 pub use chatsvc::substrate_search;
116 pub use chatsvc::compose_copilot::{Adjustment as ComposeAdjustment, ComposeAction};
116 117 pub use chatsvc::{
117 118 CallDirection, CallLogEntry, CallOutcome, ChatApp, ForcedAvailability, ForcedKind,
118 119 ForwardResult, Gif, PinnedMessage, PostFollowState, PresenceStatus, SavedMessage, ScheduledDraft, StatusNote,
@@ -113,6 +113,7 @@ pub use card_widgets::{
113};
113};
114pub use card_width::{TargetWidth, WidthClass};
114pub use card_width::{TargetWidth, WidthClass};
115pub use chatsvc::substrate_search;
115pub use chatsvc::substrate_search;
116pub use chatsvc::compose_copilot::{Adjustment as ComposeAdjustment, ComposeAction};
116pub use chatsvc::{
117pub use chatsvc::{
117 CallDirection, CallLogEntry, CallOutcome, ChatApp, ForcedAvailability, ForcedKind,
118 CallDirection, CallLogEntry, CallOutcome, ChatApp, ForcedAvailability, ForcedKind,
118 ForwardResult, Gif, PinnedMessage, PostFollowState, PresenceStatus, SavedMessage, ScheduledDraft, StatusNote,
119 ForwardResult, Gif, PinnedMessage, PostFollowState, PresenceStatus, SavedMessage, ScheduledDraft, StatusNote,
crates/core/src/remote.rs +9 −0
@@ -1,5 +1,6 @@
1 1 use std::collections::HashMap;
2 2
3 use chatsvc::compose_copilot::{ComposeCopilot, ComposeRewrite};
3 4 use chatsvc::copilot::{Copilot, CopilotAsk};
4 5 use chatsvc::sound_settings::{SoundSettings, SoundSettingsClient};
5 6 use chatsvc::substrate_search::{
@@ -515,6 +516,10 @@ pub trait Remote {
515 516 Err(Error::Unsupported("Copilot"))
516 517 }
517 518
519 async fn rewrite_draft(&self, _rewrite: &ComposeRewrite) -> Result<String> {
520 Err(Error::Unsupported("Copilot"))
521 }
522
518 523 async fn translate_chat_messages(
519 524 &self,
520 525 _chat_id: &str,
@@ -1413,6 +1418,10 @@ impl Remote for Graph {
1413 1418 Ok(Copilot::new(self.session()).ask(ask).await?)
1414 1419 }
1415 1420
1421 async fn rewrite_draft(&self, rewrite: &ComposeRewrite) -> Result<String> {
1422 Ok(ComposeCopilot::new(self.session()).rewrite(rewrite).await?)
1423 }
1424
1416 1425 async fn translate_chat_messages(
1417 1426 &self,
1418 1427 chat_id: &str,
@@ -1,5 +1,6 @@
1use std::collections::HashMap;
1use std::collections::HashMap;
2
2
3use chatsvc::compose_copilot::{ComposeCopilot, ComposeRewrite};
3use chatsvc::copilot::{Copilot, CopilotAsk};
4use chatsvc::copilot::{Copilot, CopilotAsk};
4use chatsvc::sound_settings::{SoundSettings, SoundSettingsClient};
5use chatsvc::sound_settings::{SoundSettings, SoundSettingsClient};
5use chatsvc::substrate_search::{
6use chatsvc::substrate_search::{
@@ -515,6 +516,10 @@ pub trait Remote {
515 Err(Error::Unsupported("Copilot"))
516 Err(Error::Unsupported("Copilot"))
516 }
517 }
517
518
519 async fn rewrite_draft(&self, _rewrite: &ComposeRewrite) -> Result<String> {
520 Err(Error::Unsupported("Copilot"))
521 }
522
518 async fn translate_chat_messages(
523 async fn translate_chat_messages(
519 &self,
524 &self,
520 _chat_id: &str,
525 _chat_id: &str,
@@ -1413,6 +1418,10 @@ impl Remote for Graph {
1413 Ok(Copilot::new(self.session()).ask(ask).await?)
1418 Ok(Copilot::new(self.session()).ask(ask).await?)
1414 }
1419 }
1415
1420
1421 async fn rewrite_draft(&self, rewrite: &ComposeRewrite) -> Result<String> {
1422 Ok(ComposeCopilot::new(self.session()).rewrite(rewrite).await?)
1423 }
1424
1416 async fn translate_chat_messages(
1425 async fn translate_chat_messages(
1417 &self,
1426 &self,
1418 chat_id: &str,
1427 chat_id: &str,
crates/session/assets/fetch.js +47 −0
@@ -151,8 +151,55 @@
151 151 socket.onerror = () => finish(0);
152 152 socket.onclose = () => finish(received.length ? 200 : 0);
153 153 });
154 const converse = (request) => new Promise((resolve) => {
155 const {stages, placeholder, doneMarker, timeoutMs, keepaliveMs} = request.augloop;
156 const received = [];
157 let socket = null, settled = false, stage = 0, keepalive = null;
158 const finish = (status) => {
159 if (settled) return;
160 settled = true;
161 clearTimeout(timer);
162 clearInterval(keepalive);
163 try { socket && socket.close(); } catch (error) {}
164 resolve({status, body: received});
165 };
166 const timer = setTimeout(() => finish(504), timeoutMs);
167 const sendStage = () => {
168 for (const message of stages[stage].send) socket.send(message.split(placeholder).join(token));
169 };
170 try {
171 socket = new WebSocket(request.url);
172 } catch (error) {
173 clearTimeout(timer);
174 resolve({status: 0, body: String(error)});
175 return;
176 }
177 socket.onopen = () => {
178 socket.send('~');
179 keepalive = setInterval(() => socket.send('~'), keepaliveMs);
180 sendStage();
181 };
182 socket.onmessage = (event) => {
183 const text = String(event.data);
184 if (text === '~') return;
185 let message;
186 try { message = JSON.parse(text); } catch (error) { return; }
187 const messageId = String(message.messageId || '');
188 if (messageId.startsWith('s')) socket.send(JSON.stringify({H_: {T_: 'AugLoop_Session_Protocol_Response', B_: []}, messageId}));
189 received.push(message);
190 if (message.error) { finish(502); return; }
191 if (text.includes(doneMarker)) { finish(200); return; }
192 if (stage + 1 < stages.length && messageId === stages[stage].awaitMessageId) {
193 stage++;
194 sendStage();
195 }
196 };
197 socket.onerror = () => finish(0);
198 socket.onclose = () => finish(received.length ? 200 : 0);
199 });
154 200 const run = async (request) => {
155 201 if (request.signalr) return exchange(request);
202 if (request.augloop) return converse(request);
156 203 try {
157 204 let requestBody = request.body;
158 205 for (const extra of request.bodyTokens || []) {
@@ -151,8 +151,55 @@
151 socket.onerror = () => finish(0);
151 socket.onerror = () => finish(0);
152 socket.onclose = () => finish(received.length ? 200 : 0);
152 socket.onclose = () => finish(received.length ? 200 : 0);
153 });
153 });
154 const converse = (request) => new Promise((resolve) => {
155 const {stages, placeholder, doneMarker, timeoutMs, keepaliveMs} = request.augloop;
156 const received = [];
157 let socket = null, settled = false, stage = 0, keepalive = null;
158 const finish = (status) => {
159 if (settled) return;
160 settled = true;
161 clearTimeout(timer);
162 clearInterval(keepalive);
163 try { socket && socket.close(); } catch (error) {}
164 resolve({status, body: received});
165 };
166 const timer = setTimeout(() => finish(504), timeoutMs);
167 const sendStage = () => {
168 for (const message of stages[stage].send) socket.send(message.split(placeholder).join(token));
169 };
170 try {
171 socket = new WebSocket(request.url);
172 } catch (error) {
173 clearTimeout(timer);
174 resolve({status: 0, body: String(error)});
175 return;
176 }
177 socket.onopen = () => {
178 socket.send('~');
179 keepalive = setInterval(() => socket.send('~'), keepaliveMs);
180 sendStage();
181 };
182 socket.onmessage = (event) => {
183 const text = String(event.data);
184 if (text === '~') return;
185 let message;
186 try { message = JSON.parse(text); } catch (error) { return; }
187 const messageId = String(message.messageId || '');
188 if (messageId.startsWith('s')) socket.send(JSON.stringify({H_: {T_: 'AugLoop_Session_Protocol_Response', B_: []}, messageId}));
189 received.push(message);
190 if (message.error) { finish(502); return; }
191 if (text.includes(doneMarker)) { finish(200); return; }
192 if (stage + 1 < stages.length && messageId === stages[stage].awaitMessageId) {
193 stage++;
194 sendStage();
195 }
196 };
197 socket.onerror = () => finish(0);
198 socket.onclose = () => finish(received.length ? 200 : 0);
199 });
154 const run = async (request) => {
200 const run = async (request) => {
155 if (request.signalr) return exchange(request);
201 if (request.signalr) return exchange(request);
202 if (request.augloop) return converse(request);
156 try {
203 try {
157 let requestBody = request.body;
204 let requestBody = request.body;
158 for (const extra of request.bodyTokens || []) {
205 for (const extra of request.bodyTokens || []) {
crates/session/src/lib.rs +1 −1
@@ -12,7 +12,7 @@ pub use app::{App, Target, find_app_tab, has_login_tab, is_login_url};
12 12 pub use error::{Error, Result};
13 13 pub use events::{TabChannel, TabCommand, TabControl, TabEvent, TabEvents};
14 14 pub use page_script::token_acquirer_script;
15 pub use request::{ApiResponse, BodyToken, Method, Request, SignalrExchange};
15 pub use request::{ApiResponse, AugloopExchange, AugloopStage, BodyToken, Method, Request, SignalrExchange};
16 16 pub use scope::{GRAPH, IC3, NestedApp, OUTLOOK, PRESENCE, SPACES, Scope};
17 17 pub use session::{DEFAULT_ENDPOINT, Session, SessionConfig, TabHold};
18 18 pub use transport::{BoxFuture, CdpTransport, Diagnosis, OpenedTab, Transport};
@@ -12,7 +12,7 @@ pub use app::{App, Target, find_app_tab, has_login_tab, is_login_url};
12pub use error::{Error, Result};
12pub use error::{Error, Result};
13pub use events::{TabChannel, TabCommand, TabControl, TabEvent, TabEvents};
13pub use events::{TabChannel, TabCommand, TabControl, TabEvent, TabEvents};
14pub use page_script::token_acquirer_script;
14pub use page_script::token_acquirer_script;
15pub use request::{ApiResponse, BodyToken, Method, Request, SignalrExchange};
15pub use request::{ApiResponse, AugloopExchange, AugloopStage, BodyToken, Method, Request, SignalrExchange};
16pub use scope::{GRAPH, IC3, NestedApp, OUTLOOK, PRESENCE, SPACES, Scope};
16pub use scope::{GRAPH, IC3, NestedApp, OUTLOOK, PRESENCE, SPACES, Scope};
17pub use session::{DEFAULT_ENDPOINT, Session, SessionConfig, TabHold};
17pub use session::{DEFAULT_ENDPOINT, Session, SessionConfig, TabHold};
18pub use transport::{BoxFuture, CdpTransport, Diagnosis, OpenedTab, Transport};
18pub use transport::{BoxFuture, CdpTransport, Diagnosis, OpenedTab, Transport};
crates/session/src/request.rs +34 −0
@@ -41,6 +41,28 @@ pub struct SignalrExchange {
41 41 pub timeout_ms: u64,
42 42 }
43 43
44 #[derive(Debug, Clone, PartialEq, Eq, Serialize)]
45 pub struct AugloopStage {
46 pub send: Vec<String>,
47 #[serde(rename = "awaitMessageId")]
48 pub await_message_id: Option<String>,
49 }
50
51 /// An AugLoop conversation over a WebSocket opened in the page. Each stage is sent once the previous stage's
52 /// awaited answer arrives; `placeholder` in a message becomes the token. The answer body is every received message,
53 /// up to the first one containing `done_marker`.
54 #[derive(Debug, Clone, PartialEq, Eq, Serialize)]
55 pub struct AugloopExchange {
56 pub stages: Vec<AugloopStage>,
57 pub placeholder: String,
58 #[serde(rename = "doneMarker")]
59 pub done_marker: String,
60 #[serde(rename = "timeoutMs")]
61 pub timeout_ms: u64,
62 #[serde(rename = "keepaliveMs")]
63 pub keepalive_ms: u64,
64 }
65
44 66 #[derive(Debug, Clone)]
45 67 pub struct Request {
46 68 pub method: Method,
@@ -52,9 +74,17 @@ pub struct Request {
52 74 pub body_base64: Option<String>,
53 75 pub body_tokens: Vec<BodyToken>,
54 76 pub signalr: Option<SignalrExchange>,
77 pub augloop: Option<AugloopExchange>,
55 78 }
56 79
57 80 impl Request {
81 pub fn augloop(url: impl Into<String>, exchange: AugloopExchange) -> Self {
82 Request {
83 augloop: Some(exchange),
84 ..Request::get(url)
85 }
86 }
87
58 88 pub fn signalr(url: impl Into<String>, exchange: SignalrExchange) -> Self {
59 89 Request {
60 90 signalr: Some(exchange),
@@ -81,6 +111,7 @@ impl Request {
81 111 body_base64: None,
82 112 body_tokens: Vec::new(),
83 113 signalr: None,
114 augloop: None,
84 115 }
85 116 }
86 117
@@ -132,6 +163,7 @@ impl Request {
132 163 body_base64: None,
133 164 body_tokens: Vec::new(),
134 165 signalr: None,
166 augloop: None,
135 167 }
136 168 }
137 169 }
@@ -162,6 +194,7 @@ pub(crate) struct WireRequest<'a> {
162 194 #[serde(rename = "bodyTokens")]
163 195 pub body_tokens: &'a [BodyToken],
164 196 pub signalr: Option<&'a SignalrExchange>,
197 pub augloop: Option<&'a AugloopExchange>,
165 198 }
166 199
167 200 impl<'a> From<&'a Request> for WireRequest<'a> {
@@ -184,6 +217,7 @@ impl<'a> From<&'a Request> for WireRequest<'a> {
184 217 anonymous: request.anonymous,
185 218 body_tokens: &request.body_tokens,
186 219 signalr: request.signalr.as_ref(),
220 augloop: request.augloop.as_ref(),
187 221 }
188 222 }
189 223 }
@@ -41,6 +41,28 @@ pub struct SignalrExchange {
41 pub timeout_ms: u64,
41 pub timeout_ms: u64,
42}
42}
43
43
44#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
45pub struct AugloopStage {
46 pub send: Vec<String>,
47 #[serde(rename = "awaitMessageId")]
48 pub await_message_id: Option<String>,
49}
50
51/// An AugLoop conversation over a WebSocket opened in the page. Each stage is sent once the previous stage's
52/// awaited answer arrives; `placeholder` in a message becomes the token. The answer body is every received message,
53/// up to the first one containing `done_marker`.
54#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
55pub struct AugloopExchange {
56 pub stages: Vec<AugloopStage>,
57 pub placeholder: String,
58 #[serde(rename = "doneMarker")]
59 pub done_marker: String,
60 #[serde(rename = "timeoutMs")]
61 pub timeout_ms: u64,
62 #[serde(rename = "keepaliveMs")]
63 pub keepalive_ms: u64,
64}
65
44#[derive(Debug, Clone)]
66#[derive(Debug, Clone)]
45pub struct Request {
67pub struct Request {
46 pub method: Method,
68 pub method: Method,
@@ -52,9 +74,17 @@ pub struct Request {
52 pub body_base64: Option<String>,
74 pub body_base64: Option<String>,
53 pub body_tokens: Vec<BodyToken>,
75 pub body_tokens: Vec<BodyToken>,
54 pub signalr: Option<SignalrExchange>,
76 pub signalr: Option<SignalrExchange>,
77 pub augloop: Option<AugloopExchange>,
55}
78}
56
79
57impl Request {
80impl Request {
81 pub fn augloop(url: impl Into<String>, exchange: AugloopExchange) -> Self {
82 Request {
83 augloop: Some(exchange),
84 ..Request::get(url)
85 }
86 }
87
58 pub fn signalr(url: impl Into<String>, exchange: SignalrExchange) -> Self {
88 pub fn signalr(url: impl Into<String>, exchange: SignalrExchange) -> Self {
59 Request {
89 Request {
60 signalr: Some(exchange),
90 signalr: Some(exchange),
@@ -81,6 +111,7 @@ impl Request {
81 body_base64: None,
111 body_base64: None,
82 body_tokens: Vec::new(),
112 body_tokens: Vec::new(),
83 signalr: None,
113 signalr: None,
114 augloop: None,
84 }
115 }
85 }
116 }
86
117
@@ -132,6 +163,7 @@ impl Request {
132 body_base64: None,
163 body_base64: None,
133 body_tokens: Vec::new(),
164 body_tokens: Vec::new(),
134 signalr: None,
165 signalr: None,
166 augloop: None,
135 }
167 }
136 }
168 }
137}
169}
@@ -162,6 +194,7 @@ pub(crate) struct WireRequest<'a> {
162 #[serde(rename = "bodyTokens")]
194 #[serde(rename = "bodyTokens")]
163 pub body_tokens: &'a [BodyToken],
195 pub body_tokens: &'a [BodyToken],
164 pub signalr: Option<&'a SignalrExchange>,
196 pub signalr: Option<&'a SignalrExchange>,
197 pub augloop: Option<&'a AugloopExchange>,
165}
198}
166
199
167impl<'a> From<&'a Request> for WireRequest<'a> {
200impl<'a> From<&'a Request> for WireRequest<'a> {
@@ -184,6 +217,7 @@ impl<'a> From<&'a Request> for WireRequest<'a> {
184 anonymous: request.anonymous,
217 anonymous: request.anonymous,
185 body_tokens: &request.body_tokens,
218 body_tokens: &request.body_tokens,
186 signalr: request.signalr.as_ref(),
219 signalr: request.signalr.as_ref(),
220 augloop: request.augloop.as_ref(),
187 }
221 }
188 }
222 }
189}
223}