BlueGit

ict rusty-teams

feat(chat): Copilot pane for chats

- Copilot button in the chat header opens a side pane
- Suggestions: summarize, open items, decisions, plus own questions
- Asks M365 Copilot over the SignalR chat hub with the chat as context
- Answers render as markdown; stale answers after a chat switch are dropped

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

metis Daniel Däschle · pushed by metis

Authored 2026-11-05 · 3 weeks ago

Hash
720aead31e6eee442a5070f02613b0db9912c97e
Parent
d9720b9a
10 files changed +649 −2
crates/app/src/views/conversation.rs +8 −1
@@ -22,6 +22,7 @@ use teams_core::{
22 22 };
23 23
24 24 mod channel_details;
25 mod copilot;
25 26 pub use channel_details::{
26 27 CHANNEL_DETAILS_BUTTON, CHANNEL_DETAILS_PINNED_TAG, CHANNEL_DETAILS_SHARED_TAG,
27 28 CHANNEL_DETAILS_TAG,
@@ -245,6 +246,7 @@ pub struct ConversationView {
245 246 fetched_jump: Option<String>,
246 247 pin_index: usize,
247 248 channel_details_open: bool,
249 copilot: copilot::CopilotPane,
248 250 pinned_posts_expanded: bool,
249 251 channel_details_scroll: ScrollHandle,
250 252 scroller_watch: Option<(EntityId, Subscription)>,
@@ -594,6 +596,7 @@ impl ConversationView {
594 596 fetched_jump: None,
595 597 pin_index: 0,
596 598 channel_details_open: false,
599 copilot: copilot::CopilotPane::default(),
597 600 pinned_posts_expanded: false,
598 601 channel_details_scroll: ScrollHandle::new(),
599 602 scroller_watch: None,
@@ -915,6 +918,7 @@ impl ConversationView {
915 918 self.feed_at_top = true;
916 919 self.restore_subject(None, window, cx);
917 920 self.toolbar_hovered = None;
921 self.reset_copilot();
918 922 self.toolbar_pinned = None;
919 923 self.toolbar_suppressed = None;
920 924 self.agent_layouts.clear();
@@ -3728,6 +3732,7 @@ impl ConversationView {
3728 3732 .children(inline_tabs)
3729 3733 .children(stack)
3730 3734 .children(call_controls)
3735 .children(self.copilot_button(cx))
3731 3736 .children(self.channel_find_button(cx))
3732 3737 .children(self.channel_details_button(cx))
3733 3738 .children(self.pop_in_button(current))
@@ -4001,7 +4006,9 @@ impl Render for ConversationView {
4001 4006 } else {
4002 4007 scroller.into_any_element()
4003 4008 };
4004 let channel_details = self.render_channel_details(cx);
4009 let channel_details = self
4010 .render_channel_details(cx)
4011 .or_else(|| self.render_copilot(cx));
4005 4012 let find_panel = self.find_panel.clone().filter(|_| !drafting);
4006 4013 let find_overlays = self.header_width(window) < FIND_PANEL_WIDTH + FIND_MIN_TIMELINE_WIDTH;
4007 4014 let content = v_flex()
@@ -22,6 +22,7 @@ use teams_core::{
22};
22};
23
23
24mod channel_details;
24mod channel_details;
25mod copilot;
25pub use channel_details::{
26pub use channel_details::{
26 CHANNEL_DETAILS_BUTTON, CHANNEL_DETAILS_PINNED_TAG, CHANNEL_DETAILS_SHARED_TAG,
27 CHANNEL_DETAILS_BUTTON, CHANNEL_DETAILS_PINNED_TAG, CHANNEL_DETAILS_SHARED_TAG,
27 CHANNEL_DETAILS_TAG,
28 CHANNEL_DETAILS_TAG,
@@ -245,6 +246,7 @@ pub struct ConversationView {
245 fetched_jump: Option<String>,
246 fetched_jump: Option<String>,
246 pin_index: usize,
247 pin_index: usize,
247 channel_details_open: bool,
248 channel_details_open: bool,
249 copilot: copilot::CopilotPane,
248 pinned_posts_expanded: bool,
250 pinned_posts_expanded: bool,
249 channel_details_scroll: ScrollHandle,
251 channel_details_scroll: ScrollHandle,
250 scroller_watch: Option<(EntityId, Subscription)>,
252 scroller_watch: Option<(EntityId, Subscription)>,
@@ -594,6 +596,7 @@ impl ConversationView {
594 fetched_jump: None,
596 fetched_jump: None,
595 pin_index: 0,
597 pin_index: 0,
596 channel_details_open: false,
598 channel_details_open: false,
599 copilot: copilot::CopilotPane::default(),
597 pinned_posts_expanded: false,
600 pinned_posts_expanded: false,
598 channel_details_scroll: ScrollHandle::new(),
601 channel_details_scroll: ScrollHandle::new(),
599 scroller_watch: None,
602 scroller_watch: None,
@@ -915,6 +918,7 @@ impl ConversationView {
915 self.feed_at_top = true;
918 self.feed_at_top = true;
916 self.restore_subject(None, window, cx);
919 self.restore_subject(None, window, cx);
917 self.toolbar_hovered = None;
920 self.toolbar_hovered = None;
921 self.reset_copilot();
918 self.toolbar_pinned = None;
922 self.toolbar_pinned = None;
919 self.toolbar_suppressed = None;
923 self.toolbar_suppressed = None;
920 self.agent_layouts.clear();
924 self.agent_layouts.clear();
@@ -3728,6 +3732,7 @@ impl ConversationView {
3728 .children(inline_tabs)
3732 .children(inline_tabs)
3729 .children(stack)
3733 .children(stack)
3730 .children(call_controls)
3734 .children(call_controls)
3735 .children(self.copilot_button(cx))
3731 .children(self.channel_find_button(cx))
3736 .children(self.channel_find_button(cx))
3732 .children(self.channel_details_button(cx))
3737 .children(self.channel_details_button(cx))
3733 .children(self.pop_in_button(current))
3738 .children(self.pop_in_button(current))
@@ -4001,7 +4006,9 @@ impl Render for ConversationView {
4001 } else {
4006 } else {
4002 scroller.into_any_element()
4007 scroller.into_any_element()
4003 };
4008 };
4004 let channel_details = self.render_channel_details(cx);
4009 let channel_details = self
4010 .render_channel_details(cx)
4011 .or_else(|| self.render_copilot(cx));
4005 let find_panel = self.find_panel.clone().filter(|_| !drafting);
4012 let find_panel = self.find_panel.clone().filter(|_| !drafting);
4006 let find_overlays = self.header_width(window) < FIND_PANEL_WIDTH + FIND_MIN_TIMELINE_WIDTH;
4013 let find_overlays = self.header_width(window) < FIND_PANEL_WIDTH + FIND_MIN_TIMELINE_WIDTH;
4007 let content = v_flex()
4014 let content = v_flex()
crates/app/src/views/conversation/copilot.rs added +308 −0
@@ -0,0 +1,308 @@
1 use gpui_kit::assets::IconName;
2 use gpui_kit::component::button::{Button, ButtonVariants as _};
3 use gpui_kit::component::input::{Input, InputEvent, InputState};
4 use gpui_kit::component::scroll::ScrollableElement as _;
5 use gpui_kit::component::{Disableable as _, Selectable as _, h_flex, v_flex};
6 use gpui_kit::prelude::FluentBuilder as _;
7 use gpui_kit::*;
8
9 use super::ConversationView;
10 use crate::app_state::Selection;
11 use crate::render::{layout_card_blocks, render_blocks};
12 use crate::runtime;
13 use crate::theme;
14 use crate::views::scroll_edge::with_top_edge;
15
16 pub const COPILOT_PANE_TAG: &str = "shell/islands/main/copilot";
17 const COPILOT_SCROLL_DIVIDER: &str = "shell/islands/main/copilot/divider-scroll";
18 const TITLE: &str = "Copilot";
19 const OPEN_LABEL: &str = "Open Copilot";
20 const CLOSE_LABEL: &str = "Close Copilot";
21 const PLACEHOLDER: &str = "Message Copilot";
22 const WORKING: &str = "Copilot is reading the chat ...";
23 const UNAVAILABLE: &str = "Copilot needs a signed-in account.";
24 const INTRO: &str = "Ask Copilot about this chat.";
25 const SUGGESTIONS: [&str; 3] = [
26 "Summarize this chat",
27 "What are open items?",
28 "What decisions were made?",
29 ];
30 const PANE_WIDTH: f32 = 360.;
31 const PANE_PADDING: f32 = 16.;
32 const HEADER_HEIGHT: f32 = 48.;
33 const BUTTON_SIZE: f32 = 32.;
34 const BUBBLE_RADIUS: f32 = 8.;
35
36 #[derive(Default)]
37 pub(super) struct CopilotPane {
38 open: bool,
39 turns: Vec<CopilotTurn>,
40 input: Option<Entity<InputState>>,
41 scroll: ScrollHandle,
42 generation: u64,
43 _input_events: Option<Subscription>,
44 }
45
46 struct CopilotTurn {
47 prompt: String,
48 answer: CopilotAnswer,
49 }
50
51 enum CopilotAnswer {
52 Waiting,
53 Ready(String),
54 Failed(String),
55 }
56
57 impl ConversationView {
58 fn copilot_chat_id(&self) -> Option<String> {
59 match &self.current.as_ref()?.selection {
60 Selection::Chat(chat_id) => Some(chat_id.clone()),
61 Selection::Channel(_) => None,
62 }
63 }
64
65 pub(super) fn copilot_button(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
66 self.copilot_chat_id()?;
67 let open = self.copilot.open;
68 Some(
69 Button::new("copilot-toggle")
70 .icon(IconName::Sparkles)
71 .ghost()
72 .size(px(BUTTON_SIZE))
73 .rounded(px(8.))
74 .when(open, |button| button.selected(true))
75 .tooltip(if open { CLOSE_LABEL } else { OPEN_LABEL })
76 .on_click(cx.listener(|this, _, window, cx| this.toggle_copilot(window, cx)))
77 .into_any_element(),
78 )
79 }
80
81 fn toggle_copilot(&mut self, window: &mut Window, cx: &mut Context<Self>) {
82 self.copilot.open = !self.copilot.open;
83 if self.copilot.open && self.copilot.input.is_none() {
84 let input = cx.new(|cx| InputState::new(window, cx).placeholder(PLACEHOLDER));
85 let subscription = cx.subscribe_in(&input, window, |this, input, event: &InputEvent, window, cx| {
86 if matches!(event, InputEvent::PressEnter { .. }) {
87 let prompt = input.read(cx).value().trim().to_owned();
88 if !prompt.is_empty() {
89 input.update(cx, |input, cx| input.set_value("", window, cx));
90 this.ask_copilot(prompt, cx);
91 }
92 }
93 });
94 self.copilot.input = Some(input);
95 self.copilot._input_events = Some(subscription);
96 }
97 if self.copilot.open {
98 self.channel_details_open = false;
99 if let Some(input) = &self.copilot.input {
100 input.update(cx, |input, cx| input.focus(window, cx));
101 }
102 }
103 cx.notify();
104 }
105
106 pub(super) fn reset_copilot(&mut self) {
107 let input = self.copilot.input.take();
108 let events = self.copilot._input_events.take();
109 self.copilot = CopilotPane {
110 input,
111 generation: self.copilot.generation + 1,
112 _input_events: events,
113 ..CopilotPane::default()
114 };
115 }
116
117 fn ask_copilot(&mut self, prompt: String, cx: &mut Context<Self>) {
118 let Some(chat_id) = self.copilot_chat_id() else {
119 return;
120 };
121 let index = self.copilot.turns.len();
122 let generation = self.copilot.generation;
123 self.copilot.turns.push(CopilotTurn {
124 prompt: prompt.clone(),
125 answer: CopilotAnswer::Waiting,
126 });
127 self.copilot.scroll.scroll_to_bottom();
128 cx.notify();
129 let Some(engine) = self.app.read(cx).engine.clone() else {
130 self.settle_copilot(generation, index, Err(UNAVAILABLE.to_owned()), cx);
131 return;
132 };
133 let receiver = runtime::spawn(async move { engine.ask_copilot(&chat_id, &prompt).await });
134 cx.spawn(async move |this, cx| {
135 let answer = match receiver.await {
136 Ok(Ok(text)) => Ok(text),
137 Ok(Err(error)) => Err(error.to_string()),
138 Err(error) => Err(error.to_string()),
139 };
140 this.update(cx, |this, cx| this.settle_copilot(generation, index, answer, cx))
141 .ok();
142 })
143 .detach();
144 }
145
146 fn settle_copilot(
147 &mut self,
148 generation: u64,
149 index: usize,
150 answer: Result<String, String>,
151 cx: &mut Context<Self>,
152 ) {
153 if generation != self.copilot.generation {
154 return;
155 }
156 let Some(turn) = self.copilot.turns.get_mut(index) else {
157 return;
158 };
159 turn.answer = match answer {
160 Ok(text) => CopilotAnswer::Ready(text),
161 Err(error) => CopilotAnswer::Failed(error),
162 };
163 self.copilot.scroll.scroll_to_bottom();
164 cx.notify();
165 }
166
167 pub(super) fn render_copilot(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
168 if !self.copilot.open {
169 return None;
170 }
171 self.copilot_chat_id()?;
172 let mut body = v_flex()
173 .w_full()
174 .px(px(PANE_PADDING))
175 .pb(px(PANE_PADDING))
176 .gap(px(12.));
177 if self.copilot.turns.is_empty() {
178 body = body.child(
179 div()
180 .text_size(px(13.))
181 .text_color(theme::text_muted())
182 .child(INTRO),
183 );
184 }
185 for (index, turn) in self.copilot.turns.iter().enumerate() {
186 body = body.child(prompt_bubble(&turn.prompt)).child(answer_view(index, &turn.answer, cx));
187 }
188 let busy = self
189 .copilot
190 .turns
191 .last()
192 .is_some_and(|turn| matches!(turn.answer, CopilotAnswer::Waiting));
193 let suggestions = h_flex().flex_wrap().gap(px(6.)).children(
194 SUGGESTIONS.iter().enumerate().map(|(index, prompt)| {
195 Button::new(("copilot-suggestion", index))
196 .label(*prompt)
197 .outline()
198 .rounded(px(BUBBLE_RADIUS))
199 .disabled(busy)
200 .on_click(cx.listener(move |this, _, _, cx| {
201 this.ask_copilot((*prompt).to_owned(), cx)
202 }))
203 }),
204 );
205 let footer = v_flex()
206 .flex_none()
207 .px(px(PANE_PADDING))
208 .py(px(12.))
209 .gap(px(8.))
210 .child(suggestions)
211 .children(self.copilot.input.as_ref().map(|input| Input::new(input)));
212 Some(
213 h_flex()
214 .h_full()
215 .flex_none()
216 .child(div().w(px(1.)).h_full().flex_none().bg(theme::border()))
217 .child(
218 v_flex()
219 .debug_selector(|| COPILOT_PANE_TAG.into())
220 .w(px(PANE_WIDTH))
221 .h_full()
222 .bg(theme::surface())
223 .child(
224 h_flex()
225 .h(px(HEADER_HEIGHT))
226 .flex_none()
227 .px(px(PANE_PADDING))
228 .items_center()
229 .justify_between()
230 .child(
231 div()
232 .text_size(px(15.))
233 .font_weight(FontWeight::SEMIBOLD)
234 .text_color(theme::text())
235 .child(TITLE),
236 )
237 .child(
238 Button::new("copilot-close")
239 .icon(IconName::X)
240 .ghost()
241 .size(px(BUTTON_SIZE))
242 .rounded(px(8.))
243 .tooltip(CLOSE_LABEL)
244 .on_click(cx.listener(|this, _, _, cx| {
245 this.copilot.open = false;
246 cx.notify();
247 })),
248 ),
249 )
250 .child(with_top_edge(
251 div()
252 .id("copilot-body")
253 .flex_1()
254 .min_h_0()
255 .overflow_y_scrollbar()
256 .track_scroll(&self.copilot.scroll)
257 .child(body),
258 &self.copilot.scroll,
259 COPILOT_SCROLL_DIVIDER,
260 ))
261 .child(footer),
262 )
263 .into_any_element(),
264 )
265 }
266 }
267
268 fn prompt_bubble(prompt: &str) -> Div {
269 h_flex().w_full().justify_end().child(
270 div()
271 .max_w(px(PANE_WIDTH * 0.8))
272 .px(px(10.))
273 .py(px(6.))
274 .rounded(px(BUBBLE_RADIUS))
275 .bg(theme::row_hover())
276 .text_size(px(13.))
277 .text_color(theme::text())
278 .child(prompt.to_owned()),
279 )
280 }
281
282 fn answer_view(index: usize, answer: &CopilotAnswer, cx: &App) -> AnyElement {
283 match answer {
284 CopilotAnswer::Waiting => div()
285 .text_size(px(13.))
286 .text_color(theme::text_muted())
287 .child(WORKING)
288 .into_any_element(),
289 CopilotAnswer::Failed(error) => div()
290 .text_size(px(13.))
291 .text_color(theme::red())
292 .child(error.clone())
293 .into_any_element(),
294 CopilotAnswer::Ready(text) => {
295 let spans = teams_core::html_to_spans(&teams_core::markdown_to_html(text));
296 div()
297 .w_full()
298 .text_size(px(13.))
299 .child(render_blocks(
300 &layout_card_blocks(&spans),
301 &format!("copilot-answer-{index}"),
302 false,
303 cx,
304 ))
305 .into_any_element()
306 }
307 }
308 }
@@ -0,0 +1,308 @@
1use gpui_kit::assets::IconName;
2use gpui_kit::component::button::{Button, ButtonVariants as _};
3use gpui_kit::component::input::{Input, InputEvent, InputState};
4use gpui_kit::component::scroll::ScrollableElement as _;
5use gpui_kit::component::{Disableable as _, Selectable as _, h_flex, v_flex};
6use gpui_kit::prelude::FluentBuilder as _;
7use gpui_kit::*;
8
9use super::ConversationView;
10use crate::app_state::Selection;
11use crate::render::{layout_card_blocks, render_blocks};
12use crate::runtime;
13use crate::theme;
14use crate::views::scroll_edge::with_top_edge;
15
16pub const COPILOT_PANE_TAG: &str = "shell/islands/main/copilot";
17const COPILOT_SCROLL_DIVIDER: &str = "shell/islands/main/copilot/divider-scroll";
18const TITLE: &str = "Copilot";
19const OPEN_LABEL: &str = "Open Copilot";
20const CLOSE_LABEL: &str = "Close Copilot";
21const PLACEHOLDER: &str = "Message Copilot";
22const WORKING: &str = "Copilot is reading the chat ...";
23const UNAVAILABLE: &str = "Copilot needs a signed-in account.";
24const INTRO: &str = "Ask Copilot about this chat.";
25const SUGGESTIONS: [&str; 3] = [
26 "Summarize this chat",
27 "What are open items?",
28 "What decisions were made?",
29];
30const PANE_WIDTH: f32 = 360.;
31const PANE_PADDING: f32 = 16.;
32const HEADER_HEIGHT: f32 = 48.;
33const BUTTON_SIZE: f32 = 32.;
34const BUBBLE_RADIUS: f32 = 8.;
35
36#[derive(Default)]
37pub(super) struct CopilotPane {
38 open: bool,
39 turns: Vec<CopilotTurn>,
40 input: Option<Entity<InputState>>,
41 scroll: ScrollHandle,
42 generation: u64,
43 _input_events: Option<Subscription>,
44}
45
46struct CopilotTurn {
47 prompt: String,
48 answer: CopilotAnswer,
49}
50
51enum CopilotAnswer {
52 Waiting,
53 Ready(String),
54 Failed(String),
55}
56
57impl ConversationView {
58 fn copilot_chat_id(&self) -> Option<String> {
59 match &self.current.as_ref()?.selection {
60 Selection::Chat(chat_id) => Some(chat_id.clone()),
61 Selection::Channel(_) => None,
62 }
63 }
64
65 pub(super) fn copilot_button(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
66 self.copilot_chat_id()?;
67 let open = self.copilot.open;
68 Some(
69 Button::new("copilot-toggle")
70 .icon(IconName::Sparkles)
71 .ghost()
72 .size(px(BUTTON_SIZE))
73 .rounded(px(8.))
74 .when(open, |button| button.selected(true))
75 .tooltip(if open { CLOSE_LABEL } else { OPEN_LABEL })
76 .on_click(cx.listener(|this, _, window, cx| this.toggle_copilot(window, cx)))
77 .into_any_element(),
78 )
79 }
80
81 fn toggle_copilot(&mut self, window: &mut Window, cx: &mut Context<Self>) {
82 self.copilot.open = !self.copilot.open;
83 if self.copilot.open && self.copilot.input.is_none() {
84 let input = cx.new(|cx| InputState::new(window, cx).placeholder(PLACEHOLDER));
85 let subscription = cx.subscribe_in(&input, window, |this, input, event: &InputEvent, window, cx| {
86 if matches!(event, InputEvent::PressEnter { .. }) {
87 let prompt = input.read(cx).value().trim().to_owned();
88 if !prompt.is_empty() {
89 input.update(cx, |input, cx| input.set_value("", window, cx));
90 this.ask_copilot(prompt, cx);
91 }
92 }
93 });
94 self.copilot.input = Some(input);
95 self.copilot._input_events = Some(subscription);
96 }
97 if self.copilot.open {
98 self.channel_details_open = false;
99 if let Some(input) = &self.copilot.input {
100 input.update(cx, |input, cx| input.focus(window, cx));
101 }
102 }
103 cx.notify();
104 }
105
106 pub(super) fn reset_copilot(&mut self) {
107 let input = self.copilot.input.take();
108 let events = self.copilot._input_events.take();
109 self.copilot = CopilotPane {
110 input,
111 generation: self.copilot.generation + 1,
112 _input_events: events,
113 ..CopilotPane::default()
114 };
115 }
116
117 fn ask_copilot(&mut self, prompt: String, cx: &mut Context<Self>) {
118 let Some(chat_id) = self.copilot_chat_id() else {
119 return;
120 };
121 let index = self.copilot.turns.len();
122 let generation = self.copilot.generation;
123 self.copilot.turns.push(CopilotTurn {
124 prompt: prompt.clone(),
125 answer: CopilotAnswer::Waiting,
126 });
127 self.copilot.scroll.scroll_to_bottom();
128 cx.notify();
129 let Some(engine) = self.app.read(cx).engine.clone() else {
130 self.settle_copilot(generation, index, Err(UNAVAILABLE.to_owned()), cx);
131 return;
132 };
133 let receiver = runtime::spawn(async move { engine.ask_copilot(&chat_id, &prompt).await });
134 cx.spawn(async move |this, cx| {
135 let answer = match receiver.await {
136 Ok(Ok(text)) => Ok(text),
137 Ok(Err(error)) => Err(error.to_string()),
138 Err(error) => Err(error.to_string()),
139 };
140 this.update(cx, |this, cx| this.settle_copilot(generation, index, answer, cx))
141 .ok();
142 })
143 .detach();
144 }
145
146 fn settle_copilot(
147 &mut self,
148 generation: u64,
149 index: usize,
150 answer: Result<String, String>,
151 cx: &mut Context<Self>,
152 ) {
153 if generation != self.copilot.generation {
154 return;
155 }
156 let Some(turn) = self.copilot.turns.get_mut(index) else {
157 return;
158 };
159 turn.answer = match answer {
160 Ok(text) => CopilotAnswer::Ready(text),
161 Err(error) => CopilotAnswer::Failed(error),
162 };
163 self.copilot.scroll.scroll_to_bottom();
164 cx.notify();
165 }
166
167 pub(super) fn render_copilot(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
168 if !self.copilot.open {
169 return None;
170 }
171 self.copilot_chat_id()?;
172 let mut body = v_flex()
173 .w_full()
174 .px(px(PANE_PADDING))
175 .pb(px(PANE_PADDING))
176 .gap(px(12.));
177 if self.copilot.turns.is_empty() {
178 body = body.child(
179 div()
180 .text_size(px(13.))
181 .text_color(theme::text_muted())
182 .child(INTRO),
183 );
184 }
185 for (index, turn) in self.copilot.turns.iter().enumerate() {
186 body = body.child(prompt_bubble(&turn.prompt)).child(answer_view(index, &turn.answer, cx));
187 }
188 let busy = self
189 .copilot
190 .turns
191 .last()
192 .is_some_and(|turn| matches!(turn.answer, CopilotAnswer::Waiting));
193 let suggestions = h_flex().flex_wrap().gap(px(6.)).children(
194 SUGGESTIONS.iter().enumerate().map(|(index, prompt)| {
195 Button::new(("copilot-suggestion", index))
196 .label(*prompt)
197 .outline()
198 .rounded(px(BUBBLE_RADIUS))
199 .disabled(busy)
200 .on_click(cx.listener(move |this, _, _, cx| {
201 this.ask_copilot((*prompt).to_owned(), cx)
202 }))
203 }),
204 );
205 let footer = v_flex()
206 .flex_none()
207 .px(px(PANE_PADDING))
208 .py(px(12.))
209 .gap(px(8.))
210 .child(suggestions)
211 .children(self.copilot.input.as_ref().map(|input| Input::new(input)));
212 Some(
213 h_flex()
214 .h_full()
215 .flex_none()
216 .child(div().w(px(1.)).h_full().flex_none().bg(theme::border()))
217 .child(
218 v_flex()
219 .debug_selector(|| COPILOT_PANE_TAG.into())
220 .w(px(PANE_WIDTH))
221 .h_full()
222 .bg(theme::surface())
223 .child(
224 h_flex()
225 .h(px(HEADER_HEIGHT))
226 .flex_none()
227 .px(px(PANE_PADDING))
228 .items_center()
229 .justify_between()
230 .child(
231 div()
232 .text_size(px(15.))
233 .font_weight(FontWeight::SEMIBOLD)
234 .text_color(theme::text())
235 .child(TITLE),
236 )
237 .child(
238 Button::new("copilot-close")
239 .icon(IconName::X)
240 .ghost()
241 .size(px(BUTTON_SIZE))
242 .rounded(px(8.))
243 .tooltip(CLOSE_LABEL)
244 .on_click(cx.listener(|this, _, _, cx| {
245 this.copilot.open = false;
246 cx.notify();
247 })),
248 ),
249 )
250 .child(with_top_edge(
251 div()
252 .id("copilot-body")
253 .flex_1()
254 .min_h_0()
255 .overflow_y_scrollbar()
256 .track_scroll(&self.copilot.scroll)
257 .child(body),
258 &self.copilot.scroll,
259 COPILOT_SCROLL_DIVIDER,
260 ))
261 .child(footer),
262 )
263 .into_any_element(),
264 )
265 }
266}
267
268fn prompt_bubble(prompt: &str) -> Div {
269 h_flex().w_full().justify_end().child(
270 div()
271 .max_w(px(PANE_WIDTH * 0.8))
272 .px(px(10.))
273 .py(px(6.))
274 .rounded(px(BUBBLE_RADIUS))
275 .bg(theme::row_hover())
276 .text_size(px(13.))
277 .text_color(theme::text())
278 .child(prompt.to_owned()),
279 )
280}
281
282fn answer_view(index: usize, answer: &CopilotAnswer, cx: &App) -> AnyElement {
283 match answer {
284 CopilotAnswer::Waiting => div()
285 .text_size(px(13.))
286 .text_color(theme::text_muted())
287 .child(WORKING)
288 .into_any_element(),
289 CopilotAnswer::Failed(error) => div()
290 .text_size(px(13.))
291 .text_color(theme::red())
292 .child(error.clone())
293 .into_any_element(),
294 CopilotAnswer::Ready(text) => {
295 let spans = teams_core::html_to_spans(&teams_core::markdown_to_html(text));
296 div()
297 .w_full()
298 .text_size(px(13.))
299 .child(render_blocks(
300 &layout_card_blocks(&spans),
301 &format!("copilot-answer-{index}"),
302 false,
303 cx,
304 ))
305 .into_any_element()
306 }
307 }
308}
crates/chatsvc/src/copilot.rs added +233 −0
@@ -0,0 +1,233 @@
1 use serde_json::{Value, json};
2 use session::{Request, Scope, Session, SignalrExchange};
3 use uuid::Uuid;
4
5 use crate::error::{Error, Result};
6
7 const CHATHUB_URL: &str = "https://substrate.office.com/m365Copilot/Chathub";
8 const SYDNEY_RESOURCE: &str = "https://substrate.office.com/sydney";
9 const SYDNEY_SCOPE: &str = "sydney.readwrite";
10 const HANDSHAKE: &str = r#"{"protocol":"json","version":1}"#;
11 const INVOCATION: u8 = 4;
12 const COMPLETION: u8 = 2;
13 const CLOSE: u8 = 7;
14 const ANSWER_TIMEOUT_MS: u64 = 55_000;
15 const SOURCE: &str = "teamshub";
16 const CITATION_OPEN: char = '\u{e200}';
17 const CITATION_CLOSE: char = '\u{e201}';
18 const INLINE_TAGS: [&str; 6] = ["Person", "TeamsMessage", "File", "Event", "Email", "Chat"];
19
20 #[derive(Debug, Clone, PartialEq, Eq)]
21 pub struct CopilotAsk {
22 pub user_id: String,
23 pub tenant_id: String,
24 pub chat_id: String,
25 pub prompt: String,
26 pub locale: String,
27 pub utc_offset_hours: i32,
28 }
29
30 pub struct Copilot {
31 session: Session,
32 }
33
34 impl Copilot {
35 pub fn new(session: &Session) -> Self {
36 Copilot {
37 session: session.clone(),
38 }
39 }
40
41 pub async fn ask(&self, ask: &CopilotAsk) -> Result<String> {
42 let session_id = Uuid::new_v4().to_string();
43 let request_id = Uuid::new_v4().simple().to_string();
44 let request = Request::signalr(
45 chathub_url(ask, &session_id, &request_id),
46 SignalrExchange {
47 handshake: HANDSHAKE.to_owned(),
48 invocations: vec![invocation(ask, &session_id, &request_id).to_string()],
49 done_types: vec![COMPLETION, CLOSE],
50 timeout_ms: ANSWER_TIMEOUT_MS,
51 },
52 );
53 let response = self
54 .session
55 .send(request, &Scope::new(SYDNEY_RESOURCE, SYDNEY_SCOPE))
56 .await?;
57 answer_of(&response.body)
58 }
59 }
60
61 fn chathub_url(ask: &CopilotAsk, session_id: &str, request_id: &str) -> String {
62 let route = format!("{}@{}", ask.user_id, ask.tenant_id);
63 format!(
64 "{CHATHUB_URL}/{route}?chatsessionid={request_id}&XRoutingParameterSessionKey={user}&clientrequestid={request_id}&X-SessionId={session_id}&ConversationId={conversation}",
65 user = ask.user_id,
66 conversation = Uuid::new_v4(),
67 )
68 }
69
70 pub fn invocation(ask: &CopilotAsk, session_id: &str, request_id: &str) -> Value {
71 json!({
72 "type": INVOCATION,
73 "invocationId": "0",
74 "target": "chat",
75 "arguments": [{
76 "source": SOURCE,
77 "clientCorrelationId": request_id,
78 "sessionId": session_id,
79 "optionsSets": ["enterprise_flux_work", "rich_responses"],
80 "streamingMode": "ConciseWithPadding",
81 "allowedMessageTypes": ["Chat", "Disengaged", "Progress", "EndOfRequest"],
82 "requestId": request_id,
83 "traceId": request_id,
84 "isStartOfSession": true,
85 "clientInfo": {
86 "clientPlatform": "web",
87 "clientAppName": "Teams",
88 "clientEntrypoint": "ChatPanel",
89 "clientSessionId": session_id,
90 "ProductCategory": "Chat",
91 "clientAppType": "Web",
92 "productEntryPoint": "ChatPanel",
93 },
94 "message": {
95 "author": "user",
96 "inputMethod": "Keyboard",
97 "text": ask.prompt,
98 "requestId": request_id,
99 "locale": ask.locale,
100 "locationInfo": {"timeZoneOffset": ask.utc_offset_hours},
101 "messageType": "Chat",
102 "experienceType": "Default",
103 "messageAnnotations": [{
104 "id": ask.chat_id,
105 "text": ask.chat_id,
106 "messageAnnotationAppContext": "Teams",
107 "messageAnnotationSource": "ClientAnnotated",
108 "messageAnnotationMetadata": {"@type": "Chat", "annotationType": "Chat"},
109 "messageAnnotationType": "Chat",
110 }],
111 },
112 }],
113 })
114 }
115
116 pub fn answer_of(received: &Value) -> Result<String> {
117 let messages = received.as_array().map(Vec::as_slice).unwrap_or_default();
118 let completion = messages
119 .iter()
120 .find(|message| message["type"].as_u64() == Some(u64::from(COMPLETION)))
121 .ok_or_else(|| Error::UnexpectedAnswer(close_reason(messages)))?;
122 let item = &completion["item"];
123 let answer = item["messages"]
124 .as_array()
125 .into_iter()
126 .flatten()
127 .filter(|message| message["author"] == "bot")
128 .filter(|message| message["messageType"].is_null() || message["messageType"] == "Chat")
129 .filter_map(|message| message["text"].as_str())
130 .next_back()
131 .map(clean_answer)
132 .filter(|text| !text.is_empty());
133 answer.ok_or_else(|| {
134 let reason = item["result"]["message"]
135 .as_str()
136 .or_else(|| item["result"]["value"].as_str())
137 .unwrap_or("Copilot gave no answer");
138 Error::UnexpectedAnswer(reason.to_owned())
139 })
140 }
141
142 fn close_reason(messages: &[Value]) -> String {
143 messages
144 .iter()
145 .find_map(|message| message["error"].as_str())
146 .unwrap_or("Copilot did not answer")
147 .to_owned()
148 }
149
150 pub fn clean_answer(text: &str) -> String {
151 let mut cleaned = String::with_capacity(text.len());
152 let mut in_citation = false;
153 for character in text.chars() {
154 match character {
155 CITATION_OPEN => in_citation = true,
156 CITATION_CLOSE => in_citation = false,
157 _ if !in_citation => cleaned.push(character),
158 _ => {}
159 }
160 }
161 for tag in INLINE_TAGS {
162 cleaned = cleaned
163 .replace(&format!("<{tag}>"), "")
164 .replace(&format!("</{tag}>"), "");
165 }
166 cleaned.trim().to_owned()
167 }
168
169 #[cfg(test)]
170 mod tests {
171 use super::*;
172
173 fn ask() -> CopilotAsk {
174 CopilotAsk {
175 user_id: "user-1".into(),
176 tenant_id: "tenant-1".into(),
177 chat_id: "19:chat@thread.v2".into(),
178 prompt: "Summarize this chat".into(),
179 locale: "en-us".into(),
180 utc_offset_hours: 1,
181 }
182 }
183
184 #[test]
185 fn the_chat_rides_along_as_a_message_annotation() {
186 let body = invocation(&ask(), "session-1", "request-1");
187 let message = &body["arguments"][0]["message"];
188 assert_eq!(body["target"], "chat");
189 assert_eq!(message["text"], "Summarize this chat");
190 assert_eq!(message["messageAnnotations"][0]["id"], "19:chat@thread.v2");
191 assert_eq!(message["messageAnnotations"][0]["messageAnnotationType"], "Chat");
192 }
193
194 #[test]
195 fn the_url_routes_to_the_user_in_the_tenant() {
196 let url = chathub_url(&ask(), "session-1", "request-1");
197 assert!(url.starts_with("https://substrate.office.com/m365Copilot/Chathub/user-1@tenant-1?"));
198 assert!(url.contains("X-SessionId=session-1"));
199 }
200
201 #[test]
202 fn the_last_bot_chat_message_is_the_answer() {
203 let received = json!([
204 {"type": 1, "target": "update", "arguments": [{"messages": [{"text": "Digging in", "author": "bot", "messageType": "Progress"}]}]},
205 {"type": 2, "invocationId": "0", "item": {"messages": [
206 {"text": "Summarize this chat", "author": "user"},
207 {"text": "Working", "author": "bot", "messageType": "Progress"},
208 {"text": "### Chat summary\n\n- <Person>Ada</Person> shipped it. \u{e200}cite\u{e202}turn1search1\u{e201}", "author": "bot"}
209 ], "result": {"value": "Success"}}}
210 ]);
211 assert_eq!(answer_of(&received).unwrap(), "### Chat summary\n\n- Ada shipped it.");
212 }
213
214 #[test]
215 fn a_refusal_carries_the_service_reason() {
216 let received = json!([
217 {"type": 2, "item": {"messages": [{"text": "Hi", "author": "user"}], "result": {"value": "Throttled", "message": "Too many requests"}}}
218 ]);
219 assert_eq!(
220 answer_of(&received).unwrap_err().to_string(),
221 "unexpected service answer: Too many requests"
222 );
223 }
224
225 #[test]
226 fn a_closed_hub_reports_its_error() {
227 let received = json!([{"type": 7, "error": "Unauthorized"}]);
228 assert_eq!(
229 answer_of(&received).unwrap_err().to_string(),
230 "unexpected service answer: Unauthorized"
231 );
232 }
233 }
@@ -0,0 +1,233 @@
1use serde_json::{Value, json};
2use session::{Request, Scope, Session, SignalrExchange};
3use uuid::Uuid;
4
5use crate::error::{Error, Result};
6
7const CHATHUB_URL: &str = "https://substrate.office.com/m365Copilot/Chathub";
8const SYDNEY_RESOURCE: &str = "https://substrate.office.com/sydney";
9const SYDNEY_SCOPE: &str = "sydney.readwrite";
10const HANDSHAKE: &str = r#"{"protocol":"json","version":1}"#;
11const INVOCATION: u8 = 4;
12const COMPLETION: u8 = 2;
13const CLOSE: u8 = 7;
14const ANSWER_TIMEOUT_MS: u64 = 55_000;
15const SOURCE: &str = "teamshub";
16const CITATION_OPEN: char = '\u{e200}';
17const CITATION_CLOSE: char = '\u{e201}';
18const INLINE_TAGS: [&str; 6] = ["Person", "TeamsMessage", "File", "Event", "Email", "Chat"];
19
20#[derive(Debug, Clone, PartialEq, Eq)]
21pub struct CopilotAsk {
22 pub user_id: String,
23 pub tenant_id: String,
24 pub chat_id: String,
25 pub prompt: String,
26 pub locale: String,
27 pub utc_offset_hours: i32,
28}
29
30pub struct Copilot {
31 session: Session,
32}
33
34impl Copilot {
35 pub fn new(session: &Session) -> Self {
36 Copilot {
37 session: session.clone(),
38 }
39 }
40
41 pub async fn ask(&self, ask: &CopilotAsk) -> Result<String> {
42 let session_id = Uuid::new_v4().to_string();
43 let request_id = Uuid::new_v4().simple().to_string();
44 let request = Request::signalr(
45 chathub_url(ask, &session_id, &request_id),
46 SignalrExchange {
47 handshake: HANDSHAKE.to_owned(),
48 invocations: vec![invocation(ask, &session_id, &request_id).to_string()],
49 done_types: vec![COMPLETION, CLOSE],
50 timeout_ms: ANSWER_TIMEOUT_MS,
51 },
52 );
53 let response = self
54 .session
55 .send(request, &Scope::new(SYDNEY_RESOURCE, SYDNEY_SCOPE))
56 .await?;
57 answer_of(&response.body)
58 }
59}
60
61fn chathub_url(ask: &CopilotAsk, session_id: &str, request_id: &str) -> String {
62 let route = format!("{}@{}", ask.user_id, ask.tenant_id);
63 format!(
64 "{CHATHUB_URL}/{route}?chatsessionid={request_id}&XRoutingParameterSessionKey={user}&clientrequestid={request_id}&X-SessionId={session_id}&ConversationId={conversation}",
65 user = ask.user_id,
66 conversation = Uuid::new_v4(),
67 )
68}
69
70pub fn invocation(ask: &CopilotAsk, session_id: &str, request_id: &str) -> Value {
71 json!({
72 "type": INVOCATION,
73 "invocationId": "0",
74 "target": "chat",
75 "arguments": [{
76 "source": SOURCE,
77 "clientCorrelationId": request_id,
78 "sessionId": session_id,
79 "optionsSets": ["enterprise_flux_work", "rich_responses"],
80 "streamingMode": "ConciseWithPadding",
81 "allowedMessageTypes": ["Chat", "Disengaged", "Progress", "EndOfRequest"],
82 "requestId": request_id,
83 "traceId": request_id,
84 "isStartOfSession": true,
85 "clientInfo": {
86 "clientPlatform": "web",
87 "clientAppName": "Teams",
88 "clientEntrypoint": "ChatPanel",
89 "clientSessionId": session_id,
90 "ProductCategory": "Chat",
91 "clientAppType": "Web",
92 "productEntryPoint": "ChatPanel",
93 },
94 "message": {
95 "author": "user",
96 "inputMethod": "Keyboard",
97 "text": ask.prompt,
98 "requestId": request_id,
99 "locale": ask.locale,
100 "locationInfo": {"timeZoneOffset": ask.utc_offset_hours},
101 "messageType": "Chat",
102 "experienceType": "Default",
103 "messageAnnotations": [{
104 "id": ask.chat_id,
105 "text": ask.chat_id,
106 "messageAnnotationAppContext": "Teams",
107 "messageAnnotationSource": "ClientAnnotated",
108 "messageAnnotationMetadata": {"@type": "Chat", "annotationType": "Chat"},
109 "messageAnnotationType": "Chat",
110 }],
111 },
112 }],
113 })
114}
115
116pub fn answer_of(received: &Value) -> Result<String> {
117 let messages = received.as_array().map(Vec::as_slice).unwrap_or_default();
118 let completion = messages
119 .iter()
120 .find(|message| message["type"].as_u64() == Some(u64::from(COMPLETION)))
121 .ok_or_else(|| Error::UnexpectedAnswer(close_reason(messages)))?;
122 let item = &completion["item"];
123 let answer = item["messages"]
124 .as_array()
125 .into_iter()
126 .flatten()
127 .filter(|message| message["author"] == "bot")
128 .filter(|message| message["messageType"].is_null() || message["messageType"] == "Chat")
129 .filter_map(|message| message["text"].as_str())
130 .next_back()
131 .map(clean_answer)
132 .filter(|text| !text.is_empty());
133 answer.ok_or_else(|| {
134 let reason = item["result"]["message"]
135 .as_str()
136 .or_else(|| item["result"]["value"].as_str())
137 .unwrap_or("Copilot gave no answer");
138 Error::UnexpectedAnswer(reason.to_owned())
139 })
140}
141
142fn close_reason(messages: &[Value]) -> String {
143 messages
144 .iter()
145 .find_map(|message| message["error"].as_str())
146 .unwrap_or("Copilot did not answer")
147 .to_owned()
148}
149
150pub fn clean_answer(text: &str) -> String {
151 let mut cleaned = String::with_capacity(text.len());
152 let mut in_citation = false;
153 for character in text.chars() {
154 match character {
155 CITATION_OPEN => in_citation = true,
156 CITATION_CLOSE => in_citation = false,
157 _ if !in_citation => cleaned.push(character),
158 _ => {}
159 }
160 }
161 for tag in INLINE_TAGS {
162 cleaned = cleaned
163 .replace(&format!("<{tag}>"), "")
164 .replace(&format!("</{tag}>"), "");
165 }
166 cleaned.trim().to_owned()
167}
168
169#[cfg(test)]
170mod tests {
171 use super::*;
172
173 fn ask() -> CopilotAsk {
174 CopilotAsk {
175 user_id: "user-1".into(),
176 tenant_id: "tenant-1".into(),
177 chat_id: "19:chat@thread.v2".into(),
178 prompt: "Summarize this chat".into(),
179 locale: "en-us".into(),
180 utc_offset_hours: 1,
181 }
182 }
183
184 #[test]
185 fn the_chat_rides_along_as_a_message_annotation() {
186 let body = invocation(&ask(), "session-1", "request-1");
187 let message = &body["arguments"][0]["message"];
188 assert_eq!(body["target"], "chat");
189 assert_eq!(message["text"], "Summarize this chat");
190 assert_eq!(message["messageAnnotations"][0]["id"], "19:chat@thread.v2");
191 assert_eq!(message["messageAnnotations"][0]["messageAnnotationType"], "Chat");
192 }
193
194 #[test]
195 fn the_url_routes_to_the_user_in_the_tenant() {
196 let url = chathub_url(&ask(), "session-1", "request-1");
197 assert!(url.starts_with("https://substrate.office.com/m365Copilot/Chathub/user-1@tenant-1?"));
198 assert!(url.contains("X-SessionId=session-1"));
199 }
200
201 #[test]
202 fn the_last_bot_chat_message_is_the_answer() {
203 let received = json!([
204 {"type": 1, "target": "update", "arguments": [{"messages": [{"text": "Digging in", "author": "bot", "messageType": "Progress"}]}]},
205 {"type": 2, "invocationId": "0", "item": {"messages": [
206 {"text": "Summarize this chat", "author": "user"},
207 {"text": "Working", "author": "bot", "messageType": "Progress"},
208 {"text": "### Chat summary\n\n- <Person>Ada</Person> shipped it. \u{e200}cite\u{e202}turn1search1\u{e201}", "author": "bot"}
209 ], "result": {"value": "Success"}}}
210 ]);
211 assert_eq!(answer_of(&received).unwrap(), "### Chat summary\n\n- Ada shipped it.");
212 }
213
214 #[test]
215 fn a_refusal_carries_the_service_reason() {
216 let received = json!([
217 {"type": 2, "item": {"messages": [{"text": "Hi", "author": "user"}], "result": {"value": "Throttled", "message": "Too many requests"}}}
218 ]);
219 assert_eq!(
220 answer_of(&received).unwrap_err().to_string(),
221 "unexpected service answer: Too many requests"
222 );
223 }
224
225 #[test]
226 fn a_closed_hub_reports_its_error() {
227 let received = json!([{"type": 7, "error": "Unauthorized"}]);
228 assert_eq!(
229 answer_of(&received).unwrap_err().to_string(),
230 "unexpected service answer: Unauthorized"
231 );
232 }
233}
crates/chatsvc/src/lib.rs +1 −0
@@ -9,6 +9,7 @@ pub mod chat_notifications;
9 9 pub mod chat_settings;
10 10 pub mod channel_visibility;
11 11 pub mod conversations;
12 pub mod copilot;
12 13 pub mod drafts;
13 14 pub mod emotions;
14 15 mod error;
@@ -9,6 +9,7 @@ pub mod chat_notifications;
9pub mod chat_settings;
9pub mod chat_settings;
10pub mod channel_visibility;
10pub mod channel_visibility;
11pub mod conversations;
11pub mod conversations;
12pub mod copilot;
12pub mod drafts;
13pub mod drafts;
13pub mod emotions;
14pub mod emotions;
14mod error;
15mod error;
crates/core/src/copilot.rs added +23 −0
@@ -0,0 +1,23 @@
1 use chatsvc::copilot::CopilotAsk;
2 use chrono::Local;
3
4 use crate::engine::SyncEngine;
5 use crate::error::Result;
6 use crate::remote::Remote;
7
8 const COPILOT_LOCALE: &str = "en-us";
9 const SECONDS_PER_HOUR: i32 = 3600;
10
11 impl<R: Remote> SyncEngine<R> {
12 pub async fn ask_copilot(&self, chat_id: &str, prompt: &str) -> Result<String> {
13 let ask = CopilotAsk {
14 user_id: self.my_user_id().await?,
15 tenant_id: self.my_tenant_id(chat_id).await?,
16 chat_id: chat_id.to_owned(),
17 prompt: prompt.to_owned(),
18 locale: COPILOT_LOCALE.to_owned(),
19 utc_offset_hours: Local::now().offset().local_minus_utc() / SECONDS_PER_HOUR,
20 };
21 self.remote.ask_copilot(&ask).await
22 }
23 }
@@ -0,0 +1,23 @@
1use chatsvc::copilot::CopilotAsk;
2use chrono::Local;
3
4use crate::engine::SyncEngine;
5use crate::error::Result;
6use crate::remote::Remote;
7
8const COPILOT_LOCALE: &str = "en-us";
9const SECONDS_PER_HOUR: i32 = 3600;
10
11impl<R: Remote> SyncEngine<R> {
12 pub async fn ask_copilot(&self, chat_id: &str, prompt: &str) -> Result<String> {
13 let ask = CopilotAsk {
14 user_id: self.my_user_id().await?,
15 tenant_id: self.my_tenant_id(chat_id).await?,
16 chat_id: chat_id.to_owned(),
17 prompt: prompt.to_owned(),
18 locale: COPILOT_LOCALE.to_owned(),
19 utc_offset_hours: Local::now().offset().local_minus_utc() / SECONDS_PER_HOUR,
20 };
21 self.remote.ask_copilot(&ask).await
22 }
23}
crates/core/src/lib.rs +1 −0
@@ -3,6 +3,7 @@ mod activity_sync;
3 3 mod adaptive_card;
4 4 mod avatars;
5 5 mod bot_partners;
6 mod copilot;
6 7 mod call_event;
7 8 mod card_actions;
8 9 mod card_chart;
@@ -3,6 +3,7 @@ mod activity_sync;
3mod adaptive_card;
3mod adaptive_card;
4mod avatars;
4mod avatars;
5mod bot_partners;
5mod bot_partners;
6mod copilot;
6mod call_event;
7mod call_event;
7mod card_actions;
8mod card_actions;
8mod card_chart;
9mod card_chart;
crates/core/src/remote.rs +9 −0
@@ -1,5 +1,6 @@
1 1 use std::collections::HashMap;
2 2
3 use chatsvc::copilot::{Copilot, CopilotAsk};
3 4 use chatsvc::sound_settings::{SoundSettings, SoundSettingsClient};
4 5 use chatsvc::substrate_search::{
5 6 QueryRequest, QueryResults, SearchIdentity, SearchSession, SubstrateSearch, Suggestions,
@@ -481,6 +482,10 @@ pub trait Remote {
481 482 Err(Error::Unsupported("message languages"))
482 483 }
483 484
485 async fn ask_copilot(&self, _ask: &CopilotAsk) -> Result<String> {
486 Err(Error::Unsupported("Copilot"))
487 }
488
484 489 async fn translate_chat_messages(
485 490 &self,
486 491 _chat_id: &str,
@@ -1333,6 +1338,10 @@ impl Remote for Graph {
1333 1338 .await?)
1334 1339 }
1335 1340
1341 async fn ask_copilot(&self, ask: &CopilotAsk) -> Result<String> {
1342 Ok(Copilot::new(self.session()).ask(ask).await?)
1343 }
1344
1336 1345 async fn translate_chat_messages(
1337 1346 &self,
1338 1347 chat_id: &str,
@@ -1,5 +1,6 @@
1use std::collections::HashMap;
1use std::collections::HashMap;
2
2
3use chatsvc::copilot::{Copilot, CopilotAsk};
3use chatsvc::sound_settings::{SoundSettings, SoundSettingsClient};
4use chatsvc::sound_settings::{SoundSettings, SoundSettingsClient};
4use chatsvc::substrate_search::{
5use chatsvc::substrate_search::{
5 QueryRequest, QueryResults, SearchIdentity, SearchSession, SubstrateSearch, Suggestions,
6 QueryRequest, QueryResults, SearchIdentity, SearchSession, SubstrateSearch, Suggestions,
@@ -481,6 +482,10 @@ pub trait Remote {
481 Err(Error::Unsupported("message languages"))
482 Err(Error::Unsupported("message languages"))
482 }
483 }
483
484
485 async fn ask_copilot(&self, _ask: &CopilotAsk) -> Result<String> {
486 Err(Error::Unsupported("Copilot"))
487 }
488
484 async fn translate_chat_messages(
489 async fn translate_chat_messages(
485 &self,
490 &self,
486 _chat_id: &str,
491 _chat_id: &str,
@@ -1333,6 +1338,10 @@ impl Remote for Graph {
1333 .await?)
1338 .await?)
1334 }
1339 }
1335
1340
1341 async fn ask_copilot(&self, ask: &CopilotAsk) -> Result<String> {
1342 Ok(Copilot::new(self.session()).ask(ask).await?)
1343 }
1344
1336 async fn translate_chat_messages(
1345 async fn translate_chat_messages(
1337 &self,
1346 &self,
1338 chat_id: &str,
1347 chat_id: &str,
crates/session/assets/fetch.js +41 −0
@@ -103,7 +103,48 @@
103 103 const {token, refreshError} = await acquire(resource, scope);
104 104 const page = {visibility: document.visibilityState, plain, sealed: sealed.length, opened};
105 105 if (!token) return {noToken: true, refreshError, page};
106 const exchange = (request) => new Promise((resolve) => {
107 const separator = '\u001e';
108 const {handshake, invocations, doneTypes, timeoutMs} = request.signalr;
109 const received = [];
110 let socket = null, settled = false, shookHands = false;
111 const finish = (status) => {
112 if (settled) return;
113 settled = true;
114 clearTimeout(timer);
115 try { socket && socket.close(); } catch (error) {}
116 resolve({status, body: received});
117 };
118 const timer = setTimeout(() => finish(504), timeoutMs);
119 try {
120 socket = new WebSocket(request.url + (request.url.includes('?') ? '&' : '?') + 'access_token=' + encodeURIComponent(token));
121 } catch (error) {
122 clearTimeout(timer);
123 resolve({status: 0, body: String(error)});
124 return;
125 }
126 socket.onopen = () => socket.send(handshake + separator);
127 socket.onmessage = (event) => {
128 for (const part of String(event.data).split(separator)) {
129 let message;
130 try { message = part ? JSON.parse(part) : null; } catch (error) { message = null; }
131 if (!message) continue;
132 if (!shookHands) {
133 shookHands = true;
134 if (message.error) { received.push(message); finish(502); return; }
135 invocations.forEach((invocation) => socket.send(invocation + separator));
136 continue;
137 }
138 if (message.type === 6) { socket.send('{"type":6}' + separator); continue; }
139 received.push(message);
140 if (doneTypes.includes(message.type)) finish(200);
141 }
142 };
143 socket.onerror = () => finish(0);
144 socket.onclose = () => finish(received.length ? 200 : 0);
145 });
106 146 const run = async (request) => {
147 if (request.signalr) return exchange(request);
107 148 try {
108 149 let requestBody = request.body;
109 150 for (const extra of request.bodyTokens || []) {
@@ -103,7 +103,48 @@
103 const {token, refreshError} = await acquire(resource, scope);
103 const {token, refreshError} = await acquire(resource, scope);
104 const page = {visibility: document.visibilityState, plain, sealed: sealed.length, opened};
104 const page = {visibility: document.visibilityState, plain, sealed: sealed.length, opened};
105 if (!token) return {noToken: true, refreshError, page};
105 if (!token) return {noToken: true, refreshError, page};
106 const exchange = (request) => new Promise((resolve) => {
107 const separator = '\u001e';
108 const {handshake, invocations, doneTypes, timeoutMs} = request.signalr;
109 const received = [];
110 let socket = null, settled = false, shookHands = false;
111 const finish = (status) => {
112 if (settled) return;
113 settled = true;
114 clearTimeout(timer);
115 try { socket && socket.close(); } catch (error) {}
116 resolve({status, body: received});
117 };
118 const timer = setTimeout(() => finish(504), timeoutMs);
119 try {
120 socket = new WebSocket(request.url + (request.url.includes('?') ? '&' : '?') + 'access_token=' + encodeURIComponent(token));
121 } catch (error) {
122 clearTimeout(timer);
123 resolve({status: 0, body: String(error)});
124 return;
125 }
126 socket.onopen = () => socket.send(handshake + separator);
127 socket.onmessage = (event) => {
128 for (const part of String(event.data).split(separator)) {
129 let message;
130 try { message = part ? JSON.parse(part) : null; } catch (error) { message = null; }
131 if (!message) continue;
132 if (!shookHands) {
133 shookHands = true;
134 if (message.error) { received.push(message); finish(502); return; }
135 invocations.forEach((invocation) => socket.send(invocation + separator));
136 continue;
137 }
138 if (message.type === 6) { socket.send('{"type":6}' + separator); continue; }
139 received.push(message);
140 if (doneTypes.includes(message.type)) finish(200);
141 }
142 };
143 socket.onerror = () => finish(0);
144 socket.onclose = () => finish(received.length ? 200 : 0);
145 });
106 const run = async (request) => {
146 const run = async (request) => {
147 if (request.signalr) return exchange(request);
107 try {
148 try {
108 let requestBody = request.body;
149 let requestBody = request.body;
109 for (const extra of request.bodyTokens || []) {
150 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};
15 pub use request::{ApiResponse, BodyToken, Method, Request, SignalrExchange};
16 16 pub use scope::{GRAPH, IC3, 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};
15pub use request::{ApiResponse, BodyToken, Method, Request, SignalrExchange};
16pub use scope::{GRAPH, IC3, OUTLOOK, PRESENCE, SPACES, Scope};
16pub use scope::{GRAPH, IC3, 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 +24 −0
@@ -29,6 +29,18 @@ pub struct BodyToken {
29 29 pub placeholder: String,
30 30 }
31 31
32 /// A SignalR JSON-protocol exchange over a WebSocket opened in the page with the token in the query.
33 /// The answer body is the list of received messages, up to the first whose type is in `done_types`.
34 #[derive(Debug, Clone, PartialEq, Eq, Serialize)]
35 pub struct SignalrExchange {
36 pub handshake: String,
37 pub invocations: Vec<String>,
38 #[serde(rename = "doneTypes")]
39 pub done_types: Vec<u8>,
40 #[serde(rename = "timeoutMs")]
41 pub timeout_ms: u64,
42 }
43
32 44 #[derive(Debug, Clone)]
33 45 pub struct Request {
34 46 pub method: Method,
@@ -39,9 +51,17 @@ pub struct Request {
39 51 pub anonymous: bool,
40 52 pub body_base64: Option<String>,
41 53 pub body_tokens: Vec<BodyToken>,
54 pub signalr: Option<SignalrExchange>,
42 55 }
43 56
44 57 impl Request {
58 pub fn signalr(url: impl Into<String>, exchange: SignalrExchange) -> Self {
59 Request {
60 signalr: Some(exchange),
61 ..Request::get(url)
62 }
63 }
64
45 65 /// A successful answer carries `{"base64": .., "contentType": ..}` as its body.
46 66 pub fn binary_get(url: impl Into<String>) -> Self {
47 67 Request {
@@ -60,6 +80,7 @@ impl Request {
60 80 anonymous: false,
61 81 body_base64: None,
62 82 body_tokens: Vec::new(),
83 signalr: None,
63 84 }
64 85 }
65 86
@@ -110,6 +131,7 @@ impl Request {
110 131 anonymous: false,
111 132 body_base64: None,
112 133 body_tokens: Vec::new(),
134 signalr: None,
113 135 }
114 136 }
115 137 }
@@ -139,6 +161,7 @@ pub(crate) struct WireRequest<'a> {
139 161 pub anonymous: bool,
140 162 #[serde(rename = "bodyTokens")]
141 163 pub body_tokens: &'a [BodyToken],
164 pub signalr: Option<&'a SignalrExchange>,
142 165 }
143 166
144 167 impl<'a> From<&'a Request> for WireRequest<'a> {
@@ -160,6 +183,7 @@ impl<'a> From<&'a Request> for WireRequest<'a> {
160 183 binary: request.binary,
161 184 anonymous: request.anonymous,
162 185 body_tokens: &request.body_tokens,
186 signalr: request.signalr.as_ref(),
163 187 }
164 188 }
165 189 }
@@ -29,6 +29,18 @@ pub struct BodyToken {
29 pub placeholder: String,
29 pub placeholder: String,
30}
30}
31
31
32/// A SignalR JSON-protocol exchange over a WebSocket opened in the page with the token in the query.
33/// The answer body is the list of received messages, up to the first whose type is in `done_types`.
34#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
35pub struct SignalrExchange {
36 pub handshake: String,
37 pub invocations: Vec<String>,
38 #[serde(rename = "doneTypes")]
39 pub done_types: Vec<u8>,
40 #[serde(rename = "timeoutMs")]
41 pub timeout_ms: u64,
42}
43
32#[derive(Debug, Clone)]
44#[derive(Debug, Clone)]
33pub struct Request {
45pub struct Request {
34 pub method: Method,
46 pub method: Method,
@@ -39,9 +51,17 @@ pub struct Request {
39 pub anonymous: bool,
51 pub anonymous: bool,
40 pub body_base64: Option<String>,
52 pub body_base64: Option<String>,
41 pub body_tokens: Vec<BodyToken>,
53 pub body_tokens: Vec<BodyToken>,
54 pub signalr: Option<SignalrExchange>,
42}
55}
43
56
44impl Request {
57impl Request {
58 pub fn signalr(url: impl Into<String>, exchange: SignalrExchange) -> Self {
59 Request {
60 signalr: Some(exchange),
61 ..Request::get(url)
62 }
63 }
64
45 /// A successful answer carries `{"base64": .., "contentType": ..}` as its body.
65 /// A successful answer carries `{"base64": .., "contentType": ..}` as its body.
46 pub fn binary_get(url: impl Into<String>) -> Self {
66 pub fn binary_get(url: impl Into<String>) -> Self {
47 Request {
67 Request {
@@ -60,6 +80,7 @@ impl Request {
60 anonymous: false,
80 anonymous: false,
61 body_base64: None,
81 body_base64: None,
62 body_tokens: Vec::new(),
82 body_tokens: Vec::new(),
83 signalr: None,
63 }
84 }
64 }
85 }
65
86
@@ -110,6 +131,7 @@ impl Request {
110 anonymous: false,
131 anonymous: false,
111 body_base64: None,
132 body_base64: None,
112 body_tokens: Vec::new(),
133 body_tokens: Vec::new(),
134 signalr: None,
113 }
135 }
114 }
136 }
115}
137}
@@ -139,6 +161,7 @@ pub(crate) struct WireRequest<'a> {
139 pub anonymous: bool,
161 pub anonymous: bool,
140 #[serde(rename = "bodyTokens")]
162 #[serde(rename = "bodyTokens")]
141 pub body_tokens: &'a [BodyToken],
163 pub body_tokens: &'a [BodyToken],
164 pub signalr: Option<&'a SignalrExchange>,
142}
165}
143
166
144impl<'a> From<&'a Request> for WireRequest<'a> {
167impl<'a> From<&'a Request> for WireRequest<'a> {
@@ -160,6 +183,7 @@ impl<'a> From<&'a Request> for WireRequest<'a> {
160 binary: request.binary,
183 binary: request.binary,
161 anonymous: request.anonymous,
184 anonymous: request.anonymous,
162 body_tokens: &request.body_tokens,
185 body_tokens: &request.body_tokens,
186 signalr: request.signalr.as_ref(),
163 }
187 }
164 }
188 }
165}
189}