feat(cards): run bot card actions, card and URL dialogs, real bot names
- Action.Submit, Action.Execute, ShowCard and ToggleVisibility work.
All bot actions go to chatsvc agents/{bot}/invoke (messageback, task/fetch,
task/submit, adaptiveCard/action); buttons show busy, done and error.
- Execute answers replace the card; message answers show under it.
- Card task dialogs open in-app; URL task dialogs open in a WebView2 window
that hosts the Teams JS SDK (initialize, context, SSO token, submit, resize).
- chatentitlements gives the app id, the real app name and its icon.
- Messages keep the sender application id to match a bot to its app.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@@ -274,6 +274,7 @@ dependencies = [
274
274
"tempfile",
275
275
"tokio",
276
276
"tray-icon",
277
"uuid",
277
278
"webview",
278
279
"windows 0.62.2",
279
280
]
@@ -274,6 +274,7 @@ dependencies = [274
"tempfile",274
"tempfile",275
"tokio",275
"tokio",276
"tray-icon",276
"tray-icon",277
"uuid",277
"webview",278
"webview",278
"windows 0.62.2",279
"windows 0.62.2",279
]280
]@@ -14,7 +14,7 @@ It does chats and channels. Calls, meetings and channel tabs are planned (see [R
14
14
- Send, edit, delete, react, quote-reply, @mentions
15
15
- Rich text composer: format bar over a selection, `Ctrl+B` / `Ctrl+I` / `Ctrl+U`, lists, quotes, code; Markdown converts as you type or paste
16
16
- Emoji by `:` code with English codes and German aliases, `:thumbsup:` and `:)` convert as you type
17
- Inline images, file cards, Adaptive Cards (layout, links, images; only open-URL buttons work)
17
- Inline images, file cards, Adaptive Cards (layout, links, images, buttons: submit, execute, show card, toggle; task dialogs)
18
18
- Read receipts, presence (last known status shown at start), unread jump
19
19
- Select and copy message text, `Ctrl+A` in the composer
20
20
- Local full-text search and a `Ctrl+K` switcher, served from the cache
@@ -14,7 +14,7 @@ It does chats and channels. Calls, meetings and channel tabs are planned (see [R14
- Send, edit, delete, react, quote-reply, @mentions14
- Send, edit, delete, react, quote-reply, @mentions15
- Rich text composer: format bar over a selection, `Ctrl+B` / `Ctrl+I` / `Ctrl+U`, lists, quotes, code; Markdown converts as you type or paste15
- Rich text composer: format bar over a selection, `Ctrl+B` / `Ctrl+I` / `Ctrl+U`, lists, quotes, code; Markdown converts as you type or paste16
- Emoji by `:` code with English codes and German aliases, `:thumbsup:` and `:)` convert as you type16
- Emoji by `:` code with English codes and German aliases, `:thumbsup:` and `:)` convert as you type17
- Inline images, file cards, Adaptive Cards (layout, links, images; only open-URL buttons work)17
- Inline images, file cards, Adaptive Cards (layout, links, images, buttons: submit, execute, show card, toggle; task dialogs)18
- Read receipts, presence (last known status shown at start), unread jump18
- Read receipts, presence (last known status shown at start), unread jump19
- Select and copy message text, `Ctrl+A` in the composer19
- Select and copy message text, `Ctrl+A` in the composer20
- Local full-text search and a `Ctrl+K` switcher, served from the cache20
- Local full-text search and a `Ctrl+K` switcher, served from the cache@@ -76,7 +76,7 @@ Feature parity with the Microsoft Teams desktop client.
76
76
| Unread jump with New divider | Done | |
77
77
| Read receipts | Done | |
78
78
| Select and copy message text | Done | |
79
| Adaptive Cards | Partial | Rendered as cards; only open-URL buttons work |
79
| Adaptive Cards | Partial | Buttons work (submit, execute, show card, toggle, task dialog card). URL task dialogs run in a hosted window on Windows (Teams JS SDK host, see docs/research/card-actions.md), in the browser on Linux. Missing: input fields |
80
80
| Typing indicator | Missing | Event arrives, ignored |
81
81
| Link previews | Missing | |
82
82
| Loop components | Missing | |
@@ -76,7 +76,7 @@ Feature parity with the Microsoft Teams desktop client.76
| Unread jump with New divider | Done | |76
| Unread jump with New divider | Done | |77
| Read receipts | Done | |77
| Read receipts | Done | |78
| Select and copy message text | Done | |78
| Select and copy message text | Done | |79
| Adaptive Cards | Partial | Rendered as cards; only open-URL buttons work |79
| Adaptive Cards | Partial | Buttons work (submit, execute, show card, toggle, task dialog card). URL task dialogs run in a hosted window on Windows (Teams JS SDK host, see docs/research/card-actions.md), in the browser on Linux. Missing: input fields |80
| Typing indicator | Missing | Event arrives, ignored |80
| Typing indicator | Missing | Event arrives, ignored |81
| Link previews | Missing | |81
| Link previews | Missing | |82
| Loop components | Missing | |82
| Loop components | Missing | |@@ -32,6 +32,7 @@ tokio.workspace = true
32
32
image = { version = "0.25", default-features = false, features = ["bmp", "jpeg", "png", "webp"] }
33
33
34
34
[target.'cfg(windows)'.dependencies]
35
uuid.workspace = true
35
36
webview.workspace = true
36
37
raw-window-handle = "0.6"
37
38
rodio = { version = "0.22", default-features = false, features = ["playback", "mp3"] }
@@ -32,6 +32,7 @@ tokio.workspace = true32
image = { version = "0.25", default-features = false, features = ["bmp", "jpeg", "png", "webp"] }32
image = { version = "0.25", default-features = false, features = ["bmp", "jpeg", "png", "webp"] }33
33
34
[target.'cfg(windows)'.dependencies]34
[target.'cfg(windows)'.dependencies]35
uuid.workspace = true35
webview.workspace = true36
webview.workspace = true36
raw-window-handle = "0.6"37
raw-window-handle = "0.6"37
rodio = { version = "0.22", default-features = false, features = ["playback", "mp3"] }38
rodio = { version = "0.22", default-features = false, features = ["playback", "mp3"] }@@ -1,13 +1,14 @@
1
use std::collections::HashSet;
1
use std::collections::{HashMap, HashSet};
2
2
use std::sync::Arc;
3
3
use std::time::Instant;
4
4
5
5
use chrono::{DateTime, Utc};
6
6
use gpui_kit::*;
7
7
use store::{ChatRecord, Sidebar, Store};
8
use teams_core::{CoreEvent, ImageRef};
8
use teams_core::{ChatApp, CoreEvent, ImageRef};
9
9
10
10
use crate::backend::{BackendEvent, ConnectionState, Engine, LiveState};
11
use crate::card_state::{CardState, TaskDialogState};
11
12
use crate::data::{self, Directory};
12
13
13
14
const COLLAPSED_META_KEY: &str = "ui.collapsed_sections";
@@ -34,6 +35,8 @@ pub enum AppEvent {
34
35
Jump,
35
36
Status,
36
37
Directory,
38
Cards(String),
39
TaskDialog,
37
40
}
38
41
39
42
#[derive(Debug, Clone, Copy, Default)]
@@ -58,8 +61,16 @@ pub struct AppState {
58
61
pub collapsed: HashSet<String>,
59
62
pub start_on_channels: bool,
60
63
pub pending_jump: Option<(String, String)>,
64
pub cards: CardState,
65
pub task_dialog: Option<TaskDialogState>,
66
pub bot_apps: HashMap<String, Vec<ChatApp>>,
67
pub bot_apps_pending: HashSet<String>,
61
68
}
62
69
70
pub struct AppHandle(pub Entity<AppState>);
71
72
impl Global for AppHandle {}
73
63
74
impl EventEmitter<AppEvent> for AppState {}
64
75
65
76
pub fn chat_title(chat: &ChatRecord) -> String {
@@ -115,6 +126,10 @@ impl AppState {
115
126
collapsed: HashSet::new(),
116
127
start_on_channels: false,
117
128
pending_jump: None,
129
cards: CardState::default(),
130
task_dialog: None,
131
bot_apps: HashMap::new(),
132
bot_apps_pending: HashSet::new(),
118
133
};
119
134
state.collapsed = state.load_collapsed();
120
135
if !mode.demo {
@@ -408,6 +423,7 @@ impl AppState {
408
423
pub fn reload_sidebar(&mut self, cx: &mut Context<Self>) {
409
424
if let Ok(sidebar) = self.store.sidebar() {
410
425
self.sidebar = sidebar;
426
self.apply_bot_titles();
411
427
}
412
428
if !self.mode.demo {
413
429
self.reload_directory();
@@ -1,13 +1,14 @@1
use std::collections::HashSet;1
use std::collections::{HashMap, HashSet};2
use std::sync::Arc;2
use std::sync::Arc;3
use std::time::Instant;3
use std::time::Instant;4
4
5
use chrono::{DateTime, Utc};5
use chrono::{DateTime, Utc};6
use gpui_kit::*;6
use gpui_kit::*;7
use store::{ChatRecord, Sidebar, Store};7
use store::{ChatRecord, Sidebar, Store};8
use teams_core::{CoreEvent, ImageRef};8
use teams_core::{ChatApp, CoreEvent, ImageRef};9
9
10
use crate::backend::{BackendEvent, ConnectionState, Engine, LiveState};10
use crate::backend::{BackendEvent, ConnectionState, Engine, LiveState};11
use crate::card_state::{CardState, TaskDialogState};11
use crate::data::{self, Directory};12
use crate::data::{self, Directory};12
13
13
const COLLAPSED_META_KEY: &str = "ui.collapsed_sections";14
const COLLAPSED_META_KEY: &str = "ui.collapsed_sections";@@ -34,6 +35,8 @@ pub enum AppEvent {34
Jump,35
Jump,35
Status,36
Status,36
Directory,37
Directory,38
Cards(String),39
TaskDialog,37
}40
}38
41
39
#[derive(Debug, Clone, Copy, Default)]42
#[derive(Debug, Clone, Copy, Default)]@@ -58,8 +61,16 @@ pub struct AppState {58
pub collapsed: HashSet<String>,61
pub collapsed: HashSet<String>,59
pub start_on_channels: bool,62
pub start_on_channels: bool,60
pub pending_jump: Option<(String, String)>,63
pub pending_jump: Option<(String, String)>,64
pub cards: CardState,65
pub task_dialog: Option<TaskDialogState>,66
pub bot_apps: HashMap<String, Vec<ChatApp>>,67
pub bot_apps_pending: HashSet<String>,61
}68
}62
69
70
pub struct AppHandle(pub Entity<AppState>);71
72
impl Global for AppHandle {}73
63
impl EventEmitter<AppEvent> for AppState {}74
impl EventEmitter<AppEvent> for AppState {}64
75
65
pub fn chat_title(chat: &ChatRecord) -> String {76
pub fn chat_title(chat: &ChatRecord) -> String {@@ -115,6 +126,10 @@ impl AppState {115
collapsed: HashSet::new(),126
collapsed: HashSet::new(),116
start_on_channels: false,127
start_on_channels: false,117
pending_jump: None,128
pending_jump: None,129
cards: CardState::default(),130
task_dialog: None,131
bot_apps: HashMap::new(),132
bot_apps_pending: HashSet::new(),118
};133
};119
state.collapsed = state.load_collapsed();134
state.collapsed = state.load_collapsed();120
if !mode.demo {135
if !mode.demo {@@ -408,6 +423,7 @@ impl AppState {408
pub fn reload_sidebar(&mut self, cx: &mut Context<Self>) {423
pub fn reload_sidebar(&mut self, cx: &mut Context<Self>) {409
if let Ok(sidebar) = self.store.sidebar() {424
if let Ok(sidebar) = self.store.sidebar() {410
self.sidebar = sidebar;425
self.sidebar = sidebar;426
self.apply_bot_titles();411
}427
}412
if !self.mode.demo {428
if !self.mode.demo {413
self.reload_directory();429
self.reload_directory();@@ -0,0 +1,503 @@
1
use gpui_kit::*;
2
use serde_json::Value;
3
use teams_core::{
4
AdaptiveCard, CardAction, CardActionKind, CardActionOutcome, ChatApp, TaskDialog,
5
TaskDialogKind, adaptive_cards,
6
};
7
use tokio::sync::oneshot;
8
9
use crate::app_state::{AppEvent, AppState};
10
use crate::card_state::{
11
ActionPhase, BotIdentity, CardOverride, CardScope, DONE_HOLD, Surface, TaskDialogState,
12
short_reason,
13
};
14
use crate::data::{is_one_on_one, others};
15
use crate::runtime;
16
use crate::task_dialog::{UrlDialog, UrlDialogNext, open_url_dialog};
17
18
const NOT_CONNECTED: &str = "Not connected";
19
const READ_ONLY: &str = "Read-only mode";
20
const CANCELLED: &str = "Cancelled";
21
const DIALOG_MESSAGE_HOLD: std::time::Duration = std::time::Duration::from_millis(2200);
22
23
pub enum CardTask {
24
Action(CardAction),
25
Submit(Value),
26
}
27
28
pub type CardAnswer = Result<(CardActionOutcome, Option<(ChatApp, String)>), String>;
29
30
impl AppState {
31
pub fn run_card_action(
32
&mut self,
33
scope: CardScope,
34
action_key: String,
35
action: CardAction,
36
cx: &mut Context<Self>,
37
) {
38
let task = match (&scope.surface, &action.kind) {
39
(Surface::Dialog, CardActionKind::Submit(submit)) => {
40
CardTask::Submit(submit.data.clone())
41
}
42
_ => CardTask::Action(action),
43
};
44
if self.cards.is_busy(&action_key) {
45
return;
46
}
47
self.cards.set_phase(&action_key, ActionPhase::Busy);
48
self.cards.clear_note(&scope.card_key());
49
self.announce_cards(&scope, cx);
50
let answer = self.card_answer(&scope, task);
51
cx.spawn(async move |this, cx| {
52
let answer = match answer {
53
Some(receiver) => receiver.await.unwrap_or_else(|_| Err(CANCELLED.to_owned())),
54
None => Err(NOT_CONNECTED.to_owned()),
55
};
56
this.update(cx, |state, cx| {
57
state.finish_card_task(scope, action_key, answer, cx)
58
})
59
.ok();
60
})
61
.detach();
62
}
63
64
fn card_answer(
65
&self,
66
scope: &CardScope,
67
task: CardTask,
68
) -> Option<oneshot::Receiver<CardAnswer>> {
69
if self.mode.demo {
70
return Some(runtime::spawn(crate::demo::card_answer(task)));
71
}
72
if self.mode.read_only {
73
return Some(runtime::spawn(async { Err(READ_ONLY.to_owned()) }));
74
}
75
let engine = self.engine.clone()?;
76
let (conversation_id, message_id) =
77
(scope.conversation_id.clone(), scope.message_id.clone());
78
Some(runtime::spawn(async move {
79
let outcome = match task {
80
CardTask::Action(action) => {
81
engine
82
.card_action(&conversation_id, &message_id, &action)
83
.await
84
}
85
CardTask::Submit(data) => {
86
engine
87
.task_submit(&conversation_id, &message_id, data)
88
.await
89
}
90
}
91
.map_err(|error| short_reason(&error.to_string()))?;
92
let app = engine.card_app(&conversation_id, &message_id).await.ok();
93
Ok((outcome, app))
94
}))
95
}
96
97
fn finish_card_task(
98
&mut self,
99
scope: CardScope,
100
action_key: String,
101
answer: CardAnswer,
102
cx: &mut Context<Self>,
103
) {
104
let (outcome, app) = match answer {
105
Ok(answer) => answer,
106
Err(reason) => {
107
self.fail_card_action(&scope, &action_key, reason, cx);
108
return;
109
}
110
};
111
let in_dialog = scope.surface == Surface::Dialog;
112
match outcome {
113
CardActionOutcome::Sent => {
114
self.mark_done(&scope, &action_key, cx);
115
if in_dialog {
116
self.close_task_dialog(cx);
117
}
118
}
119
CardActionOutcome::ReplaceCard(json) => {
120
if self.replace_card(&scope, &json, cx) {
121
self.mark_done(&scope, &action_key, cx);
122
} else {
123
self.fail_card_action(&scope, &action_key, "Unreadable card".into(), cx);
124
}
125
}
126
CardActionOutcome::Message(text) => {
127
self.mark_done(&scope, &action_key, cx);
128
self.note_card(&scope, text, cx);
129
if in_dialog {
130
self.close_task_dialog_later(cx);
131
}
132
}
133
CardActionOutcome::Dialog(dialog) => {
134
self.mark_done(&scope, &action_key, cx);
135
self.open_task_dialog(&scope, dialog, app, cx);
136
}
137
CardActionOutcome::Failed(reason) => {
138
self.fail_card_action(&scope, &action_key, reason, cx)
139
}
140
}
141
}
142
143
#[cfg_attr(not(windows), allow(dead_code))]
144
pub fn submit_url_dialog(
145
&mut self,
146
scope: CardScope,
147
result: Value,
148
cx: &mut Context<Self>,
149
) -> Task<UrlDialogNext> {
150
let answer = self.card_answer(&scope, CardTask::Submit(result));
151
cx.spawn(async move |this, cx| {
152
let answer = match answer {
153
Some(receiver) => receiver.await.unwrap_or_else(|_| Err(CANCELLED.to_owned())),
154
None => Err(NOT_CONNECTED.to_owned()),
155
};
156
this.update(cx, |state, cx| {
157
state.finish_url_dialog_submit(&scope, answer, cx)
158
})
159
.unwrap_or(UrlDialogNext::Close)
160
})
161
}
162
163
#[cfg_attr(not(windows), allow(dead_code))]
164
fn finish_url_dialog_submit(
165
&mut self,
166
scope: &CardScope,
167
answer: CardAnswer,
168
cx: &mut Context<Self>,
169
) -> UrlDialogNext {
170
let (outcome, app) = match answer {
171
Ok(answer) => answer,
172
Err(reason) => (CardActionOutcome::Failed(reason), None),
173
};
174
match outcome {
175
CardActionOutcome::Sent => {}
176
CardActionOutcome::ReplaceCard(json) => {
177
self.replace_card(scope, &json, cx);
178
}
179
CardActionOutcome::Message(text) => self.note_card(scope, text, cx),
180
CardActionOutcome::Failed(reason) => self.note_card(scope, short_reason(&reason), cx),
181
CardActionOutcome::Dialog(dialog) => {
182
if let TaskDialogKind::Url { url, .. } = &dialog.kind {
183
return UrlDialogNext::Navigate {
184
url: url.clone(),
185
width: dialog.width,
186
height: dialog.height,
187
};
188
}
189
self.open_task_dialog(scope, dialog, app, cx);
190
}
191
}
192
UrlDialogNext::Close
193
}
194
195
fn note_card(&mut self, scope: &CardScope, text: String, cx: &mut Context<Self>) {
196
self.cards.set_note(&scope.card_key(), text);
197
self.announce_cards(scope, cx);
198
}
199
200
fn fail_card_action(
201
&mut self,
202
scope: &CardScope,
203
action_key: &str,
204
reason: String,
205
cx: &mut Context<Self>,
206
) {
207
self.cards
208
.set_phase(action_key, ActionPhase::Failed(short_reason(&reason)));
209
self.announce_cards(scope, cx);
210
}
211
212
fn mark_done(&mut self, scope: &CardScope, action_key: &str, cx: &mut Context<Self>) {
213
self.cards.set_phase(action_key, ActionPhase::Done);
214
self.announce_cards(scope, cx);
215
let (scope, action_key) = (scope.clone(), action_key.to_owned());
216
cx.spawn(async move |this, cx| {
217
cx.background_executor().timer(DONE_HOLD).await;
218
this.update(cx, |state, cx| {
219
state.cards.clear_done(&action_key);
220
state.announce_cards(&scope, cx);
221
})
222
.ok();
223
})
224
.detach();
225
}
226
227
fn announce_cards(&mut self, scope: &CardScope, cx: &mut Context<Self>) {
228
cx.emit(AppEvent::Cards(scope.conversation_id.clone()));
229
cx.notify();
230
}
231
232
fn replace_card(&mut self, scope: &CardScope, json: &str, cx: &mut Context<Self>) -> bool {
233
let Some(card) = AdaptiveCard::parse(json) else {
234
return false;
235
};
236
if scope.surface == Surface::Dialog {
237
if let Some(dialog) = self.task_dialog.as_mut() {
238
dialog.card = card;
239
}
240
self.announce_cards(scope, cx);
241
return true;
242
}
243
let Some(record) = self
244
.store
245
.messages_by_id(
246
&scope.conversation_id,
247
std::slice::from_ref(&scope.message_id),
248
)
249
.ok()
250
.and_then(|mut records| records.remove(&scope.message_id))
251
else {
252
return false;
253
};
254
let mut cards = adaptive_cards(&record);
255
match cards.get_mut(scope.card_index) {
256
Some(slot) => *slot = card,
257
None => cards.push(card),
258
}
259
self.cards.set_override(
260
&scope.conversation_id,
261
&scope.message_id,
262
CardOverride {
263
basis: record.attachments_json,
264
cards,
265
},
266
);
267
self.announce_cards(scope, cx);
268
true
269
}
270
271
fn open_task_dialog(
272
&mut self,
273
scope: &CardScope,
274
dialog: TaskDialog,
275
app: Option<(ChatApp, String)>,
276
cx: &mut Context<Self>,
277
) {
278
let app_name = app.as_ref().map(|(app, _)| app.name.clone());
279
let title = dialog.title.clone().or(app_name).unwrap_or_default();
280
let in_dialog = scope.surface == Surface::Dialog;
281
match dialog.kind {
282
TaskDialogKind::Card(json) => {
283
let Some(card) = AdaptiveCard::parse(&json) else {
284
return;
285
};
286
self.cards.clear_card(&scope.card_key());
287
self.task_dialog = Some(TaskDialogState {
288
title,
289
card,
290
scope: CardScope {
291
card_index: 0,
292
surface: Surface::Dialog,
293
..scope.clone()
294
},
295
width: dialog.width,
296
height: dialog.height,
297
});
298
cx.emit(AppEvent::TaskDialog);
299
cx.notify();
300
}
301
TaskDialogKind::Url { url, fallback_url } => {
302
let (app_id, bot_id, web_application_resource) = match app {
303
Some((app, bot_id)) => (app.app_id, bot_id, app.web_application_resource),
304
None => (String::new(), String::new(), None),
305
};
306
open_url_dialog(
307
UrlDialog {
308
title,
309
url,
310
fallback_url,
311
width: dialog.width,
312
height: dialog.height,
313
app_id,
314
bot_id,
315
scope: scope.clone(),
316
web_application_resource,
317
},
318
cx,
319
);
320
if in_dialog {
321
self.close_task_dialog(cx);
322
}
323
}
324
}
325
}
326
327
pub fn close_task_dialog(&mut self, cx: &mut Context<Self>) {
328
if self.task_dialog.take().is_some() {
329
self.cards.clear_card(&CardScope::dialog_key());
330
cx.emit(AppEvent::TaskDialog);
331
cx.notify();
332
}
333
}
334
335
fn close_task_dialog_later(&mut self, cx: &mut Context<Self>) {
336
cx.spawn(async move |this, cx| {
337
cx.background_executor().timer(DIALOG_MESSAGE_HOLD).await;
338
this.update(cx, |state, cx| state.close_task_dialog(cx))
339
.ok();
340
})
341
.detach();
342
}
343
344
pub fn toggle_card_elements(
345
&mut self,
346
scope: &CardScope,
347
root_key: &str,
348
elements: Vec<(String, bool, Option<bool>)>,
349
cx: &mut Context<Self>,
350
) {
351
for (element_id, initial, forced) in elements {
352
self.cards
353
.toggle_visibility(&format!("{root_key}/{element_id}"), initial, forced);
354
}
355
self.announce_cards(scope, cx);
356
}
357
358
pub fn toggle_show_card(
359
&mut self,
360
scope: &CardScope,
361
actions_key: &str,
362
index: usize,
363
cx: &mut Context<Self>,
364
) {
365
self.cards.toggle_open_card(actions_key, index);
366
self.announce_cards(scope, cx);
367
}
368
369
pub fn bot_identity(&self, conversation_id: &str, application_id: &str) -> Option<BotIdentity> {
370
let apps = self.bot_apps.get(conversation_id)?;
371
let matched = apps
372
.iter()
373
.find(|app| app.has_bot(application_id) || app.app_id == application_id);
374
let mut with_bots = apps.iter().filter(|app| !app.bot_ids.is_empty());
375
let app = match (matched, with_bots.next(), with_bots.next()) {
376
(Some(app), _, _) | (None, Some(app), None) => app,
377
_ => return None,
378
};
379
Some(BotIdentity {
380
name: app.name.clone(),
381
icon_url: app.small_image_url.clone(),
382
})
383
}
384
385
pub fn request_chat_apps(&mut self, conversation_id: &str, cx: &mut Context<Self>) {
386
if self.bot_apps.contains_key(conversation_id)
387
|| self.bot_apps_pending.contains(conversation_id)
388
{
389
return;
390
}
391
let Some(engine) = self.engine.clone() else {
392
return;
393
};
394
self.bot_apps_pending.insert(conversation_id.to_owned());
395
let conversation_id = conversation_id.to_owned();
396
let receiver = {
397
let conversation_id = conversation_id.clone();
398
runtime::spawn(async move { engine.chat_apps(&conversation_id).await })
399
};
400
cx.spawn(async move |this, cx| {
401
let apps = receiver.await.ok().and_then(Result::ok).unwrap_or_default();
402
this.update(cx, |state, cx| {
403
state.bot_apps_pending.remove(&conversation_id);
404
state.bot_apps.insert(conversation_id, apps);
405
state.apply_bot_titles();
406
cx.emit(AppEvent::Sidebar);
407
cx.emit(AppEvent::Directory);
408
cx.notify();
409
})
410
.ok();
411
})
412
.detach();
413
}
414
415
pub fn apply_bot_titles(&mut self) {
416
let me = self.directory.me.clone();
417
for chat in self.sidebar.chats.iter_mut() {
418
let Some(apps) = self.bot_apps.get(&chat.id) else {
419
continue;
420
};
421
if !is_one_on_one(chat) || !others(chat, me.as_ref()).is_empty() {
422
continue;
423
}
424
let mut with_bots = apps.iter().filter(|app| !app.bot_ids.is_empty());
425
if let (Some(app), None) = (with_bots.next(), with_bots.next()) {
426
chat.title = app.name.clone();
427
}
428
}
429
}
430
}
431
432
#[cfg(test)]
433
mod tests {
434
use std::sync::Arc;
435
436
use gpui_kit::{AppContext as _, TestAppContext};
437
use store::Store;
438
use teams_core::{CardActionOutcome, TaskDialog, TaskDialogKind};
439
440
use super::CardAnswer;
441
use crate::app_state::{AppState, Mode};
442
use crate::card_state::CardScope;
443
use crate::task_dialog::UrlDialogNext;
444
445
fn finish(cx: &mut TestAppContext, answer: CardAnswer) -> (UrlDialogNext, Option<String>) {
446
let store = Arc::new(Store::open_in_memory().unwrap());
447
let app = cx.update(|cx| cx.new(|_| AppState::new(store, Mode::default())));
448
let scope = CardScope::message("19:chat@thread.v2", "m1", 0);
449
cx.update(|cx| {
450
app.update(cx, |state, cx| {
451
let next = state.finish_url_dialog_submit(&scope, answer, cx);
452
(next, state.cards.note(&scope.card_key()).map(str::to_owned))
453
})
454
})
455
}
456
457
fn dialog(kind: TaskDialogKind) -> CardActionOutcome {
458
CardActionOutcome::Dialog(TaskDialog {
459
title: None,
460
width: 640,
461
height: 300,
462
kind,
463
})
464
}
465
466
#[gpui_kit::test]
467
fn a_sent_submit_closes_the_url_dialog(cx: &mut TestAppContext) {
468
let (next, note) = finish(cx, Ok((CardActionOutcome::Sent, None)));
469
assert_eq!(next, UrlDialogNext::Close);
470
assert_eq!(note, None);
471
}
472
473
#[gpui_kit::test]
474
fn a_message_answer_is_shown_on_the_card_and_closes_the_dialog(cx: &mut TestAppContext) {
475
let (next, note) = finish(cx, Ok((CardActionOutcome::Message("Saved".into()), None)));
476
assert_eq!(next, UrlDialogNext::Close);
477
assert_eq!(note.as_deref(), Some("Saved"));
478
}
479
480
#[gpui_kit::test]
481
fn a_failed_submit_is_shown_on_the_card(cx: &mut TestAppContext) {
482
let (next, note) = finish(cx, Err("Not connected".into()));
483
assert_eq!(next, UrlDialogNext::Close);
484
assert_eq!(note.as_deref(), Some("Not connected"));
485
}
486
487
#[gpui_kit::test]
488
fn a_continued_url_task_navigates_the_open_dialog(cx: &mut TestAppContext) {
489
let kind = TaskDialogKind::Url {
490
url: "https://bot.example/next".into(),
491
fallback_url: "https://bot.example/next".into(),
492
};
493
let (next, _) = finish(cx, Ok((dialog(kind), None)));
494
assert_eq!(
495
next,
496
UrlDialogNext::Navigate {
497
url: "https://bot.example/next".into(),
498
width: 640,
499
height: 300
500
}
501
);
502
}
503
}
@@ -0,0 +1,503 @@1
use gpui_kit::*;2
use serde_json::Value;3
use teams_core::{4
AdaptiveCard, CardAction, CardActionKind, CardActionOutcome, ChatApp, TaskDialog,5
TaskDialogKind, adaptive_cards,6
};7
use tokio::sync::oneshot;8
9
use crate::app_state::{AppEvent, AppState};10
use crate::card_state::{11
ActionPhase, BotIdentity, CardOverride, CardScope, DONE_HOLD, Surface, TaskDialogState,12
short_reason,13
};14
use crate::data::{is_one_on_one, others};15
use crate::runtime;16
use crate::task_dialog::{UrlDialog, UrlDialogNext, open_url_dialog};17
18
const NOT_CONNECTED: &str = "Not connected";19
const READ_ONLY: &str = "Read-only mode";20
const CANCELLED: &str = "Cancelled";21
const DIALOG_MESSAGE_HOLD: std::time::Duration = std::time::Duration::from_millis(2200);22
23
pub enum CardTask {24
Action(CardAction),25
Submit(Value),26
}27
28
pub type CardAnswer = Result<(CardActionOutcome, Option<(ChatApp, String)>), String>;29
30
impl AppState {31
pub fn run_card_action(32
&mut self,33
scope: CardScope,34
action_key: String,35
action: CardAction,36
cx: &mut Context<Self>,37
) {38
let task = match (&scope.surface, &action.kind) {39
(Surface::Dialog, CardActionKind::Submit(submit)) => {40
CardTask::Submit(submit.data.clone())41
}42
_ => CardTask::Action(action),43
};44
if self.cards.is_busy(&action_key) {45
return;46
}47
self.cards.set_phase(&action_key, ActionPhase::Busy);48
self.cards.clear_note(&scope.card_key());49
self.announce_cards(&scope, cx);50
let answer = self.card_answer(&scope, task);51
cx.spawn(async move |this, cx| {52
let answer = match answer {53
Some(receiver) => receiver.await.unwrap_or_else(|_| Err(CANCELLED.to_owned())),54
None => Err(NOT_CONNECTED.to_owned()),55
};56
this.update(cx, |state, cx| {57
state.finish_card_task(scope, action_key, answer, cx)58
})59
.ok();60
})61
.detach();62
}63
64
fn card_answer(65
&self,66
scope: &CardScope,67
task: CardTask,68
) -> Option<oneshot::Receiver<CardAnswer>> {69
if self.mode.demo {70
return Some(runtime::spawn(crate::demo::card_answer(task)));71
}72
if self.mode.read_only {73
return Some(runtime::spawn(async { Err(READ_ONLY.to_owned()) }));74
}75
let engine = self.engine.clone()?;76
let (conversation_id, message_id) =77
(scope.conversation_id.clone(), scope.message_id.clone());78
Some(runtime::spawn(async move {79
let outcome = match task {80
CardTask::Action(action) => {81
engine82
.card_action(&conversation_id, &message_id, &action)83
.await84
}85
CardTask::Submit(data) => {86
engine87
.task_submit(&conversation_id, &message_id, data)88
.await89
}90
}91
.map_err(|error| short_reason(&error.to_string()))?;92
let app = engine.card_app(&conversation_id, &message_id).await.ok();93
Ok((outcome, app))94
}))95
}96
97
fn finish_card_task(98
&mut self,99
scope: CardScope,100
action_key: String,101
answer: CardAnswer,102
cx: &mut Context<Self>,103
) {104
let (outcome, app) = match answer {105
Ok(answer) => answer,106
Err(reason) => {107
self.fail_card_action(&scope, &action_key, reason, cx);108
return;109
}110
};111
let in_dialog = scope.surface == Surface::Dialog;112
match outcome {113
CardActionOutcome::Sent => {114
self.mark_done(&scope, &action_key, cx);115
if in_dialog {116
self.close_task_dialog(cx);117
}118
}119
CardActionOutcome::ReplaceCard(json) => {120
if self.replace_card(&scope, &json, cx) {121
self.mark_done(&scope, &action_key, cx);122
} else {123
self.fail_card_action(&scope, &action_key, "Unreadable card".into(), cx);124
}125
}126
CardActionOutcome::Message(text) => {127
self.mark_done(&scope, &action_key, cx);128
self.note_card(&scope, text, cx);129
if in_dialog {130
self.close_task_dialog_later(cx);131
}132
}133
CardActionOutcome::Dialog(dialog) => {134
self.mark_done(&scope, &action_key, cx);135
self.open_task_dialog(&scope, dialog, app, cx);136
}137
CardActionOutcome::Failed(reason) => {138
self.fail_card_action(&scope, &action_key, reason, cx)139
}140
}141
}142
143
#[cfg_attr(not(windows), allow(dead_code))]144
pub fn submit_url_dialog(145
&mut self,146
scope: CardScope,147
result: Value,148
cx: &mut Context<Self>,149
) -> Task<UrlDialogNext> {150
let answer = self.card_answer(&scope, CardTask::Submit(result));151
cx.spawn(async move |this, cx| {152
let answer = match answer {153
Some(receiver) => receiver.await.unwrap_or_else(|_| Err(CANCELLED.to_owned())),154
None => Err(NOT_CONNECTED.to_owned()),155
};156
this.update(cx, |state, cx| {157
state.finish_url_dialog_submit(&scope, answer, cx)158
})159
.unwrap_or(UrlDialogNext::Close)160
})161
}162
163
#[cfg_attr(not(windows), allow(dead_code))]164
fn finish_url_dialog_submit(165
&mut self,166
scope: &CardScope,167
answer: CardAnswer,168
cx: &mut Context<Self>,169
) -> UrlDialogNext {170
let (outcome, app) = match answer {171
Ok(answer) => answer,172
Err(reason) => (CardActionOutcome::Failed(reason), None),173
};174
match outcome {175
CardActionOutcome::Sent => {}176
CardActionOutcome::ReplaceCard(json) => {177
self.replace_card(scope, &json, cx);178
}179
CardActionOutcome::Message(text) => self.note_card(scope, text, cx),180
CardActionOutcome::Failed(reason) => self.note_card(scope, short_reason(&reason), cx),181
CardActionOutcome::Dialog(dialog) => {182
if let TaskDialogKind::Url { url, .. } = &dialog.kind {183
return UrlDialogNext::Navigate {184
url: url.clone(),185
width: dialog.width,186
height: dialog.height,187
};188
}189
self.open_task_dialog(scope, dialog, app, cx);190
}191
}192
UrlDialogNext::Close193
}194
195
fn note_card(&mut self, scope: &CardScope, text: String, cx: &mut Context<Self>) {196
self.cards.set_note(&scope.card_key(), text);197
self.announce_cards(scope, cx);198
}199
200
fn fail_card_action(201
&mut self,202
scope: &CardScope,203
action_key: &str,204
reason: String,205
cx: &mut Context<Self>,206
) {207
self.cards208
.set_phase(action_key, ActionPhase::Failed(short_reason(&reason)));209
self.announce_cards(scope, cx);210
}211
212
fn mark_done(&mut self, scope: &CardScope, action_key: &str, cx: &mut Context<Self>) {213
self.cards.set_phase(action_key, ActionPhase::Done);214
self.announce_cards(scope, cx);215
let (scope, action_key) = (scope.clone(), action_key.to_owned());216
cx.spawn(async move |this, cx| {217
cx.background_executor().timer(DONE_HOLD).await;218
this.update(cx, |state, cx| {219
state.cards.clear_done(&action_key);220
state.announce_cards(&scope, cx);221
})222
.ok();223
})224
.detach();225
}226
227
fn announce_cards(&mut self, scope: &CardScope, cx: &mut Context<Self>) {228
cx.emit(AppEvent::Cards(scope.conversation_id.clone()));229
cx.notify();230
}231
232
fn replace_card(&mut self, scope: &CardScope, json: &str, cx: &mut Context<Self>) -> bool {233
let Some(card) = AdaptiveCard::parse(json) else {234
return false;235
};236
if scope.surface == Surface::Dialog {237
if let Some(dialog) = self.task_dialog.as_mut() {238
dialog.card = card;239
}240
self.announce_cards(scope, cx);241
return true;242
}243
let Some(record) = self244
.store245
.messages_by_id(246
&scope.conversation_id,247
std::slice::from_ref(&scope.message_id),248
)249
.ok()250
.and_then(|mut records| records.remove(&scope.message_id))251
else {252
return false;253
};254
let mut cards = adaptive_cards(&record);255
match cards.get_mut(scope.card_index) {256
Some(slot) => *slot = card,257
None => cards.push(card),258
}259
self.cards.set_override(260
&scope.conversation_id,261
&scope.message_id,262
CardOverride {263
basis: record.attachments_json,264
cards,265
},266
);267
self.announce_cards(scope, cx);268
true269
}270
271
fn open_task_dialog(272
&mut self,273
scope: &CardScope,274
dialog: TaskDialog,275
app: Option<(ChatApp, String)>,276
cx: &mut Context<Self>,277
) {278
let app_name = app.as_ref().map(|(app, _)| app.name.clone());279
let title = dialog.title.clone().or(app_name).unwrap_or_default();280
let in_dialog = scope.surface == Surface::Dialog;281
match dialog.kind {282
TaskDialogKind::Card(json) => {283
let Some(card) = AdaptiveCard::parse(&json) else {284
return;285
};286
self.cards.clear_card(&scope.card_key());287
self.task_dialog = Some(TaskDialogState {288
title,289
card,290
scope: CardScope {291
card_index: 0,292
surface: Surface::Dialog,293
..scope.clone()294
},295
width: dialog.width,296
height: dialog.height,297
});298
cx.emit(AppEvent::TaskDialog);299
cx.notify();300
}301
TaskDialogKind::Url { url, fallback_url } => {302
let (app_id, bot_id, web_application_resource) = match app {303
Some((app, bot_id)) => (app.app_id, bot_id, app.web_application_resource),304
None => (String::new(), String::new(), None),305
};306
open_url_dialog(307
UrlDialog {308
title,309
url,310
fallback_url,311
width: dialog.width,312
height: dialog.height,313
app_id,314
bot_id,315
scope: scope.clone(),316
web_application_resource,317
},318
cx,319
);320
if in_dialog {321
self.close_task_dialog(cx);322
}323
}324
}325
}326
327
pub fn close_task_dialog(&mut self, cx: &mut Context<Self>) {328
if self.task_dialog.take().is_some() {329
self.cards.clear_card(&CardScope::dialog_key());330
cx.emit(AppEvent::TaskDialog);331
cx.notify();332
}333
}334
335
fn close_task_dialog_later(&mut self, cx: &mut Context<Self>) {336
cx.spawn(async move |this, cx| {337
cx.background_executor().timer(DIALOG_MESSAGE_HOLD).await;338
this.update(cx, |state, cx| state.close_task_dialog(cx))339
.ok();340
})341
.detach();342
}343
344
pub fn toggle_card_elements(345
&mut self,346
scope: &CardScope,347
root_key: &str,348
elements: Vec<(String, bool, Option<bool>)>,349
cx: &mut Context<Self>,350
) {351
for (element_id, initial, forced) in elements {352
self.cards353
.toggle_visibility(&format!("{root_key}/{element_id}"), initial, forced);354
}355
self.announce_cards(scope, cx);356
}357
358
pub fn toggle_show_card(359
&mut self,360
scope: &CardScope,361
actions_key: &str,362
index: usize,363
cx: &mut Context<Self>,364
) {365
self.cards.toggle_open_card(actions_key, index);366
self.announce_cards(scope, cx);367
}368
369
pub fn bot_identity(&self, conversation_id: &str, application_id: &str) -> Option<BotIdentity> {370
let apps = self.bot_apps.get(conversation_id)?;371
let matched = apps372
.iter()373
.find(|app| app.has_bot(application_id) || app.app_id == application_id);374
let mut with_bots = apps.iter().filter(|app| !app.bot_ids.is_empty());375
let app = match (matched, with_bots.next(), with_bots.next()) {376
(Some(app), _, _) | (None, Some(app), None) => app,377
_ => return None,378
};379
Some(BotIdentity {380
name: app.name.clone(),381
icon_url: app.small_image_url.clone(),382
})383
}384
385
pub fn request_chat_apps(&mut self, conversation_id: &str, cx: &mut Context<Self>) {386
if self.bot_apps.contains_key(conversation_id)387
|| self.bot_apps_pending.contains(conversation_id)388
{389
return;390
}391
let Some(engine) = self.engine.clone() else {392
return;393
};394
self.bot_apps_pending.insert(conversation_id.to_owned());395
let conversation_id = conversation_id.to_owned();396
let receiver = {397
let conversation_id = conversation_id.clone();398
runtime::spawn(async move { engine.chat_apps(&conversation_id).await })399
};400
cx.spawn(async move |this, cx| {401
let apps = receiver.await.ok().and_then(Result::ok).unwrap_or_default();402
this.update(cx, |state, cx| {403
state.bot_apps_pending.remove(&conversation_id);404
state.bot_apps.insert(conversation_id, apps);405
state.apply_bot_titles();406
cx.emit(AppEvent::Sidebar);407
cx.emit(AppEvent::Directory);408
cx.notify();409
})410
.ok();411
})412
.detach();413
}414
415
pub fn apply_bot_titles(&mut self) {416
let me = self.directory.me.clone();417
for chat in self.sidebar.chats.iter_mut() {418
let Some(apps) = self.bot_apps.get(&chat.id) else {419
continue;420
};421
if !is_one_on_one(chat) || !others(chat, me.as_ref()).is_empty() {422
continue;423
}424
let mut with_bots = apps.iter().filter(|app| !app.bot_ids.is_empty());425
if let (Some(app), None) = (with_bots.next(), with_bots.next()) {426
chat.title = app.name.clone();427
}428
}429
}430
}431
432
#[cfg(test)]433
mod tests {434
use std::sync::Arc;435
436
use gpui_kit::{AppContext as _, TestAppContext};437
use store::Store;438
use teams_core::{CardActionOutcome, TaskDialog, TaskDialogKind};439
440
use super::CardAnswer;441
use crate::app_state::{AppState, Mode};442
use crate::card_state::CardScope;443
use crate::task_dialog::UrlDialogNext;444
445
fn finish(cx: &mut TestAppContext, answer: CardAnswer) -> (UrlDialogNext, Option<String>) {446
let store = Arc::new(Store::open_in_memory().unwrap());447
let app = cx.update(|cx| cx.new(|_| AppState::new(store, Mode::default())));448
let scope = CardScope::message("19:chat@thread.v2", "m1", 0);449
cx.update(|cx| {450
app.update(cx, |state, cx| {451
let next = state.finish_url_dialog_submit(&scope, answer, cx);452
(next, state.cards.note(&scope.card_key()).map(str::to_owned))453
})454
})455
}456
457
fn dialog(kind: TaskDialogKind) -> CardActionOutcome {458
CardActionOutcome::Dialog(TaskDialog {459
title: None,460
width: 640,461
height: 300,462
kind,463
})464
}465
466
#[gpui_kit::test]467
fn a_sent_submit_closes_the_url_dialog(cx: &mut TestAppContext) {468
let (next, note) = finish(cx, Ok((CardActionOutcome::Sent, None)));469
assert_eq!(next, UrlDialogNext::Close);470
assert_eq!(note, None);471
}472
473
#[gpui_kit::test]474
fn a_message_answer_is_shown_on_the_card_and_closes_the_dialog(cx: &mut TestAppContext) {475
let (next, note) = finish(cx, Ok((CardActionOutcome::Message("Saved".into()), None)));476
assert_eq!(next, UrlDialogNext::Close);477
assert_eq!(note.as_deref(), Some("Saved"));478
}479
480
#[gpui_kit::test]481
fn a_failed_submit_is_shown_on_the_card(cx: &mut TestAppContext) {482
let (next, note) = finish(cx, Err("Not connected".into()));483
assert_eq!(next, UrlDialogNext::Close);484
assert_eq!(note.as_deref(), Some("Not connected"));485
}486
487
#[gpui_kit::test]488
fn a_continued_url_task_navigates_the_open_dialog(cx: &mut TestAppContext) {489
let kind = TaskDialogKind::Url {490
url: "https://bot.example/next".into(),491
fallback_url: "https://bot.example/next".into(),492
};493
let (next, _) = finish(cx, Ok((dialog(kind), None)));494
assert_eq!(495
next,496
UrlDialogNext::Navigate {497
url: "https://bot.example/next".into(),498
width: 640,499
height: 300500
}501
);502
}503
}@@ -0,0 +1,239 @@
1
use std::collections::HashMap;
2
use std::time::Duration;
3
4
use teams_core::AdaptiveCard;
5
6
const DIALOG_KEY: &str = "task-dialog";
7
pub const DONE_HOLD: Duration = Duration::from_millis(1600);
8
pub const MAX_REASON_CHARS: usize = 160;
9
10
#[derive(Debug, Clone, PartialEq, Eq)]
11
pub enum ActionPhase {
12
Busy,
13
Done,
14
Failed(String),
15
}
16
17
#[derive(Debug, Clone, PartialEq, Eq)]
18
pub struct BotIdentity {
19
pub name: String,
20
pub icon_url: Option<String>,
21
}
22
23
#[derive(Debug, Clone, PartialEq)]
24
pub struct TaskDialogState {
25
pub title: String,
26
pub card: AdaptiveCard,
27
pub scope: CardScope,
28
pub width: u32,
29
pub height: u32,
30
}
31
32
#[derive(Debug, Clone, PartialEq)]
33
pub struct CardOverride {
34
pub basis: String,
35
pub cards: Vec<AdaptiveCard>,
36
}
37
38
#[derive(Debug, Clone, PartialEq, Eq)]
39
pub enum Surface {
40
Message,
41
Dialog,
42
}
43
44
#[derive(Debug, Clone, PartialEq, Eq)]
45
pub struct CardScope {
46
pub conversation_id: String,
47
pub message_id: String,
48
pub card_index: usize,
49
pub surface: Surface,
50
}
51
52
impl CardScope {
53
pub fn message(conversation_id: &str, message_id: &str, card_index: usize) -> Self {
54
CardScope {
55
conversation_id: conversation_id.to_owned(),
56
message_id: message_id.to_owned(),
57
card_index,
58
surface: Surface::Message,
59
}
60
}
61
62
pub fn card_key(&self) -> String {
63
match self.surface {
64
Surface::Message => format!("{}-card-{}", self.message_id, self.card_index),
65
Surface::Dialog => Self::dialog_key(),
66
}
67
}
68
69
pub fn dialog_key() -> String {
70
DIALOG_KEY.to_owned()
71
}
72
}
73
74
#[derive(Default)]
75
pub struct CardState {
76
phases: HashMap<String, ActionPhase>,
77
visibility: HashMap<String, bool>,
78
open_cards: HashMap<String, usize>,
79
notes: HashMap<String, String>,
80
overrides: HashMap<(String, String), CardOverride>,
81
}
82
83
impl CardState {
84
pub fn phase(&self, action_key: &str) -> Option<&ActionPhase> {
85
self.phases.get(action_key)
86
}
87
88
pub fn is_busy(&self, action_key: &str) -> bool {
89
self.phases.get(action_key) == Some(&ActionPhase::Busy)
90
}
91
92
pub fn set_phase(&mut self, action_key: &str, phase: ActionPhase) {
93
self.phases.insert(action_key.to_owned(), phase);
94
}
95
96
pub fn clear_done(&mut self, action_key: &str) {
97
if self.phases.get(action_key) == Some(&ActionPhase::Done) {
98
self.phases.remove(action_key);
99
}
100
}
101
102
pub fn clear_card(&mut self, card_key: &str) {
103
self.phases.retain(|key, _| !key.starts_with(card_key));
104
self.visibility.retain(|key, _| !key.starts_with(card_key));
105
self.open_cards.retain(|key, _| !key.starts_with(card_key));
106
self.notes.remove(card_key);
107
}
108
109
pub fn is_visible(&self, element_key: &str, initial: bool) -> bool {
110
self.visibility.get(element_key).copied().unwrap_or(initial)
111
}
112
113
pub fn toggle_visibility(&mut self, element_key: &str, initial: bool, forced: Option<bool>) {
114
let next = forced.unwrap_or(!self.is_visible(element_key, initial));
115
self.visibility.insert(element_key.to_owned(), next);
116
}
117
118
pub fn open_card(&self, actions_key: &str) -> Option<usize> {
119
self.open_cards.get(actions_key).copied()
120
}
121
122
pub fn toggle_open_card(&mut self, actions_key: &str, index: usize) {
123
if self.open_cards.get(actions_key) == Some(&index) {
124
self.open_cards.remove(actions_key);
125
} else {
126
self.open_cards.insert(actions_key.to_owned(), index);
127
}
128
}
129
130
pub fn note(&self, card_key: &str) -> Option<&str> {
131
self.notes.get(card_key).map(String::as_str)
132
}
133
134
pub fn set_note(&mut self, card_key: &str, text: String) {
135
self.notes.insert(card_key.to_owned(), text);
136
}
137
138
pub fn clear_note(&mut self, card_key: &str) {
139
self.notes.remove(card_key);
140
}
141
142
pub fn set_override(
143
&mut self,
144
conversation_id: &str,
145
message_id: &str,
146
replaced: CardOverride,
147
) {
148
self.overrides.insert(
149
(conversation_id.to_owned(), message_id.to_owned()),
150
replaced,
151
);
152
}
153
154
pub fn overrides_for(&self, conversation_id: &str) -> HashMap<String, CardOverride> {
155
self.overrides
156
.iter()
157
.filter(|((conversation, _), _)| conversation == conversation_id)
158
.map(|((_, message_id), replaced)| (message_id.clone(), replaced.clone()))
159
.collect()
160
}
161
}
162
163
pub fn short_reason(reason: &str) -> String {
164
reason.chars().take(MAX_REASON_CHARS).collect()
165
}
166
167
#[cfg(test)]
168
mod tests {
169
use super::*;
170
171
#[test]
172
fn done_clears_but_busy_and_failed_stay() {
173
let mut state = CardState::default();
174
state.set_phase("a", ActionPhase::Done);
175
state.set_phase("b", ActionPhase::Busy);
176
state.set_phase("c", ActionPhase::Failed("nope".into()));
177
for key in ["a", "b", "c"] {
178
state.clear_done(key);
179
}
180
assert_eq!(state.phase("a"), None);
181
assert!(state.is_busy("b"));
182
assert_eq!(state.phase("c"), Some(&ActionPhase::Failed("nope".into())));
183
}
184
185
#[test]
186
fn visibility_toggles_from_the_initial_value_or_is_forced() {
187
let mut state = CardState::default();
188
assert!(!state.is_visible("e", false));
189
state.toggle_visibility("e", false, None);
190
assert!(state.is_visible("e", false));
191
state.toggle_visibility("e", false, None);
192
assert!(!state.is_visible("e", false));
193
state.toggle_visibility("e", false, Some(true));
194
state.toggle_visibility("e", false, Some(true));
195
assert!(state.is_visible("e", false));
196
}
197
198
#[test]
199
fn one_show_card_is_open_per_action_set() {
200
let mut state = CardState::default();
201
state.toggle_open_card("set", 1);
202
assert_eq!(state.open_card("set"), Some(1));
203
state.toggle_open_card("set", 2);
204
assert_eq!(state.open_card("set"), Some(2));
205
state.toggle_open_card("set", 2);
206
assert_eq!(state.open_card("set"), None);
207
}
208
209
#[test]
210
fn overrides_are_scoped_to_their_conversation() {
211
let mut state = CardState::default();
212
let replaced = CardOverride {
213
basis: "[]".into(),
214
cards: Vec::new(),
215
};
216
state.set_override("c1", "m1", replaced.clone());
217
assert_eq!(state.overrides_for("c1").get("m1"), Some(&replaced));
218
assert!(state.overrides_for("c2").is_empty());
219
}
220
221
#[test]
222
fn reasons_are_shortened() {
223
assert_eq!(
224
short_reason(&"x".repeat(500)).chars().count(),
225
MAX_REASON_CHARS
226
);
227
}
228
229
#[test]
230
fn card_keys_differ_by_surface_and_index() {
231
let message = CardScope::message("c", "m", 2);
232
assert_eq!(message.card_key(), "m-card-2");
233
let dialog = CardScope {
234
surface: Surface::Dialog,
235
..message
236
};
237
assert_eq!(dialog.card_key(), "task-dialog");
238
}
239
}
@@ -0,0 +1,239 @@1
use std::collections::HashMap;2
use std::time::Duration;3
4
use teams_core::AdaptiveCard;5
6
const DIALOG_KEY: &str = "task-dialog";7
pub const DONE_HOLD: Duration = Duration::from_millis(1600);8
pub const MAX_REASON_CHARS: usize = 160;9
10
#[derive(Debug, Clone, PartialEq, Eq)]11
pub enum ActionPhase {12
Busy,13
Done,14
Failed(String),15
}16
17
#[derive(Debug, Clone, PartialEq, Eq)]18
pub struct BotIdentity {19
pub name: String,20
pub icon_url: Option<String>,21
}22
23
#[derive(Debug, Clone, PartialEq)]24
pub struct TaskDialogState {25
pub title: String,26
pub card: AdaptiveCard,27
pub scope: CardScope,28
pub width: u32,29
pub height: u32,30
}31
32
#[derive(Debug, Clone, PartialEq)]33
pub struct CardOverride {34
pub basis: String,35
pub cards: Vec<AdaptiveCard>,36
}37
38
#[derive(Debug, Clone, PartialEq, Eq)]39
pub enum Surface {40
Message,41
Dialog,42
}43
44
#[derive(Debug, Clone, PartialEq, Eq)]45
pub struct CardScope {46
pub conversation_id: String,47
pub message_id: String,48
pub card_index: usize,49
pub surface: Surface,50
}51
52
impl CardScope {53
pub fn message(conversation_id: &str, message_id: &str, card_index: usize) -> Self {54
CardScope {55
conversation_id: conversation_id.to_owned(),56
message_id: message_id.to_owned(),57
card_index,58
surface: Surface::Message,59
}60
}61
62
pub fn card_key(&self) -> String {63
match self.surface {64
Surface::Message => format!("{}-card-{}", self.message_id, self.card_index),65
Surface::Dialog => Self::dialog_key(),66
}67
}68
69
pub fn dialog_key() -> String {70
DIALOG_KEY.to_owned()71
}72
}73
74
#[derive(Default)]75
pub struct CardState {76
phases: HashMap<String, ActionPhase>,77
visibility: HashMap<String, bool>,78
open_cards: HashMap<String, usize>,79
notes: HashMap<String, String>,80
overrides: HashMap<(String, String), CardOverride>,81
}82
83
impl CardState {84
pub fn phase(&self, action_key: &str) -> Option<&ActionPhase> {85
self.phases.get(action_key)86
}87
88
pub fn is_busy(&self, action_key: &str) -> bool {89
self.phases.get(action_key) == Some(&ActionPhase::Busy)90
}91
92
pub fn set_phase(&mut self, action_key: &str, phase: ActionPhase) {93
self.phases.insert(action_key.to_owned(), phase);94
}95
96
pub fn clear_done(&mut self, action_key: &str) {97
if self.phases.get(action_key) == Some(&ActionPhase::Done) {98
self.phases.remove(action_key);99
}100
}101
102
pub fn clear_card(&mut self, card_key: &str) {103
self.phases.retain(|key, _| !key.starts_with(card_key));104
self.visibility.retain(|key, _| !key.starts_with(card_key));105
self.open_cards.retain(|key, _| !key.starts_with(card_key));106
self.notes.remove(card_key);107
}108
109
pub fn is_visible(&self, element_key: &str, initial: bool) -> bool {110
self.visibility.get(element_key).copied().unwrap_or(initial)111
}112
113
pub fn toggle_visibility(&mut self, element_key: &str, initial: bool, forced: Option<bool>) {114
let next = forced.unwrap_or(!self.is_visible(element_key, initial));115
self.visibility.insert(element_key.to_owned(), next);116
}117
118
pub fn open_card(&self, actions_key: &str) -> Option<usize> {119
self.open_cards.get(actions_key).copied()120
}121
122
pub fn toggle_open_card(&mut self, actions_key: &str, index: usize) {123
if self.open_cards.get(actions_key) == Some(&index) {124
self.open_cards.remove(actions_key);125
} else {126
self.open_cards.insert(actions_key.to_owned(), index);127
}128
}129
130
pub fn note(&self, card_key: &str) -> Option<&str> {131
self.notes.get(card_key).map(String::as_str)132
}133
134
pub fn set_note(&mut self, card_key: &str, text: String) {135
self.notes.insert(card_key.to_owned(), text);136
}137
138
pub fn clear_note(&mut self, card_key: &str) {139
self.notes.remove(card_key);140
}141
142
pub fn set_override(143
&mut self,144
conversation_id: &str,145
message_id: &str,146
replaced: CardOverride,147
) {148
self.overrides.insert(149
(conversation_id.to_owned(), message_id.to_owned()),150
replaced,151
);152
}153
154
pub fn overrides_for(&self, conversation_id: &str) -> HashMap<String, CardOverride> {155
self.overrides156
.iter()157
.filter(|((conversation, _), _)| conversation == conversation_id)158
.map(|((_, message_id), replaced)| (message_id.clone(), replaced.clone()))159
.collect()160
}161
}162
163
pub fn short_reason(reason: &str) -> String {164
reason.chars().take(MAX_REASON_CHARS).collect()165
}166
167
#[cfg(test)]168
mod tests {169
use super::*;170
171
#[test]172
fn done_clears_but_busy_and_failed_stay() {173
let mut state = CardState::default();174
state.set_phase("a", ActionPhase::Done);175
state.set_phase("b", ActionPhase::Busy);176
state.set_phase("c", ActionPhase::Failed("nope".into()));177
for key in ["a", "b", "c"] {178
state.clear_done(key);179
}180
assert_eq!(state.phase("a"), None);181
assert!(state.is_busy("b"));182
assert_eq!(state.phase("c"), Some(&ActionPhase::Failed("nope".into())));183
}184
185
#[test]186
fn visibility_toggles_from_the_initial_value_or_is_forced() {187
let mut state = CardState::default();188
assert!(!state.is_visible("e", false));189
state.toggle_visibility("e", false, None);190
assert!(state.is_visible("e", false));191
state.toggle_visibility("e", false, None);192
assert!(!state.is_visible("e", false));193
state.toggle_visibility("e", false, Some(true));194
state.toggle_visibility("e", false, Some(true));195
assert!(state.is_visible("e", false));196
}197
198
#[test]199
fn one_show_card_is_open_per_action_set() {200
let mut state = CardState::default();201
state.toggle_open_card("set", 1);202
assert_eq!(state.open_card("set"), Some(1));203
state.toggle_open_card("set", 2);204
assert_eq!(state.open_card("set"), Some(2));205
state.toggle_open_card("set", 2);206
assert_eq!(state.open_card("set"), None);207
}208
209
#[test]210
fn overrides_are_scoped_to_their_conversation() {211
let mut state = CardState::default();212
let replaced = CardOverride {213
basis: "[]".into(),214
cards: Vec::new(),215
};216
state.set_override("c1", "m1", replaced.clone());217
assert_eq!(state.overrides_for("c1").get("m1"), Some(&replaced));218
assert!(state.overrides_for("c2").is_empty());219
}220
221
#[test]222
fn reasons_are_shortened() {223
assert_eq!(224
short_reason(&"x".repeat(500)).chars().count(),225
MAX_REASON_CHARS226
);227
}228
229
#[test]230
fn card_keys_differ_by_surface_and_index() {231
let message = CardScope::message("c", "m", 2);232
assert_eq!(message.card_key(), "m-card-2");233
let dialog = CardScope {234
surface: Surface::Dialog,235
..message236
};237
assert_eq!(dialog.card_key(), "task-dialog");238
}239
}@@ -7,9 +7,13 @@ use store::{
7
7
ChannelLayoutRecord, ChannelRecord, ChatRecord, MemberRecord, MessageRecord, Store,
8
8
TeamLayoutRecord, TeamRecord,
9
9
};
10
use teams_core::{MentionCandidate, PersonCandidate, PersonSource};
10
use teams_core::{
11
CardActionOutcome, ChatApp, MentionCandidate, PersonCandidate, PersonSource, TaskDialog,
12
TaskDialogKind,
13
};
11
14
12
15
use crate::app_state::{AppState, Selection};
16
use crate::card_actions::{CardAnswer, CardTask};
13
17
use crate::data::{FolderInfo, FolderKind, Person, PresenceKind};
14
18
15
19
pub const DEMO_USER_ID: &str = "demo-me";
@@ -21,6 +25,9 @@ const STAGING_SIZE: (usize, usize) = (960, 540);
21
25
const PRIORITY_CHAT: &str = "demo-chat-priya";
22
26
const BOT_CHAT: &str = "demo-chat-wiki-bot";
23
27
const BOT_NAME: &str = "Wiki Bot";
28
const BOT_APP_NAME: &str = "Wiki Cloud";
29
const BOT_ID: &str = "00000000-0000-0000-0000-00000000b07a";
30
const CARD_ANSWER_DELAY: std::time::Duration = std::time::Duration::from_millis(700);
24
31
const CARD_PERSON_URL: &str = "https://avatars.githubusercontent.com/u/9919?s=64";
25
32
const CARD_PAGE_URL: &str = "https://avatars.githubusercontent.com/u/9919?s=64";
26
33
const NEW_CHAT_PREFIX: &str = "demo-chat-new-";
@@ -528,6 +535,8 @@ pub fn seed_directory(state: &mut AppState) {
528
535
conversation_ids: Vec::new(),
529
536
},
530
537
];
538
state.bot_apps.insert(BOT_CHAT.to_owned(), vec![bot_app()]);
539
let directory = &mut state.directory;
531
540
directory.pinned_channels = ids(&["demo-channel-1-1", "demo-channel-3-2"]);
532
541
directory
533
542
.unread_counts
@@ -564,6 +573,7 @@ pub fn seed_directory(state: &mut AppState) {
564
573
}
565
574
state.collapsed.insert(CUSTOMERS_FOLDER.to_owned());
566
575
state.last_sync = Some(Utc::now());
576
state.apply_bot_titles();
567
577
}
568
578
569
579
#[allow(clippy::too_many_arguments)]
@@ -583,6 +593,7 @@ fn message(
583
593
reply_to_id: reply_to.map(str::to_owned),
584
594
sender_id: Some(sender.0.to_owned()),
585
595
sender_name: Some(sender.1.to_owned()),
596
sender_application_id: None,
586
597
created_at: time,
587
598
edited_at: edited.then_some(time + Duration::minutes(2)),
588
599
deleted: false,
@@ -619,11 +630,17 @@ fn bot_messages() -> Vec<MessageRecord> {
619
630
{"type": "TextBlock", "spacing": "small", "isSubtle": true, "wrap": true, "text": "Owned by: Dana Demo"}
620
631
]}
621
632
]},
633
{"type": "TextBlock", "id": "owner-note", "isVisible": false, "isSubtle": true, "wrap": true, "text": "Owner notes are only shown on request."},
622
634
{"type": "ActionSet", "actions": [
623
635
{"type": "Action.OpenUrl", "title": "View page", "url": "https://example.com/wiki/release-checklist"},
624
636
{"type": "Action.OpenUrl", "title": "View changes", "url": "https://example.com/wiki/release-checklist/changes"},
625
637
{"type": "Action.Submit", "title": "Watch page", "data": {"action": "watch"}},
626
{"type": "Action.Submit", "title": "Stop watching", "data": {"action": "unwatch"}}
638
{"type": "Action.Submit", "title": "Stop watching", "data": {"action": "unwatch"}},
639
{"type": "Action.Submit", "title": "Settings", "data": {"msteams": {"type": "task/fetch"}}},
640
{"type": "Action.ToggleVisibility", "title": "Owner notes", "targetElements": ["owner-note"]},
641
{"type": "Action.ShowCard", "title": "Details", "card": {"body": [
642
{"type": "TextBlock", "wrap": true, "text": "Last edited by **Mara Lindqvist** on Tuesday."}
643
]}}
627
644
]}
628
645
]
629
646
});
@@ -648,9 +665,64 @@ fn bot_messages() -> Vec<MessageRecord> {
648
665
&attachments.to_string(),
649
666
);
650
667
record.sender_id = None;
668
record.sender_application_id = Some(BOT_ID.to_owned());
651
669
vec![record]
652
670
}
653
671
672
fn bot_app() -> ChatApp {
673
ChatApp {
674
app_id: "demo-app-wiki".to_owned(),
675
name: BOT_APP_NAME.to_owned(),
676
bot_ids: vec![BOT_ID.to_owned()],
677
small_image_url: None,
678
accent_color: None,
679
web_application_resource: None,
680
}
681
}
682
683
pub async fn card_answer(task: CardTask) -> CardAnswer {
684
tokio::time::sleep(CARD_ANSWER_DELAY).await;
685
let data = match task {
686
CardTask::Submit(_) => {
687
return Ok((
688
CardActionOutcome::Message("Settings saved".into()),
689
Some((bot_app(), BOT_ID.to_owned())),
690
));
691
}
692
CardTask::Action(action) => match action.invoke_payload() {
693
Some(payload) => payload.value,
694
None => return Err("Not supported".to_owned()),
695
},
696
};
697
let outcome = if data.pointer("/data/type").and_then(|kind| kind.as_str()) == Some("task/fetch")
698
{
699
CardActionOutcome::Dialog(TaskDialog {
700
title: None,
701
width: 520,
702
height: 300,
703
kind: TaskDialogKind::Card(settings_card().to_string()),
704
})
705
} else if data.get("action").and_then(|action| action.as_str()) == Some("unwatch") {
706
CardActionOutcome::Failed("The app answered 500: demo failure".into())
707
} else {
708
CardActionOutcome::Sent
709
};
710
Ok((outcome, Some((bot_app(), BOT_ID.to_owned()))))
711
}
712
713
fn settings_card() -> serde_json::Value {
714
serde_json::json!({
715
"type": "AdaptiveCard",
716
"body": [
717
{"type": "TextBlock", "weight": "bolder", "text": "Notification settings"},
718
{"type": "TextBlock", "wrap": true, "isSubtle": true, "text": "Choose how the bot tells you about page changes."}
719
],
720
"actions": [
721
{"type": "Action.Submit", "title": "Save", "data": {"save": true}}
722
]
723
})
724
}
725
654
726
fn priority_messages() -> Vec<MessageRecord> {
655
727
let priya = (PRIYA_ID, "Priya Nair");
656
728
let me = (DEMO_USER_ID, DEMO_USER_NAME);
@@ -7,9 +7,13 @@ use store::{7
ChannelLayoutRecord, ChannelRecord, ChatRecord, MemberRecord, MessageRecord, Store,7
ChannelLayoutRecord, ChannelRecord, ChatRecord, MemberRecord, MessageRecord, Store,8
TeamLayoutRecord, TeamRecord,8
TeamLayoutRecord, TeamRecord,9
};9
};10
use teams_core::{MentionCandidate, PersonCandidate, PersonSource};10
use teams_core::{11
CardActionOutcome, ChatApp, MentionCandidate, PersonCandidate, PersonSource, TaskDialog,12
TaskDialogKind,13
};11
14
12
use crate::app_state::{AppState, Selection};15
use crate::app_state::{AppState, Selection};16
use crate::card_actions::{CardAnswer, CardTask};13
use crate::data::{FolderInfo, FolderKind, Person, PresenceKind};17
use crate::data::{FolderInfo, FolderKind, Person, PresenceKind};14
18
15
pub const DEMO_USER_ID: &str = "demo-me";19
pub const DEMO_USER_ID: &str = "demo-me";@@ -21,6 +25,9 @@ const STAGING_SIZE: (usize, usize) = (960, 540);21
const PRIORITY_CHAT: &str = "demo-chat-priya";25
const PRIORITY_CHAT: &str = "demo-chat-priya";22
const BOT_CHAT: &str = "demo-chat-wiki-bot";26
const BOT_CHAT: &str = "demo-chat-wiki-bot";23
const BOT_NAME: &str = "Wiki Bot";27
const BOT_NAME: &str = "Wiki Bot";28
const BOT_APP_NAME: &str = "Wiki Cloud";29
const BOT_ID: &str = "00000000-0000-0000-0000-00000000b07a";30
const CARD_ANSWER_DELAY: std::time::Duration = std::time::Duration::from_millis(700);24
const CARD_PERSON_URL: &str = "https://avatars.githubusercontent.com/u/9919?s=64";31
const CARD_PERSON_URL: &str = "https://avatars.githubusercontent.com/u/9919?s=64";25
const CARD_PAGE_URL: &str = "https://avatars.githubusercontent.com/u/9919?s=64";32
const CARD_PAGE_URL: &str = "https://avatars.githubusercontent.com/u/9919?s=64";26
const NEW_CHAT_PREFIX: &str = "demo-chat-new-";33
const NEW_CHAT_PREFIX: &str = "demo-chat-new-";@@ -528,6 +535,8 @@ pub fn seed_directory(state: &mut AppState) {528
conversation_ids: Vec::new(),535
conversation_ids: Vec::new(),529
},536
},530
];537
];538
state.bot_apps.insert(BOT_CHAT.to_owned(), vec![bot_app()]);539
let directory = &mut state.directory;531
directory.pinned_channels = ids(&["demo-channel-1-1", "demo-channel-3-2"]);540
directory.pinned_channels = ids(&["demo-channel-1-1", "demo-channel-3-2"]);532
directory541
directory533
.unread_counts542
.unread_counts@@ -564,6 +573,7 @@ pub fn seed_directory(state: &mut AppState) {564
}573
}565
state.collapsed.insert(CUSTOMERS_FOLDER.to_owned());574
state.collapsed.insert(CUSTOMERS_FOLDER.to_owned());566
state.last_sync = Some(Utc::now());575
state.last_sync = Some(Utc::now());576
state.apply_bot_titles();567
}577
}568
578
569
#[allow(clippy::too_many_arguments)]579
#[allow(clippy::too_many_arguments)]@@ -583,6 +593,7 @@ fn message(583
reply_to_id: reply_to.map(str::to_owned),593
reply_to_id: reply_to.map(str::to_owned),584
sender_id: Some(sender.0.to_owned()),594
sender_id: Some(sender.0.to_owned()),585
sender_name: Some(sender.1.to_owned()),595
sender_name: Some(sender.1.to_owned()),596
sender_application_id: None,586
created_at: time,597
created_at: time,587
edited_at: edited.then_some(time + Duration::minutes(2)),598
edited_at: edited.then_some(time + Duration::minutes(2)),588
deleted: false,599
deleted: false,@@ -619,11 +630,17 @@ fn bot_messages() -> Vec<MessageRecord> {619
{"type": "TextBlock", "spacing": "small", "isSubtle": true, "wrap": true, "text": "Owned by: Dana Demo"}630
{"type": "TextBlock", "spacing": "small", "isSubtle": true, "wrap": true, "text": "Owned by: Dana Demo"}620
]}631
]}621
]},632
]},633
{"type": "TextBlock", "id": "owner-note", "isVisible": false, "isSubtle": true, "wrap": true, "text": "Owner notes are only shown on request."},622
{"type": "ActionSet", "actions": [634
{"type": "ActionSet", "actions": [623
{"type": "Action.OpenUrl", "title": "View page", "url": "https://example.com/wiki/release-checklist"},635
{"type": "Action.OpenUrl", "title": "View page", "url": "https://example.com/wiki/release-checklist"},624
{"type": "Action.OpenUrl", "title": "View changes", "url": "https://example.com/wiki/release-checklist/changes"},636
{"type": "Action.OpenUrl", "title": "View changes", "url": "https://example.com/wiki/release-checklist/changes"},625
{"type": "Action.Submit", "title": "Watch page", "data": {"action": "watch"}},637
{"type": "Action.Submit", "title": "Watch page", "data": {"action": "watch"}},626
{"type": "Action.Submit", "title": "Stop watching", "data": {"action": "unwatch"}}638
{"type": "Action.Submit", "title": "Stop watching", "data": {"action": "unwatch"}},639
{"type": "Action.Submit", "title": "Settings", "data": {"msteams": {"type": "task/fetch"}}},640
{"type": "Action.ToggleVisibility", "title": "Owner notes", "targetElements": ["owner-note"]},641
{"type": "Action.ShowCard", "title": "Details", "card": {"body": [642
{"type": "TextBlock", "wrap": true, "text": "Last edited by **Mara Lindqvist** on Tuesday."}643
]}}627
]}644
]}628
]645
]629
});646
});@@ -648,9 +665,64 @@ fn bot_messages() -> Vec<MessageRecord> {648
&attachments.to_string(),665
&attachments.to_string(),649
);666
);650
record.sender_id = None;667
record.sender_id = None;668
record.sender_application_id = Some(BOT_ID.to_owned());651
vec![record]669
vec![record]652
}670
}653
671
672
fn bot_app() -> ChatApp {673
ChatApp {674
app_id: "demo-app-wiki".to_owned(),675
name: BOT_APP_NAME.to_owned(),676
bot_ids: vec![BOT_ID.to_owned()],677
small_image_url: None,678
accent_color: None,679
web_application_resource: None,680
}681
}682
683
pub async fn card_answer(task: CardTask) -> CardAnswer {684
tokio::time::sleep(CARD_ANSWER_DELAY).await;685
let data = match task {686
CardTask::Submit(_) => {687
return Ok((688
CardActionOutcome::Message("Settings saved".into()),689
Some((bot_app(), BOT_ID.to_owned())),690
));691
}692
CardTask::Action(action) => match action.invoke_payload() {693
Some(payload) => payload.value,694
None => return Err("Not supported".to_owned()),695
},696
};697
let outcome = if data.pointer("/data/type").and_then(|kind| kind.as_str()) == Some("task/fetch")698
{699
CardActionOutcome::Dialog(TaskDialog {700
title: None,701
width: 520,702
height: 300,703
kind: TaskDialogKind::Card(settings_card().to_string()),704
})705
} else if data.get("action").and_then(|action| action.as_str()) == Some("unwatch") {706
CardActionOutcome::Failed("The app answered 500: demo failure".into())707
} else {708
CardActionOutcome::Sent709
};710
Ok((outcome, Some((bot_app(), BOT_ID.to_owned()))))711
}712
713
fn settings_card() -> serde_json::Value {714
serde_json::json!({715
"type": "AdaptiveCard",716
"body": [717
{"type": "TextBlock", "weight": "bolder", "text": "Notification settings"},718
{"type": "TextBlock", "wrap": true, "isSubtle": true, "text": "Choose how the bot tells you about page changes."}719
],720
"actions": [721
{"type": "Action.Submit", "title": "Save", "data": {"save": true}}722
]723
})724
}725
654
fn priority_messages() -> Vec<MessageRecord> {726
fn priority_messages() -> Vec<MessageRecord> {655
let priya = (PRIYA_ID, "Priya Nair");727
let priya = (PRIYA_ID, "Priya Nair");656
let me = (DEMO_USER_ID, DEMO_USER_NAME);728
let me = (DEMO_USER_ID, DEMO_USER_NAME);@@ -7,6 +7,8 @@ mod app_state;
7
7
mod assets;
8
8
mod avatar_image;
9
9
mod backend;
10
mod card_actions;
11
mod card_state;
10
12
mod data;
11
13
mod demo;
12
14
mod downloads;
@@ -21,6 +23,7 @@ mod render;
21
23
mod rows;
22
24
mod runtime;
23
25
mod sidebar_model;
26
mod task_dialog;
24
27
mod theme;
25
28
mod updater;
26
29
mod views;
@@ -114,10 +117,12 @@ fn transport(endpoint: Option<&str>, database: Option<&std::path::Path>) -> Arc<
114
117
Some(directory) => directory.join(WEBVIEW_FOLDER),
115
118
None => data_path(WEBVIEW_FOLDER),
116
119
};
117
return webview::start(webview::HostConfig {
120
let transport = webview::start(webview::HostConfig {
118
121
user_data_folder,
119
122
window_title: format!("{APP_NAME} - Sign in"),
120
123
});
124
task_dialog::install_host(transport.clone());
125
return transport;
121
126
}
122
127
#[cfg(not(windows))]
123
128
let _ = database;
@@ -167,6 +172,7 @@ fn main() {
167
172
state.start_on_channels = arguments.channels_tab;
168
173
state
169
174
});
175
cx.set_global(app_state::AppHandle(state.clone()));
170
176
if arguments.demo {
171
177
state.update(cx, |state, cx| {
172
178
demo::seed_directory(state);
@@ -7,6 +7,8 @@ mod app_state;7
mod assets;7
mod assets;8
mod avatar_image;8
mod avatar_image;9
mod backend;9
mod backend;10
mod card_actions;11
mod card_state;10
mod data;12
mod data;11
mod demo;13
mod demo;12
mod downloads;14
mod downloads;@@ -21,6 +23,7 @@ mod render;21
mod rows;23
mod rows;22
mod runtime;24
mod runtime;23
mod sidebar_model;25
mod sidebar_model;26
mod task_dialog;24
mod theme;27
mod theme;25
mod updater;28
mod updater;26
mod views;29
mod views;@@ -114,10 +117,12 @@ fn transport(endpoint: Option<&str>, database: Option<&std::path::Path>) -> Arc<114
Some(directory) => directory.join(WEBVIEW_FOLDER),117
Some(directory) => directory.join(WEBVIEW_FOLDER),115
None => data_path(WEBVIEW_FOLDER),118
None => data_path(WEBVIEW_FOLDER),116
};119
};117
return webview::start(webview::HostConfig {120
let transport = webview::start(webview::HostConfig {118
user_data_folder,121
user_data_folder,119
window_title: format!("{APP_NAME} - Sign in"),122
window_title: format!("{APP_NAME} - Sign in"),120
});123
});124
task_dialog::install_host(transport.clone());125
return transport;121
}126
}122
#[cfg(not(windows))]127
#[cfg(not(windows))]123
let _ = database;128
let _ = database;@@ -167,6 +172,7 @@ fn main() {167
state.start_on_channels = arguments.channels_tab;172
state.start_on_channels = arguments.channels_tab;168
state173
state169
});174
});175
cx.set_global(app_state::AppHandle(state.clone()));170
if arguments.demo {176
if arguments.demo {171
state.update(cx, |state, cx| {177
state.update(cx, |state, cx| {172
demo::seed_directory(state);178
demo::seed_directory(state);@@ -172,6 +172,7 @@ mod tests {
172
172
reply_to_id: None,
173
173
sender_id: Some(sender.into()),
174
174
sender_name: Some("Sender".into()),
175
sender_application_id: None,
175
176
created_at: at,
176
177
edited_at: None,
177
178
deleted: false,
@@ -172,6 +172,7 @@ mod tests {172
reply_to_id: None,172
reply_to_id: None,173
sender_id: Some(sender.into()),173
sender_id: Some(sender.into()),174
sender_name: Some("Sender".into()),174
sender_name: Some("Sender".into()),175
sender_application_id: None,175
created_at: at,176
created_at: at,176
edited_at: None,177
edited_at: None,177
deleted: false,178
deleted: false,@@ -13,3 +13,5 @@ mod text;
13
13
mod toast;
14
14
15
15
pub use center::NotificationCenter;
16
#[cfg(windows)]
17
pub use platform::native_handle;
@@ -13,3 +13,5 @@ mod text;13
mod toast;13
mod toast;14
14
15
pub use center::NotificationCenter;15
pub use center::NotificationCenter;16
#[cfg(windows)]17
pub use platform::native_handle;@@ -10,6 +10,7 @@ use teams_core::{
10
10
images, message_spans, reactions,
11
11
};
12
12
13
use crate::card_state::CardOverride;
13
14
use crate::format;
14
15
use crate::reaction_model::{Reactor, UNKNOWN_REACTOR};
15
16
use crate::render::blocks::{Inline, strip_image_placeholders};
@@ -112,8 +113,10 @@ pub struct LocalImage {
112
113
#[derive(Debug, Clone, PartialEq)]
113
114
pub struct MessageRow {
114
115
pub key: String,
116
pub conversation_id: String,
115
117
pub author: String,
116
118
pub sender_id: Option<String>,
119
pub application_id: Option<String>,
117
120
pub created_at: DateTime<Utc>,
118
121
pub series: Series,
119
122
pub card: bool,
@@ -453,6 +456,7 @@ pub struct RowContext {
453
456
pub my_user_id: Option<String>,
454
457
pub names: HashMap<String, String>,
455
458
pub pending_reactions: PendingReactions,
459
pub card_overrides: HashMap<String, CardOverride>,
456
460
}
457
461
458
462
fn visible_reactions(record: &MessageRecord, context: &RowContext) -> Vec<ReactionInfo> {
@@ -481,7 +485,9 @@ pub fn message_row(record: &MessageRecord, context: &RowContext) -> MessageRow {
481
485
};
482
486
MessageRow {
483
487
key: record.message_id.clone(),
488
conversation_id: record.conversation_id.clone(),
484
489
sender_id: record.sender_id.clone(),
490
application_id: record.sender_application_id.clone(),
485
491
created_at: record.created_at,
486
492
series: Series::default(),
487
493
card: false,
@@ -498,7 +504,10 @@ pub fn message_row(record: &MessageRecord, context: &RowContext) -> MessageRow {
498
504
images,
499
505
local_images: Vec::new(),
500
506
files: files(record),
501
adaptive_cards: adaptive_cards(record),
507
adaptive_cards: match context.card_overrides.get(&record.message_id) {
508
Some(replaced) if replaced.basis == record.attachments_json => replaced.cards.clone(),
509
_ => adaptive_cards(record),
510
},
502
511
reply_count: None,
503
512
new_marker: false,
504
513
reply_faces: Vec::new(),
@@ -703,6 +712,7 @@ mod tests {
703
712
reply_to_id: reply_to.map(str::to_owned),
704
713
sender_id: Some("u".into()),
705
714
sender_name: Some("Author".into()),
715
sender_application_id: None,
706
716
created_at: Utc.with_ymd_and_hms(2026, 10, day, hour, 0, 0).unwrap(),
707
717
edited_at: None,
708
718
deleted: false,
@@ -830,6 +840,7 @@ mod tests {
830
840
my_user_id: None,
831
841
names: HashMap::new(),
832
842
pending_reactions: HashMap::new(),
843
card_overrides: HashMap::new(),
833
844
}
834
845
}
835
846
@@ -10,6 +10,7 @@ use teams_core::{10
images, message_spans, reactions,10
images, message_spans, reactions,11
};11
};12
12
13
use crate::card_state::CardOverride;13
use crate::format;14
use crate::format;14
use crate::reaction_model::{Reactor, UNKNOWN_REACTOR};15
use crate::reaction_model::{Reactor, UNKNOWN_REACTOR};15
use crate::render::blocks::{Inline, strip_image_placeholders};16
use crate::render::blocks::{Inline, strip_image_placeholders};@@ -112,8 +113,10 @@ pub struct LocalImage {112
#[derive(Debug, Clone, PartialEq)]113
#[derive(Debug, Clone, PartialEq)]113
pub struct MessageRow {114
pub struct MessageRow {114
pub key: String,115
pub key: String,116
pub conversation_id: String,115
pub author: String,117
pub author: String,116
pub sender_id: Option<String>,118
pub sender_id: Option<String>,119
pub application_id: Option<String>,117
pub created_at: DateTime<Utc>,120
pub created_at: DateTime<Utc>,118
pub series: Series,121
pub series: Series,119
pub card: bool,122
pub card: bool,@@ -453,6 +456,7 @@ pub struct RowContext {453
pub my_user_id: Option<String>,456
pub my_user_id: Option<String>,454
pub names: HashMap<String, String>,457
pub names: HashMap<String, String>,455
pub pending_reactions: PendingReactions,458
pub pending_reactions: PendingReactions,459
pub card_overrides: HashMap<String, CardOverride>,456
}460
}457
461
458
fn visible_reactions(record: &MessageRecord, context: &RowContext) -> Vec<ReactionInfo> {462
fn visible_reactions(record: &MessageRecord, context: &RowContext) -> Vec<ReactionInfo> {@@ -481,7 +485,9 @@ pub fn message_row(record: &MessageRecord, context: &RowContext) -> MessageRow {481
};485
};482
MessageRow {486
MessageRow {483
key: record.message_id.clone(),487
key: record.message_id.clone(),488
conversation_id: record.conversation_id.clone(),484
sender_id: record.sender_id.clone(),489
sender_id: record.sender_id.clone(),490
application_id: record.sender_application_id.clone(),485
created_at: record.created_at,491
created_at: record.created_at,486
series: Series::default(),492
series: Series::default(),487
card: false,493
card: false,@@ -498,7 +504,10 @@ pub fn message_row(record: &MessageRecord, context: &RowContext) -> MessageRow {498
images,504
images,499
local_images: Vec::new(),505
local_images: Vec::new(),500
files: files(record),506
files: files(record),501
adaptive_cards: adaptive_cards(record),507
adaptive_cards: match context.card_overrides.get(&record.message_id) {508
Some(replaced) if replaced.basis == record.attachments_json => replaced.cards.clone(),509
_ => adaptive_cards(record),510
},502
reply_count: None,511
reply_count: None,503
new_marker: false,512
new_marker: false,504
reply_faces: Vec::new(),513
reply_faces: Vec::new(),@@ -703,6 +712,7 @@ mod tests {703
reply_to_id: reply_to.map(str::to_owned),712
reply_to_id: reply_to.map(str::to_owned),704
sender_id: Some("u".into()),713
sender_id: Some("u".into()),705
sender_name: Some("Author".into()),714
sender_name: Some("Author".into()),715
sender_application_id: None,706
created_at: Utc.with_ymd_and_hms(2026, 10, day, hour, 0, 0).unwrap(),716
created_at: Utc.with_ymd_and_hms(2026, 10, day, hour, 0, 0).unwrap(),707
edited_at: None,717
edited_at: None,708
deleted: false,718
deleted: false,@@ -830,6 +840,7 @@ mod tests {830
my_user_id: None,840
my_user_id: None,831
names: HashMap::new(),841
names: HashMap::new(),832
pending_reactions: HashMap::new(),842
pending_reactions: HashMap::new(),843
card_overrides: HashMap::new(),833
}844
}834
}845
}835
846
@@ -0,0 +1,46 @@
1
use gpui_kit::*;
2
3
use crate::card_state::CardScope;
4
5
#[cfg(windows)]
6
mod hosted;
7
#[cfg_attr(not(windows), allow(dead_code))]
8
mod sdk;
9
10
#[cfg(windows)]
11
pub use hosted::install_host;
12
13
#[cfg_attr(not(windows), allow(dead_code))]
14
#[derive(Debug, Clone, PartialEq)]
15
pub struct UrlDialog {
16
pub title: String,
17
pub url: String,
18
pub fallback_url: String,
19
pub width: u32,
20
pub height: u32,
21
pub app_id: String,
22
pub bot_id: String,
23
pub scope: CardScope,
24
pub web_application_resource: Option<String>,
25
}
26
27
#[cfg_attr(not(windows), allow(dead_code))]
28
#[derive(Debug, Clone, PartialEq, Eq)]
29
pub enum UrlDialogNext {
30
Close,
31
Navigate {
32
url: String,
33
width: u32,
34
height: u32,
35
},
36
}
37
38
#[cfg(windows)]
39
pub fn open_url_dialog(dialog: UrlDialog, cx: &mut App) {
40
hosted::open(dialog, cx);
41
}
42
43
#[cfg(not(windows))]
44
pub fn open_url_dialog(dialog: UrlDialog, cx: &mut App) {
45
cx.open_url(&dialog.fallback_url);
46
}
@@ -0,0 +1,46 @@1
use gpui_kit::*;2
3
use crate::card_state::CardScope;4
5
#[cfg(windows)]6
mod hosted;7
#[cfg_attr(not(windows), allow(dead_code))]8
mod sdk;9
10
#[cfg(windows)]11
pub use hosted::install_host;12
13
#[cfg_attr(not(windows), allow(dead_code))]14
#[derive(Debug, Clone, PartialEq)]15
pub struct UrlDialog {16
pub title: String,17
pub url: String,18
pub fallback_url: String,19
pub width: u32,20
pub height: u32,21
pub app_id: String,22
pub bot_id: String,23
pub scope: CardScope,24
pub web_application_resource: Option<String>,25
}26
27
#[cfg_attr(not(windows), allow(dead_code))]28
#[derive(Debug, Clone, PartialEq, Eq)]29
pub enum UrlDialogNext {30
Close,31
Navigate {32
url: String,33
width: u32,34
height: u32,35
},36
}37
38
#[cfg(windows)]39
pub fn open_url_dialog(dialog: UrlDialog, cx: &mut App) {40
hosted::open(dialog, cx);41
}42
43
#[cfg(not(windows))]44
pub fn open_url_dialog(dialog: UrlDialog, cx: &mut App) {45
cx.open_url(&dialog.fallback_url);46
}@@ -0,0 +1,50 @@
1
<!doctype html>
2
<html>
3
<head>
4
<meta charset="utf-8">
5
<title></title>
6
<style>
7
html, body { margin: 0; height: 100%; overflow: hidden; background: __BACKGROUND__; }
8
iframe { display: block; width: 100%; height: 100%; border: 0; }
9
</style>
10
</head>
11
<body>
12
<iframe id="app"></iframe>
13
<script>
14
(() => {
15
const config = __CONFIG__;
16
const makeAcquirer = __ACQUIRE__;
17
const frame = document.getElementById('app');
18
const originOf = (url) => { try { return new URL(url).origin; } catch (error) { return null; } };
19
let childOrigin = null;
20
const toHost = (message) => window.chrome.webview.postMessage(JSON.stringify(message));
21
const postToChild = (message) => {
22
if (frame.contentWindow && childOrigin) frame.contentWindow.postMessage(message, childOrigin);
23
};
24
const load = (url) => { childOrigin = originOf(url); frame.src = url; };
25
const answerAuthToken = async ({id, uuidAsString, resource}) => {
26
let args;
27
try {
28
const acquire = await makeAcquirer({marginMs: config.marginMs, forceRefresh: false});
29
const {token, refreshError} = await acquire(resource, '.default');
30
args = token ? [true, token] : [false, refreshError || 'tokenFailed'];
31
} catch (error) {
32
args = [false, 'tokenFailed'];
33
}
34
postToChild({id, uuidAsString, args});
35
};
36
window.addEventListener('message', (event) => {
37
if (event.source !== frame.contentWindow || event.origin !== childOrigin) return;
38
if (event.data && typeof event.data === 'object') toHost({kind: 'sdk', message: event.data});
39
});
40
window.chrome.webview.addEventListener('message', (event) => {
41
const directive = event.data || {};
42
if (directive.kind === 'post') postToChild(directive.message);
43
else if (directive.kind === 'authToken') answerAuthToken(directive);
44
else if (directive.kind === 'load') load(directive.url);
45
});
46
load(config.url);
47
})();
48
</script>
49
</body>
50
</html>
@@ -0,0 +1,50 @@1
<!doctype html>2
<html>3
<head>4
<meta charset="utf-8">5
<title></title>6
<style>7
html, body { margin: 0; height: 100%; overflow: hidden; background: __BACKGROUND__; }8
iframe { display: block; width: 100%; height: 100%; border: 0; }9
</style>10
</head>11
<body>12
<iframe id="app"></iframe>13
<script>14
(() => {15
const config = __CONFIG__;16
const makeAcquirer = __ACQUIRE__;17
const frame = document.getElementById('app');18
const originOf = (url) => { try { return new URL(url).origin; } catch (error) { return null; } };19
let childOrigin = null;20
const toHost = (message) => window.chrome.webview.postMessage(JSON.stringify(message));21
const postToChild = (message) => {22
if (frame.contentWindow && childOrigin) frame.contentWindow.postMessage(message, childOrigin);23
};24
const load = (url) => { childOrigin = originOf(url); frame.src = url; };25
const answerAuthToken = async ({id, uuidAsString, resource}) => {26
let args;27
try {28
const acquire = await makeAcquirer({marginMs: config.marginMs, forceRefresh: false});29
const {token, refreshError} = await acquire(resource, '.default');30
args = token ? [true, token] : [false, refreshError || 'tokenFailed'];31
} catch (error) {32
args = [false, 'tokenFailed'];33
}34
postToChild({id, uuidAsString, args});35
};36
window.addEventListener('message', (event) => {37
if (event.source !== frame.contentWindow || event.origin !== childOrigin) return;38
if (event.data && typeof event.data === 'object') toHost({kind: 'sdk', message: event.data});39
});40
window.chrome.webview.addEventListener('message', (event) => {41
const directive = event.data || {};42
if (directive.kind === 'post') postToChild(directive.message);43
else if (directive.kind === 'authToken') answerAuthToken(directive);44
else if (directive.kind === 'load') load(directive.url);45
});46
load(config.url);47
})();48
</script>49
</body>50
</html>@@ -0,0 +1,124 @@
1
use std::sync::{Arc, OnceLock};
2
3
use gpui_kit::*;
4
use serde_json::json;
5
use teams_core::DialogIdentity;
6
use webview::{DialogEvent, DialogHandle, DialogSpec, WebViewTransport};
7
8
use super::sdk::{self, Effect, HostContext, HostPage};
9
use super::{UrlDialog, UrlDialogNext};
10
use crate::app_state::{AppHandle, AppState};
11
use crate::backend::Engine;
12
use crate::{notify, runtime, theme};
13
14
static HOST: OnceLock<Arc<WebViewTransport>> = OnceLock::new();
15
16
pub fn install_host(transport: Arc<WebViewTransport>) {
17
let _ = HOST.set(transport);
18
}
19
20
pub fn open(dialog: UrlDialog, cx: &mut App) {
21
let Some(host) = HOST.get().cloned() else {
22
cx.open_url(&dialog.fallback_url);
23
return;
24
};
25
let state = cx.global::<AppHandle>().0.clone();
26
let engine = state.read(cx).engine.clone();
27
let owner = cx
28
.active_window()
29
.and_then(|window| {
30
window
31
.update(cx, |_, window, _| notify::native_handle(window))
32
.ok()
33
})
34
.flatten();
35
cx.spawn(async move |cx| run(host, dialog, state, engine, owner, cx).await)
36
.detach();
37
}
38
39
async fn run(
40
host: Arc<WebViewTransport>,
41
dialog: UrlDialog,
42
state: Entity<AppState>,
43
engine: Option<Arc<Engine>>,
44
owner: Option<isize>,
45
cx: &mut AsyncApp,
46
) {
47
let identity = fetch_identity(engine, &dialog.scope.conversation_id).await;
48
let context = HostContext {
49
user_id: identity.user_id,
50
user_display_name: identity.display_name,
51
tenant_id: identity.tenant_id,
52
conversation_id: dialog.scope.conversation_id.clone(),
53
app_id: dialog.app_id.clone(),
54
session_id: uuid::Uuid::new_v4().to_string(),
55
dark: true,
56
web_application_resource: dialog.web_application_resource.clone(),
57
};
58
let page_html = HostPage {
59
task_url: &dialog.url,
60
background: theme::BACKGROUND,
61
token_acquirer_script: &session::token_acquirer_script(),
62
}
63
.html();
64
let (handle, mut events) = host.open_dialog(DialogSpec {
65
title: dialog.title.clone(),
66
width: dialog.width,
67
height: dialog.height,
68
background: theme::BACKGROUND,
69
owner,
70
page_url: sdk::host_page_url(),
71
page_html,
72
});
73
while let Some(DialogEvent::Message(raw)) = events.recv().await {
74
let handled = sdk::handle(&raw, &context);
75
for directive in &handled.directives {
76
handle.post(directive.to_string());
77
}
78
if let Some(effect) = handled.effect {
79
apply(effect, &dialog, &state, &handle, cx).await;
80
}
81
}
82
}
83
84
async fn fetch_identity(engine: Option<Arc<Engine>>, conversation_id: &str) -> DialogIdentity {
85
let empty = DialogIdentity {
86
user_id: String::new(),
87
display_name: String::new(),
88
tenant_id: String::new(),
89
};
90
let Some(engine) = engine else {
91
return empty;
92
};
93
let conversation_id = conversation_id.to_owned();
94
let lookup = runtime::spawn(async move { engine.dialog_identity(&conversation_id).await.ok() });
95
lookup.await.ok().flatten().unwrap_or(empty)
96
}
97
98
async fn apply(
99
effect: Effect,
100
dialog: &UrlDialog,
101
state: &Entity<AppState>,
102
handle: &DialogHandle,
103
cx: &mut AsyncApp,
104
) {
105
match effect {
106
Effect::Resize { width, height } => handle.resize(width, height),
107
Effect::OpenLink(link) => {
108
cx.update(|cx| cx.open_url(&link));
109
}
110
Effect::Submit(result) => {
111
let scope = dialog.scope.clone();
112
let next = state
113
.update(cx, |state, cx| state.submit_url_dialog(scope, result, cx))
114
.await;
115
match next {
116
UrlDialogNext::Close => handle.close(),
117
UrlDialogNext::Navigate { url, width, height } => {
118
handle.resize(Some(width), Some(height));
119
handle.post(json!({"kind": "load", "url": url}).to_string());
120
}
121
}
122
}
123
}
124
}
@@ -0,0 +1,124 @@1
use std::sync::{Arc, OnceLock};2
3
use gpui_kit::*;4
use serde_json::json;5
use teams_core::DialogIdentity;6
use webview::{DialogEvent, DialogHandle, DialogSpec, WebViewTransport};7
8
use super::sdk::{self, Effect, HostContext, HostPage};9
use super::{UrlDialog, UrlDialogNext};10
use crate::app_state::{AppHandle, AppState};11
use crate::backend::Engine;12
use crate::{notify, runtime, theme};13
14
static HOST: OnceLock<Arc<WebViewTransport>> = OnceLock::new();15
16
pub fn install_host(transport: Arc<WebViewTransport>) {17
let _ = HOST.set(transport);18
}19
20
pub fn open(dialog: UrlDialog, cx: &mut App) {21
let Some(host) = HOST.get().cloned() else {22
cx.open_url(&dialog.fallback_url);23
return;24
};25
let state = cx.global::<AppHandle>().0.clone();26
let engine = state.read(cx).engine.clone();27
let owner = cx28
.active_window()29
.and_then(|window| {30
window31
.update(cx, |_, window, _| notify::native_handle(window))32
.ok()33
})34
.flatten();35
cx.spawn(async move |cx| run(host, dialog, state, engine, owner, cx).await)36
.detach();37
}38
39
async fn run(40
host: Arc<WebViewTransport>,41
dialog: UrlDialog,42
state: Entity<AppState>,43
engine: Option<Arc<Engine>>,44
owner: Option<isize>,45
cx: &mut AsyncApp,46
) {47
let identity = fetch_identity(engine, &dialog.scope.conversation_id).await;48
let context = HostContext {49
user_id: identity.user_id,50
user_display_name: identity.display_name,51
tenant_id: identity.tenant_id,52
conversation_id: dialog.scope.conversation_id.clone(),53
app_id: dialog.app_id.clone(),54
session_id: uuid::Uuid::new_v4().to_string(),55
dark: true,56
web_application_resource: dialog.web_application_resource.clone(),57
};58
let page_html = HostPage {59
task_url: &dialog.url,60
background: theme::BACKGROUND,61
token_acquirer_script: &session::token_acquirer_script(),62
}63
.html();64
let (handle, mut events) = host.open_dialog(DialogSpec {65
title: dialog.title.clone(),66
width: dialog.width,67
height: dialog.height,68
background: theme::BACKGROUND,69
owner,70
page_url: sdk::host_page_url(),71
page_html,72
});73
while let Some(DialogEvent::Message(raw)) = events.recv().await {74
let handled = sdk::handle(&raw, &context);75
for directive in &handled.directives {76
handle.post(directive.to_string());77
}78
if let Some(effect) = handled.effect {79
apply(effect, &dialog, &state, &handle, cx).await;80
}81
}82
}83
84
async fn fetch_identity(engine: Option<Arc<Engine>>, conversation_id: &str) -> DialogIdentity {85
let empty = DialogIdentity {86
user_id: String::new(),87
display_name: String::new(),88
tenant_id: String::new(),89
};90
let Some(engine) = engine else {91
return empty;92
};93
let conversation_id = conversation_id.to_owned();94
let lookup = runtime::spawn(async move { engine.dialog_identity(&conversation_id).await.ok() });95
lookup.await.ok().flatten().unwrap_or(empty)96
}97
98
async fn apply(99
effect: Effect,100
dialog: &UrlDialog,101
state: &Entity<AppState>,102
handle: &DialogHandle,103
cx: &mut AsyncApp,104
) {105
match effect {106
Effect::Resize { width, height } => handle.resize(width, height),107
Effect::OpenLink(link) => {108
cx.update(|cx| cx.open_url(&link));109
}110
Effect::Submit(result) => {111
let scope = dialog.scope.clone();112
let next = state113
.update(cx, |state, cx| state.submit_url_dialog(scope, result, cx))114
.await;115
match next {116
UrlDialogNext::Close => handle.close(),117
UrlDialogNext::Navigate { url, width, height } => {118
handle.resize(Some(width), Some(height));119
handle.post(json!({"kind": "load", "url": url}).to_string());120
}121
}122
}123
}124
}@@ -0,0 +1,523 @@
1
use serde_json::{Map, Value, json};
2
3
pub const HOST_ORIGIN: &str = "https://teams.cloud.microsoft";
4
pub const HOST_PAGE_PATH: &str = "/__rusty/dialog";
5
const SDK_VERSION: &str = "2.1.0";
6
const FRAME_CONTEXT: &str = "task";
7
const CLIENT_TYPE: &str = "web";
8
const HOST_NAME: &str = "Teams";
9
const LOCALE: &str = "en-us";
10
const NOT_SUPPORTED: &str = "not supported";
11
const NO_SSO_RESOURCE: &str = "resourceDisabled";
12
const TOKEN_MARGIN_MS: u64 = 60_000;
13
const CHANNEL_SUFFIX: &str = "@thread.tacv2";
14
const HOST_PAGE_TEMPLATE: &str = include_str!("host_page.html");
15
16
pub fn host_page_url() -> String {
17
format!("{HOST_ORIGIN}{HOST_PAGE_PATH}")
18
}
19
20
#[derive(Debug, Clone, PartialEq)]
21
pub struct HostContext {
22
pub user_id: String,
23
pub user_display_name: String,
24
pub tenant_id: String,
25
pub conversation_id: String,
26
pub app_id: String,
27
pub session_id: String,
28
pub dark: bool,
29
pub web_application_resource: Option<String>,
30
}
31
32
#[derive(Debug, Clone, PartialEq)]
33
pub enum Effect {
34
Submit(Value),
35
Resize {
36
width: Option<u32>,
37
height: Option<u32>,
38
},
39
OpenLink(String),
40
}
41
42
#[derive(Debug, Default, PartialEq)]
43
pub struct Handled {
44
pub directives: Vec<Value>,
45
pub effect: Option<Effect>,
46
}
47
48
struct Request {
49
id: Value,
50
uuid: Value,
51
func: String,
52
args: Vec<Value>,
53
}
54
55
impl Request {
56
fn parse(envelope: &Value) -> Option<Request> {
57
let message = envelope.get("message")?;
58
Some(Request {
59
id: message.get("id").cloned().unwrap_or(Value::Null),
60
uuid: message.get("uuidAsString").cloned().unwrap_or(Value::Null),
61
func: message.get("func")?.as_str()?.to_owned(),
62
args: message
63
.get("args")
64
.and_then(Value::as_array)
65
.cloned()
66
.unwrap_or_default(),
67
})
68
}
69
70
fn reply(&self, args: Vec<Value>) -> Value {
71
json!({
72
"kind": "post",
73
"message": {"id": self.id, "uuidAsString": self.uuid, "args": args},
74
})
75
}
76
77
fn auth_token(&self, resource: &str) -> Value {
78
json!({
79
"kind": "authToken",
80
"id": self.id,
81
"uuidAsString": self.uuid,
82
"resource": resource,
83
})
84
}
85
}
86
87
pub fn handle(raw: &str, context: &HostContext) -> Handled {
88
let Ok(envelope) = serde_json::from_str::<Value>(raw) else {
89
return Handled::default();
90
};
91
match envelope.get("kind").and_then(Value::as_str) {
92
Some("sdk") => Request::parse(&envelope)
93
.map_or_else(Handled::default, |request| call(&request, context)),
94
Some("newWindow") => new_window(&envelope),
95
_ => Handled::default(),
96
}
97
}
98
99
fn new_window(envelope: &Value) -> Handled {
100
let link = envelope
101
.get("url")
102
.and_then(Value::as_str)
103
.unwrap_or_default();
104
Handled {
105
directives: Vec::new(),
106
effect: is_web_link(link).then(|| Effect::OpenLink(link.to_owned())),
107
}
108
}
109
110
fn is_web_link(link: &str) -> bool {
111
link.starts_with("https://") || link.starts_with("http://")
112
}
113
114
fn call(request: &Request, context: &HostContext) -> Handled {
115
match request.func.as_str() {
116
"initialize" => answer(request.reply(vec![
117
json!(FRAME_CONTEXT),
118
json!(CLIENT_TYPE),
119
json!(runtime_config().to_string()),
120
json!(SDK_VERSION),
121
])),
122
"getContext" => answer(request.reply(vec![legacy_context(context)])),
123
"authentication.getAuthToken" => {
124
answer(match context.web_application_resource.as_deref() {
125
Some(resource) => request.auth_token(resource),
126
None => request.reply(vec![json!(false), json!(NO_SSO_RESOURCE)]),
127
})
128
}
129
"tasks.completeTask" | "tasks.submitTask" | "dialog.url.submit" => Handled {
130
directives: Vec::new(),
131
effect: request
132
.args
133
.first()
134
.filter(|result| !result.is_null())
135
.cloned()
136
.map(Effect::Submit),
137
},
138
"tasks.updateTask" | "dialog.update.resize" => Handled {
139
directives: Vec::new(),
140
effect: Some(resize_of(request.args.first())),
141
},
142
"executeDeepLink" | "app.openLink" => open_link(request),
143
"registerHandler" => register_handler(request, context),
144
name if is_notification(name) => Handled::default(),
145
_ => answer(request.reply(vec![json!(false), json!(NOT_SUPPORTED)])),
146
}
147
}
148
149
fn answer(directive: Value) -> Handled {
150
Handled {
151
directives: vec![directive],
152
effect: None,
153
}
154
}
155
156
fn is_notification(name: &str) -> bool {
157
name.starts_with("appInitialization.") || name == "readyToUnload" || name == "setFrameContext"
158
}
159
160
fn resize_of(dimensions: Option<&Value>) -> Effect {
161
let pixels = |key: &str| {
162
dimensions
163
.and_then(|dimensions| dimensions.get(key))
164
.and_then(Value::as_u64)
165
.and_then(|pixels| u32::try_from(pixels).ok())
166
};
167
Effect::Resize {
168
width: pixels("width"),
169
height: pixels("height"),
170
}
171
}
172
173
fn open_link(request: &Request) -> Handled {
174
let link = request
175
.args
176
.first()
177
.and_then(Value::as_str)
178
.unwrap_or_default();
179
if is_web_link(link) {
180
Handled {
181
directives: vec![request.reply(vec![json!(true)])],
182
effect: Some(Effect::OpenLink(link.to_owned())),
183
}
184
} else {
185
answer(request.reply(vec![json!(false), json!(NOT_SUPPORTED)]))
186
}
187
}
188
189
fn register_handler(request: &Request, context: &HostContext) -> Handled {
190
let wants_theme = request.args.first().and_then(Value::as_str) == Some("themeChange");
191
Handled {
192
directives: if wants_theme {
193
vec![json!({
194
"kind": "post",
195
"message": {"func": "themeChange", "args": [theme_name(context.dark)]},
196
})]
197
} else {
198
Vec::new()
199
},
200
effect: None,
201
}
202
}
203
204
fn theme_name(dark: bool) -> &'static str {
205
if dark { "dark" } else { "default" }
206
}
207
208
pub fn runtime_config() -> Value {
209
json!({
210
"apiVersion": 4,
211
"hostVersionsInfo": {"adaptiveCardSchemaVersion": {"major": 1, "minor": 5}},
212
"isLegacyTeams": true,
213
"supports": {
214
"dialog": {
215
"card": {"bot": {}},
216
"url": {"bot": {}, "parentCommunication": {}},
217
"update": {},
218
},
219
"logs": {},
220
"teamsCore": {},
221
},
222
})
223
}
224
225
pub fn legacy_context(context: &HostContext) -> Value {
226
let mut fields = Map::new();
227
let mut put = |key: &str, value: Value| {
228
fields.insert(key.to_owned(), value);
229
};
230
put("locale", json!(LOCALE));
231
put("theme", json!(theme_name(context.dark)));
232
put("frameContext", json!(FRAME_CONTEXT));
233
put("hostClientType", json!(CLIENT_TYPE));
234
put("hostName", json!(HOST_NAME));
235
put("sessionId", json!(context.session_id));
236
put("appSessionId", json!(context.session_id));
237
put("userObjectId", json!(context.user_id));
238
put("userDisplayName", json!(context.user_display_name));
239
put("tid", json!(context.tenant_id));
240
put("appId", json!(context.app_id));
241
put("isFullScreen", json!(false));
242
let conversation_key = if context.conversation_id.ends_with(CHANNEL_SUFFIX) {
243
"channelId"
244
} else {
245
"chatId"
246
};
247
put(conversation_key, json!(context.conversation_id));
248
Value::Object(fields)
249
}
250
251
pub struct HostPage<'a> {
252
pub task_url: &'a str,
253
pub background: u32,
254
pub token_acquirer_script: &'a str,
255
}
256
257
impl HostPage<'_> {
258
pub fn html(&self) -> String {
259
let config = json!({"url": self.task_url, "marginMs": TOKEN_MARGIN_MS});
260
let safe_config = config.to_string().replace('<', "\\u003c");
261
HOST_PAGE_TEMPLATE
262
.replace("__BACKGROUND__", &format!("#{:06x}", self.background))
263
.replace("__CONFIG__", &safe_config)
264
.replace("__ACQUIRE__", self.token_acquirer_script)
265
}
266
}
267
268
#[cfg(test)]
269
mod tests {
270
use super::*;
271
272
fn context() -> HostContext {
273
HostContext {
274
user_id: "user-1".into(),
275
user_display_name: "Ada".into(),
276
tenant_id: "tenant-1".into(),
277
conversation_id: "19:chat@thread.v2".into(),
278
app_id: "app-1".into(),
279
session_id: "session-1".into(),
280
dark: true,
281
web_application_resource: Some("api://bot.example/app-1".into()),
282
}
283
}
284
285
fn call(func: &str, args: Value) -> String {
286
json!({"kind": "sdk", "message": {"id": 7, "uuidAsString": "uuid-7", "func": func, "args": args}})
287
.to_string()
288
}
289
290
fn reply_args(handled: &Handled) -> Value {
291
handled.directives[0]["message"]["args"].clone()
292
}
293
294
#[test]
295
fn replies_carry_the_numeric_id_and_the_uuid_string() {
296
let handled = handle(&call("getContext", json!([])), &context());
297
let message = &handled.directives[0]["message"];
298
assert_eq!(handled.directives[0]["kind"], "post");
299
assert_eq!(message["id"], 7);
300
assert_eq!(message["uuidAsString"], "uuid-7");
301
}
302
303
#[test]
304
fn initialize_answers_a_task_frame_on_the_web_client_with_a_runtime_config_string() {
305
let handled = handle(&call("initialize", json!(["2.0.0", 4, []])), &context());
306
let args = reply_args(&handled);
307
assert_eq!(args[0], "task");
308
assert_eq!(args[1], "web");
309
let runtime: Value = serde_json::from_str(args[2].as_str().unwrap()).unwrap();
310
assert_eq!(runtime, runtime_config());
311
assert_eq!(args[3], SDK_VERSION);
312
assert!(handled.effect.is_none());
313
}
314
315
#[test]
316
fn the_runtime_config_supports_bot_url_dialogs_and_resizing() {
317
let runtime = runtime_config();
318
assert_eq!(runtime["apiVersion"], 4);
319
assert!(runtime["supports"]["dialog"]["url"]["bot"].is_object());
320
assert!(runtime["supports"]["dialog"]["update"].is_object());
321
}
322
323
#[test]
324
fn get_context_describes_the_user_tenant_chat_and_theme() {
325
let args = reply_args(&handle(&call("getContext", json!([])), &context()));
326
let legacy = &args[0];
327
assert_eq!(legacy["frameContext"], "task");
328
assert_eq!(legacy["hostClientType"], "web");
329
assert_eq!(legacy["hostName"], "Teams");
330
assert_eq!(legacy["locale"], "en-us");
331
assert_eq!(legacy["theme"], "dark");
332
assert_eq!(legacy["userObjectId"], "user-1");
333
assert_eq!(legacy["tid"], "tenant-1");
334
assert_eq!(legacy["chatId"], "19:chat@thread.v2");
335
assert_eq!(legacy["appSessionId"], "session-1");
336
assert!(legacy.get("channelId").is_none());
337
}
338
339
#[test]
340
fn channel_conversations_are_reported_as_channels() {
341
let mut channel = context();
342
channel.conversation_id = "19:abc@thread.tacv2".into();
343
let legacy = legacy_context(&channel);
344
assert_eq!(legacy["channelId"], "19:abc@thread.tacv2");
345
assert!(legacy.get("chatId").is_none());
346
}
347
348
#[test]
349
fn a_light_theme_is_called_default() {
350
let mut light = context();
351
light.dark = false;
352
assert_eq!(legacy_context(&light)["theme"], "default");
353
}
354
355
#[test]
356
fn auth_tokens_are_requested_from_the_page_for_the_app_resource() {
357
let handled = handle(
358
&call("authentication.getAuthToken", json!([[], null, false])),
359
&context(),
360
);
361
assert_eq!(
362
handled.directives,
363
vec![json!({
364
"kind": "authToken",
365
"id": 7,
366
"uuidAsString": "uuid-7",
367
"resource": "api://bot.example/app-1",
368
})]
369
);
370
}
371
372
#[test]
373
fn auth_tokens_fail_when_the_app_has_no_sso_resource() {
374
let mut without_resource = context();
375
without_resource.web_application_resource = None;
376
let handled = handle(
377
&call("authentication.getAuthToken", json!([])),
378
&without_resource,
379
);
380
assert_eq!(reply_args(&handled), json!([false, NO_SSO_RESOURCE]));
381
}
382
383
#[test]
384
fn submitting_hands_the_result_to_the_bot() {
385
for func in [
386
"tasks.completeTask",
387
"tasks.submitTask",
388
"dialog.url.submit",
389
] {
390
let handled = handle(&call(func, json!([{"choice": "a"}, ["app-1"]])), &context());
391
assert_eq!(handled.effect, Some(Effect::Submit(json!({"choice": "a"}))));
392
assert!(handled.directives.is_empty());
393
}
394
}
395
396
#[test]
397
fn submitting_without_a_result_sends_nothing() {
398
let handled = handle(&call("tasks.completeTask", json!([])), &context());
399
assert_eq!(handled, Handled::default());
400
}
401
402
#[test]
403
fn resizing_takes_numeric_dimensions_only() {
404
let handled = handle(
405
&call(
406
"tasks.updateTask",
407
json!([{"width": 700, "height": "large"}]),
408
),
409
&context(),
410
);
411
assert_eq!(
412
handled.effect,
413
Some(Effect::Resize {
414
width: Some(700),
415
height: None
416
})
417
);
418
}
419
420
#[test]
421
fn web_links_open_in_the_browser_and_other_schemes_are_refused() {
422
let handled = handle(
423
&call("executeDeepLink", json!(["https://example.com/page"])),
424
&context(),
425
);
426
assert_eq!(
427
handled.effect,
428
Some(Effect::OpenLink("https://example.com/page".into()))
429
);
430
assert_eq!(reply_args(&handled), json!([true]));
431
let refused = handle(
432
&call("executeDeepLink", json!(["file:///etc/passwd"])),
433
&context(),
434
);
435
assert!(refused.effect.is_none());
436
assert_eq!(reply_args(&refused), json!([false, NOT_SUPPORTED]));
437
}
438
439
#[test]
440
fn popups_of_the_page_open_in_the_browser() {
441
let popup = |url: &str| json!({"kind": "newWindow", "url": url}).to_string();
442
let handled = handle(&popup("https://example.com/docs"), &context());
443
assert_eq!(
444
handled.effect,
445
Some(Effect::OpenLink("https://example.com/docs".into()))
446
);
447
assert!(
448
handle(&popup("javascript:alert(1)"), &context())
449
.effect
450
.is_none()
451
);
452
}
453
454
#[test]
455
fn registering_a_theme_handler_pushes_the_current_theme() {
456
let handled = handle(&call("registerHandler", json!(["themeChange"])), &context());
457
assert_eq!(
458
handled.directives,
459
vec![json!({"kind": "post", "message": {"func": "themeChange", "args": ["dark"]}})]
460
);
461
let other = handle(&call("registerHandler", json!(["load"])), &context());
462
assert_eq!(other, Handled::default());
463
}
464
465
#[test]
466
fn lifecycle_notifications_are_not_answered() {
467
for func in [
468
"appInitialization.appLoaded",
469
"appInitialization.success",
470
"appInitialization.failure",
471
"readyToUnload",
472
] {
473
assert_eq!(
474
handle(&call(func, json!([])), &context()),
475
Handled::default()
476
);
477
}
478
}
479
480
#[test]
481
fn unknown_calls_are_answered_as_unsupported() {
482
let handled = handle(&call("media.captureImage", json!([])), &context());
483
assert_eq!(reply_args(&handled), json!([false, NOT_SUPPORTED]));
484
}
485
486
#[test]
487
fn malformed_or_foreign_messages_are_ignored() {
488
for raw in [
489
"not json",
490
r#"{"kind":"other"}"#,
491
r#"{"kind":"sdk","message":{"id":1}}"#,
492
] {
493
assert_eq!(handle(raw, &context()), Handled::default());
494
}
495
}
496
497
#[test]
498
fn the_host_page_embeds_the_task_url_and_cannot_be_broken_out_of() {
499
let page = HostPage {
500
task_url: "https://bot.example/task?x=</script><script>alert(1)",
501
background: 0x0f0f10,
502
token_acquirer_script: "(async () => () => null)",
503
}
504
.html();
505
assert!(page.contains("#0f0f10"));
506
assert!(page.contains("(async () => () => null)"));
507
assert!(page.contains(r"\u003c/script>\u003cscript>alert(1)"));
508
assert_eq!(page.matches("</script>").count(), 1);
509
assert!(
510
!page.contains("__CONFIG__")
511
&& !page.contains("__ACQUIRE__")
512
&& !page.contains("__BACKGROUND__")
513
);
514
}
515
516
#[test]
517
fn the_host_page_url_lives_on_an_origin_the_sdk_trusts() {
518
assert_eq!(
519
host_page_url(),
520
"https://teams.cloud.microsoft/__rusty/dialog"
521
);
522
}
523
}
@@ -0,0 +1,523 @@1
use serde_json::{Map, Value, json};2
3
pub const HOST_ORIGIN: &str = "https://teams.cloud.microsoft";4
pub const HOST_PAGE_PATH: &str = "/__rusty/dialog";5
const SDK_VERSION: &str = "2.1.0";6
const FRAME_CONTEXT: &str = "task";7
const CLIENT_TYPE: &str = "web";8
const HOST_NAME: &str = "Teams";9
const LOCALE: &str = "en-us";10
const NOT_SUPPORTED: &str = "not supported";11
const NO_SSO_RESOURCE: &str = "resourceDisabled";12
const TOKEN_MARGIN_MS: u64 = 60_000;13
const CHANNEL_SUFFIX: &str = "@thread.tacv2";14
const HOST_PAGE_TEMPLATE: &str = include_str!("host_page.html");15
16
pub fn host_page_url() -> String {17
format!("{HOST_ORIGIN}{HOST_PAGE_PATH}")18
}19
20
#[derive(Debug, Clone, PartialEq)]21
pub struct HostContext {22
pub user_id: String,23
pub user_display_name: String,24
pub tenant_id: String,25
pub conversation_id: String,26
pub app_id: String,27
pub session_id: String,28
pub dark: bool,29
pub web_application_resource: Option<String>,30
}31
32
#[derive(Debug, Clone, PartialEq)]33
pub enum Effect {34
Submit(Value),35
Resize {36
width: Option<u32>,37
height: Option<u32>,38
},39
OpenLink(String),40
}41
42
#[derive(Debug, Default, PartialEq)]43
pub struct Handled {44
pub directives: Vec<Value>,45
pub effect: Option<Effect>,46
}47
48
struct Request {49
id: Value,50
uuid: Value,51
func: String,52
args: Vec<Value>,53
}54
55
impl Request {56
fn parse(envelope: &Value) -> Option<Request> {57
let message = envelope.get("message")?;58
Some(Request {59
id: message.get("id").cloned().unwrap_or(Value::Null),60
uuid: message.get("uuidAsString").cloned().unwrap_or(Value::Null),61
func: message.get("func")?.as_str()?.to_owned(),62
args: message63
.get("args")64
.and_then(Value::as_array)65
.cloned()66
.unwrap_or_default(),67
})68
}69
70
fn reply(&self, args: Vec<Value>) -> Value {71
json!({72
"kind": "post",73
"message": {"id": self.id, "uuidAsString": self.uuid, "args": args},74
})75
}76
77
fn auth_token(&self, resource: &str) -> Value {78
json!({79
"kind": "authToken",80
"id": self.id,81
"uuidAsString": self.uuid,82
"resource": resource,83
})84
}85
}86
87
pub fn handle(raw: &str, context: &HostContext) -> Handled {88
let Ok(envelope) = serde_json::from_str::<Value>(raw) else {89
return Handled::default();90
};91
match envelope.get("kind").and_then(Value::as_str) {92
Some("sdk") => Request::parse(&envelope)93
.map_or_else(Handled::default, |request| call(&request, context)),94
Some("newWindow") => new_window(&envelope),95
_ => Handled::default(),96
}97
}98
99
fn new_window(envelope: &Value) -> Handled {100
let link = envelope101
.get("url")102
.and_then(Value::as_str)103
.unwrap_or_default();104
Handled {105
directives: Vec::new(),106
effect: is_web_link(link).then(|| Effect::OpenLink(link.to_owned())),107
}108
}109
110
fn is_web_link(link: &str) -> bool {111
link.starts_with("https://") || link.starts_with("http://")112
}113
114
fn call(request: &Request, context: &HostContext) -> Handled {115
match request.func.as_str() {116
"initialize" => answer(request.reply(vec![117
json!(FRAME_CONTEXT),118
json!(CLIENT_TYPE),119
json!(runtime_config().to_string()),120
json!(SDK_VERSION),121
])),122
"getContext" => answer(request.reply(vec![legacy_context(context)])),123
"authentication.getAuthToken" => {124
answer(match context.web_application_resource.as_deref() {125
Some(resource) => request.auth_token(resource),126
None => request.reply(vec![json!(false), json!(NO_SSO_RESOURCE)]),127
})128
}129
"tasks.completeTask" | "tasks.submitTask" | "dialog.url.submit" => Handled {130
directives: Vec::new(),131
effect: request132
.args133
.first()134
.filter(|result| !result.is_null())135
.cloned()136
.map(Effect::Submit),137
},138
"tasks.updateTask" | "dialog.update.resize" => Handled {139
directives: Vec::new(),140
effect: Some(resize_of(request.args.first())),141
},142
"executeDeepLink" | "app.openLink" => open_link(request),143
"registerHandler" => register_handler(request, context),144
name if is_notification(name) => Handled::default(),145
_ => answer(request.reply(vec![json!(false), json!(NOT_SUPPORTED)])),146
}147
}148
149
fn answer(directive: Value) -> Handled {150
Handled {151
directives: vec![directive],152
effect: None,153
}154
}155
156
fn is_notification(name: &str) -> bool {157
name.starts_with("appInitialization.") || name == "readyToUnload" || name == "setFrameContext"158
}159
160
fn resize_of(dimensions: Option<&Value>) -> Effect {161
let pixels = |key: &str| {162
dimensions163
.and_then(|dimensions| dimensions.get(key))164
.and_then(Value::as_u64)165
.and_then(|pixels| u32::try_from(pixels).ok())166
};167
Effect::Resize {168
width: pixels("width"),169
height: pixels("height"),170
}171
}172
173
fn open_link(request: &Request) -> Handled {174
let link = request175
.args176
.first()177
.and_then(Value::as_str)178
.unwrap_or_default();179
if is_web_link(link) {180
Handled {181
directives: vec![request.reply(vec![json!(true)])],182
effect: Some(Effect::OpenLink(link.to_owned())),183
}184
} else {185
answer(request.reply(vec![json!(false), json!(NOT_SUPPORTED)]))186
}187
}188
189
fn register_handler(request: &Request, context: &HostContext) -> Handled {190
let wants_theme = request.args.first().and_then(Value::as_str) == Some("themeChange");191
Handled {192
directives: if wants_theme {193
vec![json!({194
"kind": "post",195
"message": {"func": "themeChange", "args": [theme_name(context.dark)]},196
})]197
} else {198
Vec::new()199
},200
effect: None,201
}202
}203
204
fn theme_name(dark: bool) -> &'static str {205
if dark { "dark" } else { "default" }206
}207
208
pub fn runtime_config() -> Value {209
json!({210
"apiVersion": 4,211
"hostVersionsInfo": {"adaptiveCardSchemaVersion": {"major": 1, "minor": 5}},212
"isLegacyTeams": true,213
"supports": {214
"dialog": {215
"card": {"bot": {}},216
"url": {"bot": {}, "parentCommunication": {}},217
"update": {},218
},219
"logs": {},220
"teamsCore": {},221
},222
})223
}224
225
pub fn legacy_context(context: &HostContext) -> Value {226
let mut fields = Map::new();227
let mut put = |key: &str, value: Value| {228
fields.insert(key.to_owned(), value);229
};230
put("locale", json!(LOCALE));231
put("theme", json!(theme_name(context.dark)));232
put("frameContext", json!(FRAME_CONTEXT));233
put("hostClientType", json!(CLIENT_TYPE));234
put("hostName", json!(HOST_NAME));235
put("sessionId", json!(context.session_id));236
put("appSessionId", json!(context.session_id));237
put("userObjectId", json!(context.user_id));238
put("userDisplayName", json!(context.user_display_name));239
put("tid", json!(context.tenant_id));240
put("appId", json!(context.app_id));241
put("isFullScreen", json!(false));242
let conversation_key = if context.conversation_id.ends_with(CHANNEL_SUFFIX) {243
"channelId"244
} else {245
"chatId"246
};247
put(conversation_key, json!(context.conversation_id));248
Value::Object(fields)249
}250
251
pub struct HostPage<'a> {252
pub task_url: &'a str,253
pub background: u32,254
pub token_acquirer_script: &'a str,255
}256
257
impl HostPage<'_> {258
pub fn html(&self) -> String {259
let config = json!({"url": self.task_url, "marginMs": TOKEN_MARGIN_MS});260
let safe_config = config.to_string().replace('<', "\\u003c");261
HOST_PAGE_TEMPLATE262
.replace("__BACKGROUND__", &format!("#{:06x}", self.background))263
.replace("__CONFIG__", &safe_config)264
.replace("__ACQUIRE__", self.token_acquirer_script)265
}266
}267
268
#[cfg(test)]269
mod tests {270
use super::*;271
272
fn context() -> HostContext {273
HostContext {274
user_id: "user-1".into(),275
user_display_name: "Ada".into(),276
tenant_id: "tenant-1".into(),277
conversation_id: "19:chat@thread.v2".into(),278
app_id: "app-1".into(),279
session_id: "session-1".into(),280
dark: true,281
web_application_resource: Some("api://bot.example/app-1".into()),282
}283
}284
285
fn call(func: &str, args: Value) -> String {286
json!({"kind": "sdk", "message": {"id": 7, "uuidAsString": "uuid-7", "func": func, "args": args}})287
.to_string()288
}289
290
fn reply_args(handled: &Handled) -> Value {291
handled.directives[0]["message"]["args"].clone()292
}293
294
#[test]295
fn replies_carry_the_numeric_id_and_the_uuid_string() {296
let handled = handle(&call("getContext", json!([])), &context());297
let message = &handled.directives[0]["message"];298
assert_eq!(handled.directives[0]["kind"], "post");299
assert_eq!(message["id"], 7);300
assert_eq!(message["uuidAsString"], "uuid-7");301
}302
303
#[test]304
fn initialize_answers_a_task_frame_on_the_web_client_with_a_runtime_config_string() {305
let handled = handle(&call("initialize", json!(["2.0.0", 4, []])), &context());306
let args = reply_args(&handled);307
assert_eq!(args[0], "task");308
assert_eq!(args[1], "web");309
let runtime: Value = serde_json::from_str(args[2].as_str().unwrap()).unwrap();310
assert_eq!(runtime, runtime_config());311
assert_eq!(args[3], SDK_VERSION);312
assert!(handled.effect.is_none());313
}314
315
#[test]316
fn the_runtime_config_supports_bot_url_dialogs_and_resizing() {317
let runtime = runtime_config();318
assert_eq!(runtime["apiVersion"], 4);319
assert!(runtime["supports"]["dialog"]["url"]["bot"].is_object());320
assert!(runtime["supports"]["dialog"]["update"].is_object());321
}322
323
#[test]324
fn get_context_describes_the_user_tenant_chat_and_theme() {325
let args = reply_args(&handle(&call("getContext", json!([])), &context()));326
let legacy = &args[0];327
assert_eq!(legacy["frameContext"], "task");328
assert_eq!(legacy["hostClientType"], "web");329
assert_eq!(legacy["hostName"], "Teams");330
assert_eq!(legacy["locale"], "en-us");331
assert_eq!(legacy["theme"], "dark");332
assert_eq!(legacy["userObjectId"], "user-1");333
assert_eq!(legacy["tid"], "tenant-1");334
assert_eq!(legacy["chatId"], "19:chat@thread.v2");335
assert_eq!(legacy["appSessionId"], "session-1");336
assert!(legacy.get("channelId").is_none());337
}338
339
#[test]340
fn channel_conversations_are_reported_as_channels() {341
let mut channel = context();342
channel.conversation_id = "19:abc@thread.tacv2".into();343
let legacy = legacy_context(&channel);344
assert_eq!(legacy["channelId"], "19:abc@thread.tacv2");345
assert!(legacy.get("chatId").is_none());346
}347
348
#[test]349
fn a_light_theme_is_called_default() {350
let mut light = context();351
light.dark = false;352
assert_eq!(legacy_context(&light)["theme"], "default");353
}354
355
#[test]356
fn auth_tokens_are_requested_from_the_page_for_the_app_resource() {357
let handled = handle(358
&call("authentication.getAuthToken", json!([[], null, false])),359
&context(),360
);361
assert_eq!(362
handled.directives,363
vec![json!({364
"kind": "authToken",365
"id": 7,366
"uuidAsString": "uuid-7",367
"resource": "api://bot.example/app-1",368
})]369
);370
}371
372
#[test]373
fn auth_tokens_fail_when_the_app_has_no_sso_resource() {374
let mut without_resource = context();375
without_resource.web_application_resource = None;376
let handled = handle(377
&call("authentication.getAuthToken", json!([])),378
&without_resource,379
);380
assert_eq!(reply_args(&handled), json!([false, NO_SSO_RESOURCE]));381
}382
383
#[test]384
fn submitting_hands_the_result_to_the_bot() {385
for func in [386
"tasks.completeTask",387
"tasks.submitTask",388
"dialog.url.submit",389
] {390
let handled = handle(&call(func, json!([{"choice": "a"}, ["app-1"]])), &context());391
assert_eq!(handled.effect, Some(Effect::Submit(json!({"choice": "a"}))));392
assert!(handled.directives.is_empty());393
}394
}395
396
#[test]397
fn submitting_without_a_result_sends_nothing() {398
let handled = handle(&call("tasks.completeTask", json!([])), &context());399
assert_eq!(handled, Handled::default());400
}401
402
#[test]403
fn resizing_takes_numeric_dimensions_only() {404
let handled = handle(405
&call(406
"tasks.updateTask",407
json!([{"width": 700, "height": "large"}]),408
),409
&context(),410
);411
assert_eq!(412
handled.effect,413
Some(Effect::Resize {414
width: Some(700),415
height: None416
})417
);418
}419
420
#[test]421
fn web_links_open_in_the_browser_and_other_schemes_are_refused() {422
let handled = handle(423
&call("executeDeepLink", json!(["https://example.com/page"])),424
&context(),425
);426
assert_eq!(427
handled.effect,428
Some(Effect::OpenLink("https://example.com/page".into()))429
);430
assert_eq!(reply_args(&handled), json!([true]));431
let refused = handle(432
&call("executeDeepLink", json!(["file:///etc/passwd"])),433
&context(),434
);435
assert!(refused.effect.is_none());436
assert_eq!(reply_args(&refused), json!([false, NOT_SUPPORTED]));437
}438
439
#[test]440
fn popups_of_the_page_open_in_the_browser() {441
let popup = |url: &str| json!({"kind": "newWindow", "url": url}).to_string();442
let handled = handle(&popup("https://example.com/docs"), &context());443
assert_eq!(444
handled.effect,445
Some(Effect::OpenLink("https://example.com/docs".into()))446
);447
assert!(448
handle(&popup("javascript:alert(1)"), &context())449
.effect450
.is_none()451
);452
}453
454
#[test]455
fn registering_a_theme_handler_pushes_the_current_theme() {456
let handled = handle(&call("registerHandler", json!(["themeChange"])), &context());457
assert_eq!(458
handled.directives,459
vec![json!({"kind": "post", "message": {"func": "themeChange", "args": ["dark"]}})]460
);461
let other = handle(&call("registerHandler", json!(["load"])), &context());462
assert_eq!(other, Handled::default());463
}464
465
#[test]466
fn lifecycle_notifications_are_not_answered() {467
for func in [468
"appInitialization.appLoaded",469
"appInitialization.success",470
"appInitialization.failure",471
"readyToUnload",472
] {473
assert_eq!(474
handle(&call(func, json!([])), &context()),475
Handled::default()476
);477
}478
}479
480
#[test]481
fn unknown_calls_are_answered_as_unsupported() {482
let handled = handle(&call("media.captureImage", json!([])), &context());483
assert_eq!(reply_args(&handled), json!([false, NOT_SUPPORTED]));484
}485
486
#[test]487
fn malformed_or_foreign_messages_are_ignored() {488
for raw in [489
"not json",490
r#"{"kind":"other"}"#,491
r#"{"kind":"sdk","message":{"id":1}}"#,492
] {493
assert_eq!(handle(raw, &context()), Handled::default());494
}495
}496
497
#[test]498
fn the_host_page_embeds_the_task_url_and_cannot_be_broken_out_of() {499
let page = HostPage {500
task_url: "https://bot.example/task?x=</script><script>alert(1)",501
background: 0x0f0f10,502
token_acquirer_script: "(async () => () => null)",503
}504
.html();505
assert!(page.contains("#0f0f10"));506
assert!(page.contains("(async () => () => null)"));507
assert!(page.contains(r"\u003c/script>\u003cscript>alert(1)"));508
assert_eq!(page.matches("</script>").count(), 1);509
assert!(510
!page.contains("__CONFIG__")511
&& !page.contains("__ACQUIRE__")512
&& !page.contains("__BACKGROUND__")513
);514
}515
516
#[test]517
fn the_host_page_url_lives_on_an_origin_the_sdk_trusts() {518
assert_eq!(519
host_page_url(),520
"https://teams.cloud.microsoft/__rusty/dialog"521
);522
}523
}@@ -13,7 +13,7 @@ const FONT_FILES: [&[u8]; 4] = [
13
13
include_bytes!("../assets/fonts/GoogleSansFlex-Italic.ttf"),
14
14
];
15
15
16
const BACKGROUND: u32 = 0x0f0f10;
16
pub const BACKGROUND: u32 = 0x0f0f10;
17
17
const SURFACE: u32 = 0x161617;
18
18
const SURFACE_RAISED: u32 = 0x232325;
19
19
const ROW_HOVER: u32 = 0x1c1c1e;
@@ -13,7 +13,7 @@ const FONT_FILES: [&[u8]; 4] = [13
include_bytes!("../assets/fonts/GoogleSansFlex-Italic.ttf"),13
include_bytes!("../assets/fonts/GoogleSansFlex-Italic.ttf"),14
];14
];15
15
16
const BACKGROUND: u32 = 0x0f0f10;16
pub const BACKGROUND: u32 = 0x0f0f10;17
const SURFACE: u32 = 0x161617;17
const SURFACE: u32 = 0x161617;18
const SURFACE_RAISED: u32 = 0x232325;18
const SURFACE_RAISED: u32 = 0x232325;19
const ROW_HOVER: u32 = 0x1c1c1e;19
const ROW_HOVER: u32 = 0x1c1c1e;@@ -1,3 +1,5 @@
1
use std::collections::HashMap;
2
1
3
use gpui_kit::component::{h_flex, tooltip::Tooltip, v_flex};
2
4
use gpui_kit::prelude::FluentBuilder as _;
3
5
use gpui_kit::*;
@@ -7,6 +9,9 @@ use teams_core::{
7
9
VerticalAlignment,
8
10
};
9
11
12
use super::widgets::symbol;
13
use crate::app_state::AppHandle;
14
use crate::card_state::{ActionPhase, CardScope, CardState};
10
15
use crate::render::{layout_blocks, render_blocks};
11
16
use crate::theme;
12
17
@@ -22,6 +27,10 @@ const ACTION_RADIUS: f32 = 6.;
22
27
const ACTION_TEXT_SIZE: f32 = 13.;
23
28
const ACTION_DISABLED_OPACITY: f32 = 0.5;
24
29
const ACTION_DISABLED_TOOLTIP: &str = "Not supported in this app";
30
const ACTION_BUSY_OPACITY: f32 = 0.6;
31
const ACTION_CHECK_SIZE: f32 = 14.;
32
const ACTION_ICON_GAP: f32 = 4.;
33
const NOTE_TEXT_SIZE: f32 = 12.;
25
34
const FACT_TITLE_WIDTH: f32 = 96.;
26
35
const FACT_GAP: f32 = 2.;
27
36
const CONTAINER_PADDING: f32 = 8.;
@@ -35,20 +44,64 @@ const MEDIUM_IMAGE: f32 = 80.;
35
44
const LARGE_IMAGE: f32 = 160.;
36
45
const EXTERNAL_IMAGE_SCHEME: &str = "https://";
37
46
38
pub fn cards_view(cards: &[AdaptiveCard], id: &str, cx: &App) -> Vec<AnyElement> {
47
struct CardContext<'a> {
48
cx: &'a App,
49
scope: &'a CardScope,
50
state: &'a CardState,
51
root_key: String,
52
initial_visibility: HashMap<String, bool>,
53
}
54
55
impl<'a> CardContext<'a> {
56
fn new(card: &AdaptiveCard, scope: &'a CardScope, cx: &'a App) -> Self {
57
CardContext {
58
cx,
59
scope,
60
state: &cx.global::<AppHandle>().0.read(cx).cards,
61
root_key: scope.card_key(),
62
initial_visibility: card.element_visibility(),
63
}
64
}
65
66
fn visible(&self, id: Option<&String>, initial: bool) -> bool {
67
match id {
68
Some(id) => self
69
.state
70
.is_visible(&format!("{}/{id}", self.root_key), initial),
71
None => initial,
72
}
73
}
74
}
75
76
pub fn cards_view(
77
cards: &[AdaptiveCard],
78
conversation_id: &str,
79
message_id: &str,
80
cx: &App,
81
) -> Vec<AnyElement> {
39
82
cards
40
83
.iter()
41
84
.enumerate()
42
.map(|(index, card)| card_view(card, &format!("{id}-card-{index}"), cx))
85
.map(|(index, card)| {
86
let scope = CardScope::message(conversation_id, message_id, index);
87
card_view(card, &scope, cx)
88
})
43
89
.collect()
44
90
}
45
91
46
fn card_view(card: &AdaptiveCard, id: &str, cx: &App) -> AnyElement {
92
pub fn card_view(card: &AdaptiveCard, scope: &CardScope, cx: &App) -> AnyElement {
93
let context = CardContext::new(card, scope, cx);
94
let id = scope.card_key();
47
95
let width = if card.full_width {
48
96
CARD_FULL_WIDTH
49
97
} else {
50
98
CARD_WIDTH
51
99
};
100
let note = context.state.note(&id).map(str::to_owned);
101
let visible_actions = card
102
.actions
103
.iter()
104
.any(|action| context.visible(action.id.as_ref(), action.visible));
52
105
v_flex()
53
106
.w(px(width))
54
107
.max_w(relative(1.))
@@ -58,35 +111,50 @@ fn card_view(card: &AdaptiveCard, id: &str, cx: &App) -> AnyElement {
58
111
.border(px(CARD_BORDER_WIDTH))
59
112
.border_color(theme::border())
60
113
.text_color(theme::text_strong())
61
.child(items_view(&card.items, id, cx))
62
.when(!card.actions.is_empty(), |card_element| {
114
.child(items_view(&card.items, &id, &context))
115
.when(visible_actions, |card_element| {
116
card_element.child(div().mt(px(spacing_pixels(CardSpacing::Default))).child(
117
actions_view(&card.actions, &format!("{id}-actions"), &context),
118
))
119
})
120
.when_some(note, |card_element, note| {
63
121
card_element.child(
64
122
div()
65
123
.mt(px(spacing_pixels(CardSpacing::Default)))
66
.child(actions_view(&card.actions, &format!("{id}-actions"))),
124
.text_size(px(NOTE_TEXT_SIZE))
125
.text_color(theme::text_muted())
126
.child(note),
67
127
)
68
128
})
69
129
.into_any_element()
70
130
}
71
131
72
fn items_view(items: &[CardItem], id: &str, cx: &App) -> Div {
73
v_flex()
74
.w_full()
75
.children(items.iter().enumerate().map(|(index, item)| {
76
let item_id = format!("{id}-{index}");
132
fn items_view(items: &[CardItem], id: &str, context: &CardContext) -> Div {
133
let mut shown = 0;
134
let mut column = v_flex().w_full();
135
for (index, item) in items.iter().enumerate() {
136
if !context.visible(item.id.as_ref(), item.visible) {
137
continue;
138
}
139
let item_id = format!("{id}-{index}");
140
let first = shown == 0;
141
shown += 1;
142
column = column.child(
77
143
div()
78
144
.w_full()
79
.when(index > 0, |wrapper| {
145
.when(!first, |wrapper| {
80
146
wrapper.mt(px(spacing_pixels(item.spacing)))
81
147
})
82
.when(index > 0 && item.separator, |wrapper| {
148
.when(!first && item.separator, |wrapper| {
83
149
wrapper
84
150
.pt(px(SEPARATOR_PADDING))
85
151
.border_t_1()
86
152
.border_color(theme::border())
87
153
})
88
.child(element_view(&item.element, &item_id, cx))
89
}))
154
.child(element_view(&item.element, &item_id, context)),
155
);
156
}
157
column
90
158
}
91
159
92
160
fn spacing_pixels(spacing: CardSpacing) -> f32 {
@@ -100,9 +168,9 @@ fn spacing_pixels(spacing: CardSpacing) -> f32 {
100
168
}
101
169
}
102
170
103
fn element_view(element: &CardElement, id: &str, cx: &App) -> AnyElement {
171
fn element_view(element: &CardElement, id: &str, context: &CardContext) -> AnyElement {
104
172
match element {
105
CardElement::Text(text) => text_view(text, id, cx),
173
CardElement::Text(text) => text_view(text, id, context.cx),
106
174
CardElement::Image(image) => image_view(image, id),
107
175
CardElement::ImageSet(images) => h_flex()
108
176
.flex_wrap()
@@ -114,10 +182,10 @@ fn element_view(element: &CardElement, id: &str, cx: &App) -> AnyElement {
114
182
.map(|(index, image)| image_view(image, &format!("{id}-{index}"))),
115
183
)
116
184
.into_any_element(),
117
CardElement::Columns(columns) => columns_view(columns, id, cx),
185
CardElement::Columns(columns) => columns_view(columns, id, context),
118
186
CardElement::Container { style, items } => {
119
187
let tint = container_tint(*style);
120
items_view(items, id, cx)
188
items_view(items, id, context)
121
189
.when_some(tint, |container, tint| {
122
190
container
123
191
.p(px(CONTAINER_PADDING))
@@ -126,8 +194,8 @@ fn element_view(element: &CardElement, id: &str, cx: &App) -> AnyElement {
126
194
})
127
195
.into_any_element()
128
196
}
129
CardElement::Facts(facts) => facts_view(facts, id, cx),
130
CardElement::Actions(actions) => actions_view(actions, id).into_any_element(),
197
CardElement::Facts(facts) => facts_view(facts, id, context.cx),
198
CardElement::Actions(actions) => actions_view(actions, id, context).into_any_element(),
131
199
}
132
200
}
133
201
@@ -208,7 +276,7 @@ fn facts_view(facts: &[CardFact], id: &str, cx: &App) -> AnyElement {
208
276
.into_any_element()
209
277
}
210
278
211
fn columns_view(columns: &[CardColumn], id: &str, cx: &App) -> AnyElement {
279
fn columns_view(columns: &[CardColumn], id: &str, context: &CardContext) -> AnyElement {
212
280
div()
213
281
.flex()
214
282
.flex_row()
@@ -216,7 +284,7 @@ fn columns_view(columns: &[CardColumn], id: &str, cx: &App) -> AnyElement {
216
284
.w_full()
217
285
.gap(px(COLUMN_GAP))
218
286
.children(columns.iter().enumerate().map(|(index, column)| {
219
let content = items_view(&column.items, &format!("{id}-{index}"), cx);
287
let content = items_view(&column.items, &format!("{id}-{index}"), context);
220
288
let aligned = v_flex()
221
289
.h_full()
222
290
.map(|aligned| match column.vertical_alignment {
@@ -296,42 +364,167 @@ fn named_image_width(size: ImageSize) -> Option<f32> {
296
364
}
297
365
}
298
366
299
fn actions_view(actions: &[CardAction], id: &str) -> Div {
300
h_flex().w_full().flex_wrap().gap(px(ACTION_GAP)).children(
301
actions
302
.iter()
303
.enumerate()
304
.map(|(index, action)| action_button(action, format!("{id}-{index}"))),
305
)
367
fn actions_view(actions: &[CardAction], id: &str, context: &CardContext) -> Div {
368
let open_card = context
369
.state
370
.open_card(id)
371
.and_then(|index| actions.get(index))
372
.and_then(|action| match &action.kind {
373
CardActionKind::ShowCard(card) => Some(card),
374
_ => None,
375
});
376
v_flex()
377
.w_full()
378
.gap(px(ACTION_GAP))
379
.child(
380
h_flex().w_full().flex_wrap().gap(px(ACTION_GAP)).children(
381
actions
382
.iter()
383
.enumerate()
384
.filter(|(_, action)| context.visible(action.id.as_ref(), action.visible))
385
.map(|(index, action)| action_button(action, index, id, context)),
386
),
387
)
388
.when_some(open_card, |column, card| {
389
let nested_id = format!("{id}-show");
390
column.child(
391
v_flex()
392
.w_full()
393
.p(px(CONTAINER_PADDING))
394
.gap(px(ACTION_GAP))
395
.rounded(px(CONTAINER_RADIUS))
396
.bg(theme::surface_raised())
397
.child(items_view(&card.items, &nested_id, context))
398
.when(!card.actions.is_empty(), |nested| {
399
nested.child(actions_view(
400
&card.actions,
401
&format!("{nested_id}-actions"),
402
context,
403
))
404
}),
405
)
406
})
306
407
}
307
408
308
fn action_button(action: &CardAction, id: String) -> Stateful<Div> {
409
fn action_button(
410
action: &CardAction,
411
index: usize,
412
actions_id: &str,
413
context: &CardContext,
414
) -> Stateful<Div> {
415
let button_id = format!("{actions_id}-{index}");
416
let phase = context.state.phase(&button_id).cloned();
417
let label = action_label(
418
action,
419
&phase,
420
context.state.open_card(actions_id) == Some(index),
421
);
309
422
let button = div()
310
.id(ElementId::Name(id.into()))
423
.id(ElementId::Name(button_id.clone().into()))
311
424
.px(px(12.))
312
425
.py(px(6.))
313
426
.rounded(px(ACTION_RADIUS))
314
427
.border_1()
315
.border_color(theme::border_strong())
428
.border_color(match phase {
429
Some(ActionPhase::Failed(_)) => theme::red(),
430
_ => theme::border_strong(),
431
})
316
432
.text_size(px(ACTION_TEXT_SIZE))
317
433
.font_weight(FontWeight::SEMIBOLD)
318
.child(action.title.clone());
434
.child(label);
435
if !action.is_clickable() {
436
return button
437
.text_color(theme::text_muted())
438
.opacity(ACTION_DISABLED_OPACITY)
439
.when(action.enabled, |button| {
440
button.tooltip(|window, cx| Tooltip::new(ACTION_DISABLED_TOOLTIP).build(window, cx))
441
})
442
.on_click(|_, _, cx| cx.stop_propagation());
443
}
444
let enabled = button.text_color(theme::accent_text());
445
if phase == Some(ActionPhase::Busy) {
446
return enabled
447
.opacity(ACTION_BUSY_OPACITY)
448
.on_click(|_, _, cx| cx.stop_propagation());
449
}
450
let enabled = enabled
451
.cursor_pointer()
452
.hover(|button| button.bg(theme::row_hover()))
453
.when_some(failure_reason(&phase), |button, reason| {
454
button.tooltip(move |window, cx| Tooltip::new(reason.clone()).build(window, cx))
455
});
456
let scope = context.scope.clone();
319
457
match &action.kind {
320
458
CardActionKind::OpenUrl(url) => {
321
459
let url = url.clone();
322
button
323
.text_color(theme::accent_text())
324
.cursor_pointer()
325
.hover(|button| button.bg(theme::row_hover()))
326
.on_click(move |_, _, cx| {
327
cx.stop_propagation();
328
cx.open_url(&url);
460
enabled.on_click(move |_, _, cx| {
461
cx.stop_propagation();
462
cx.open_url(&url);
463
})
464
}
465
CardActionKind::Submit(_) | CardActionKind::Execute(_) => {
466
let action = action.clone();
467
enabled.on_click(move |_, _, cx| {
468
cx.stop_propagation();
469
let (scope, action, button_id) = (scope.clone(), action.clone(), button_id.clone());
470
cx.global::<AppHandle>().0.clone().update(cx, |state, cx| {
471
state.run_card_action(scope, button_id, action, cx)
472
});
473
})
474
}
475
CardActionKind::ShowCard(_) => {
476
let actions_id = actions_id.to_owned();
477
enabled.on_click(move |_, _, cx| {
478
cx.stop_propagation();
479
let (scope, actions_id) = (scope.clone(), actions_id.clone());
480
cx.global::<AppHandle>().0.clone().update(cx, |state, cx| {
481
state.toggle_show_card(&scope, &actions_id, index, cx)
482
});
483
})
484
}
485
CardActionKind::ToggleVisibility(targets) => {
486
let elements: Vec<(String, bool, Option<bool>)> = targets
487
.iter()
488
.map(|target| {
489
let initial = context
490
.initial_visibility
491
.get(&target.element_id)
492
.copied()
493
.unwrap_or(true);
494
(target.element_id.clone(), initial, target.visible)
329
495
})
496
.collect();
497
let root_key = context.root_key.clone();
498
enabled.on_click(move |_, _, cx| {
499
cx.stop_propagation();
500
let (scope, root_key, elements) =
501
(scope.clone(), root_key.clone(), elements.clone());
502
cx.global::<AppHandle>().0.clone().update(cx, |state, cx| {
503
state.toggle_card_elements(&scope, &root_key, elements, cx)
504
});
505
})
330
506
}
331
CardActionKind::Unsupported => button
332
.text_color(theme::text_muted())
333
.opacity(ACTION_DISABLED_OPACITY)
334
.tooltip(|window, cx| Tooltip::new(ACTION_DISABLED_TOOLTIP).build(window, cx))
335
.on_click(|_, _, cx| cx.stop_propagation()),
507
CardActionKind::Unsupported => enabled,
508
}
509
}
510
511
fn failure_reason(phase: &Option<ActionPhase>) -> Option<String> {
512
match phase {
513
Some(ActionPhase::Failed(reason)) => Some(reason.clone()),
514
_ => None,
515
}
516
}
517
518
fn action_label(action: &CardAction, phase: &Option<ActionPhase>, open: bool) -> AnyElement {
519
match phase {
520
Some(ActionPhase::Busy) => format!("{}...", action.title).into_any_element(),
521
Some(ActionPhase::Done) => h_flex()
522
.gap(px(ACTION_ICON_GAP))
523
.items_center()
524
.child(symbol("done", ACTION_CHECK_SIZE, theme::green()))
525
.child(action.title.clone())
526
.into_any_element(),
527
_ if open => format!("{} ^", action.title).into_any_element(),
528
_ => action.title.clone().into_any_element(),
336
529
}
337
530
}
@@ -1,3 +1,5 @@1
use std::collections::HashMap;2
1
use gpui_kit::component::{h_flex, tooltip::Tooltip, v_flex};3
use gpui_kit::component::{h_flex, tooltip::Tooltip, v_flex};2
use gpui_kit::prelude::FluentBuilder as _;4
use gpui_kit::prelude::FluentBuilder as _;3
use gpui_kit::*;5
use gpui_kit::*;@@ -7,6 +9,9 @@ use teams_core::{7
VerticalAlignment,9
VerticalAlignment,8
};10
};9
11
12
use super::widgets::symbol;13
use crate::app_state::AppHandle;14
use crate::card_state::{ActionPhase, CardScope, CardState};10
use crate::render::{layout_blocks, render_blocks};15
use crate::render::{layout_blocks, render_blocks};11
use crate::theme;16
use crate::theme;12
17
@@ -22,6 +27,10 @@ const ACTION_RADIUS: f32 = 6.;22
const ACTION_TEXT_SIZE: f32 = 13.;27
const ACTION_TEXT_SIZE: f32 = 13.;23
const ACTION_DISABLED_OPACITY: f32 = 0.5;28
const ACTION_DISABLED_OPACITY: f32 = 0.5;24
const ACTION_DISABLED_TOOLTIP: &str = "Not supported in this app";29
const ACTION_DISABLED_TOOLTIP: &str = "Not supported in this app";30
const ACTION_BUSY_OPACITY: f32 = 0.6;31
const ACTION_CHECK_SIZE: f32 = 14.;32
const ACTION_ICON_GAP: f32 = 4.;33
const NOTE_TEXT_SIZE: f32 = 12.;25
const FACT_TITLE_WIDTH: f32 = 96.;34
const FACT_TITLE_WIDTH: f32 = 96.;26
const FACT_GAP: f32 = 2.;35
const FACT_GAP: f32 = 2.;27
const CONTAINER_PADDING: f32 = 8.;36
const CONTAINER_PADDING: f32 = 8.;@@ -35,20 +44,64 @@ const MEDIUM_IMAGE: f32 = 80.;35
const LARGE_IMAGE: f32 = 160.;44
const LARGE_IMAGE: f32 = 160.;36
const EXTERNAL_IMAGE_SCHEME: &str = "https://";45
const EXTERNAL_IMAGE_SCHEME: &str = "https://";37
46
38
pub fn cards_view(cards: &[AdaptiveCard], id: &str, cx: &App) -> Vec<AnyElement> {47
struct CardContext<'a> {48
cx: &'a App,49
scope: &'a CardScope,50
state: &'a CardState,51
root_key: String,52
initial_visibility: HashMap<String, bool>,53
}54
55
impl<'a> CardContext<'a> {56
fn new(card: &AdaptiveCard, scope: &'a CardScope, cx: &'a App) -> Self {57
CardContext {58
cx,59
scope,60
state: &cx.global::<AppHandle>().0.read(cx).cards,61
root_key: scope.card_key(),62
initial_visibility: card.element_visibility(),63
}64
}65
66
fn visible(&self, id: Option<&String>, initial: bool) -> bool {67
match id {68
Some(id) => self69
.state70
.is_visible(&format!("{}/{id}", self.root_key), initial),71
None => initial,72
}73
}74
}75
76
pub fn cards_view(77
cards: &[AdaptiveCard],78
conversation_id: &str,79
message_id: &str,80
cx: &App,81
) -> Vec<AnyElement> {39
cards82
cards40
.iter()83
.iter()41
.enumerate()84
.enumerate()42
.map(|(index, card)| card_view(card, &format!("{id}-card-{index}"), cx))85
.map(|(index, card)| {86
let scope = CardScope::message(conversation_id, message_id, index);87
card_view(card, &scope, cx)88
})43
.collect()89
.collect()44
}90
}45
91
46
fn card_view(card: &AdaptiveCard, id: &str, cx: &App) -> AnyElement {92
pub fn card_view(card: &AdaptiveCard, scope: &CardScope, cx: &App) -> AnyElement {93
let context = CardContext::new(card, scope, cx);94
let id = scope.card_key();47
let width = if card.full_width {95
let width = if card.full_width {48
CARD_FULL_WIDTH96
CARD_FULL_WIDTH49
} else {97
} else {50
CARD_WIDTH98
CARD_WIDTH51
};99
};100
let note = context.state.note(&id).map(str::to_owned);101
let visible_actions = card102
.actions103
.iter()104
.any(|action| context.visible(action.id.as_ref(), action.visible));52
v_flex()105
v_flex()53
.w(px(width))106
.w(px(width))54
.max_w(relative(1.))107
.max_w(relative(1.))@@ -58,35 +111,50 @@ fn card_view(card: &AdaptiveCard, id: &str, cx: &App) -> AnyElement {58
.border(px(CARD_BORDER_WIDTH))111
.border(px(CARD_BORDER_WIDTH))59
.border_color(theme::border())112
.border_color(theme::border())60
.text_color(theme::text_strong())113
.text_color(theme::text_strong())61
.child(items_view(&card.items, id, cx))114
.child(items_view(&card.items, &id, &context))62
.when(!card.actions.is_empty(), |card_element| {115
.when(visible_actions, |card_element| {116
card_element.child(div().mt(px(spacing_pixels(CardSpacing::Default))).child(117
actions_view(&card.actions, &format!("{id}-actions"), &context),118
))119
})120
.when_some(note, |card_element, note| {63
card_element.child(121
card_element.child(64
div()122
div()65
.mt(px(spacing_pixels(CardSpacing::Default)))123
.mt(px(spacing_pixels(CardSpacing::Default)))66
.child(actions_view(&card.actions, &format!("{id}-actions"))),124
.text_size(px(NOTE_TEXT_SIZE))125
.text_color(theme::text_muted())126
.child(note),67
)127
)68
})128
})69
.into_any_element()129
.into_any_element()70
}130
}71
131
72
fn items_view(items: &[CardItem], id: &str, cx: &App) -> Div {132
fn items_view(items: &[CardItem], id: &str, context: &CardContext) -> Div {73
v_flex()133
let mut shown = 0;74
.w_full()134
let mut column = v_flex().w_full();75
.children(items.iter().enumerate().map(|(index, item)| {135
for (index, item) in items.iter().enumerate() {76
let item_id = format!("{id}-{index}");136
if !context.visible(item.id.as_ref(), item.visible) {137
continue;138
}139
let item_id = format!("{id}-{index}");140
let first = shown == 0;141
shown += 1;142
column = column.child(77
div()143
div()78
.w_full()144
.w_full()79
.when(index > 0, |wrapper| {145
.when(!first, |wrapper| {80
wrapper.mt(px(spacing_pixels(item.spacing)))146
wrapper.mt(px(spacing_pixels(item.spacing)))81
})147
})82
.when(index > 0 && item.separator, |wrapper| {148
.when(!first && item.separator, |wrapper| {83
wrapper149
wrapper84
.pt(px(SEPARATOR_PADDING))150
.pt(px(SEPARATOR_PADDING))85
.border_t_1()151
.border_t_1()86
.border_color(theme::border())152
.border_color(theme::border())87
})153
})88
.child(element_view(&item.element, &item_id, cx))154
.child(element_view(&item.element, &item_id, context)),89
}))155
);156
}157
column90
}158
}91
159
92
fn spacing_pixels(spacing: CardSpacing) -> f32 {160
fn spacing_pixels(spacing: CardSpacing) -> f32 {@@ -100,9 +168,9 @@ fn spacing_pixels(spacing: CardSpacing) -> f32 {100
}168
}101
}169
}102
170
103
fn element_view(element: &CardElement, id: &str, cx: &App) -> AnyElement {171
fn element_view(element: &CardElement, id: &str, context: &CardContext) -> AnyElement {104
match element {172
match element {105
CardElement::Text(text) => text_view(text, id, cx),173
CardElement::Text(text) => text_view(text, id, context.cx),106
CardElement::Image(image) => image_view(image, id),174
CardElement::Image(image) => image_view(image, id),107
CardElement::ImageSet(images) => h_flex()175
CardElement::ImageSet(images) => h_flex()108
.flex_wrap()176
.flex_wrap()@@ -114,10 +182,10 @@ fn element_view(element: &CardElement, id: &str, cx: &App) -> AnyElement {114
.map(|(index, image)| image_view(image, &format!("{id}-{index}"))),182
.map(|(index, image)| image_view(image, &format!("{id}-{index}"))),115
)183
)116
.into_any_element(),184
.into_any_element(),117
CardElement::Columns(columns) => columns_view(columns, id, cx),185
CardElement::Columns(columns) => columns_view(columns, id, context),118
CardElement::Container { style, items } => {186
CardElement::Container { style, items } => {119
let tint = container_tint(*style);187
let tint = container_tint(*style);120
items_view(items, id, cx)188
items_view(items, id, context)121
.when_some(tint, |container, tint| {189
.when_some(tint, |container, tint| {122
container190
container123
.p(px(CONTAINER_PADDING))191
.p(px(CONTAINER_PADDING))@@ -126,8 +194,8 @@ fn element_view(element: &CardElement, id: &str, cx: &App) -> AnyElement {126
})194
})127
.into_any_element()195
.into_any_element()128
}196
}129
CardElement::Facts(facts) => facts_view(facts, id, cx),197
CardElement::Facts(facts) => facts_view(facts, id, context.cx),130
CardElement::Actions(actions) => actions_view(actions, id).into_any_element(),198
CardElement::Actions(actions) => actions_view(actions, id, context).into_any_element(),131
}199
}132
}200
}133
201
@@ -208,7 +276,7 @@ fn facts_view(facts: &[CardFact], id: &str, cx: &App) -> AnyElement {208
.into_any_element()276
.into_any_element()209
}277
}210
278
211
fn columns_view(columns: &[CardColumn], id: &str, cx: &App) -> AnyElement {279
fn columns_view(columns: &[CardColumn], id: &str, context: &CardContext) -> AnyElement {212
div()280
div()213
.flex()281
.flex()214
.flex_row()282
.flex_row()@@ -216,7 +284,7 @@ fn columns_view(columns: &[CardColumn], id: &str, cx: &App) -> AnyElement {216
.w_full()284
.w_full()217
.gap(px(COLUMN_GAP))285
.gap(px(COLUMN_GAP))218
.children(columns.iter().enumerate().map(|(index, column)| {286
.children(columns.iter().enumerate().map(|(index, column)| {219
let content = items_view(&column.items, &format!("{id}-{index}"), cx);287
let content = items_view(&column.items, &format!("{id}-{index}"), context);220
let aligned = v_flex()288
let aligned = v_flex()221
.h_full()289
.h_full()222
.map(|aligned| match column.vertical_alignment {290
.map(|aligned| match column.vertical_alignment {@@ -296,42 +364,167 @@ fn named_image_width(size: ImageSize) -> Option<f32> {296
}364
}297
}365
}298
366
299
fn actions_view(actions: &[CardAction], id: &str) -> Div {367
fn actions_view(actions: &[CardAction], id: &str, context: &CardContext) -> Div {300
h_flex().w_full().flex_wrap().gap(px(ACTION_GAP)).children(368
let open_card = context301
actions369
.state302
.iter()370
.open_card(id)303
.enumerate()371
.and_then(|index| actions.get(index))304
.map(|(index, action)| action_button(action, format!("{id}-{index}"))),372
.and_then(|action| match &action.kind {305
)373
CardActionKind::ShowCard(card) => Some(card),374
_ => None,375
});376
v_flex()377
.w_full()378
.gap(px(ACTION_GAP))379
.child(380
h_flex().w_full().flex_wrap().gap(px(ACTION_GAP)).children(381
actions382
.iter()383
.enumerate()384
.filter(|(_, action)| context.visible(action.id.as_ref(), action.visible))385
.map(|(index, action)| action_button(action, index, id, context)),386
),387
)388
.when_some(open_card, |column, card| {389
let nested_id = format!("{id}-show");390
column.child(391
v_flex()392
.w_full()393
.p(px(CONTAINER_PADDING))394
.gap(px(ACTION_GAP))395
.rounded(px(CONTAINER_RADIUS))396
.bg(theme::surface_raised())397
.child(items_view(&card.items, &nested_id, context))398
.when(!card.actions.is_empty(), |nested| {399
nested.child(actions_view(400
&card.actions,401
&format!("{nested_id}-actions"),402
context,403
))404
}),405
)406
})306
}407
}307
408
308
fn action_button(action: &CardAction, id: String) -> Stateful<Div> {409
fn action_button(410
action: &CardAction,411
index: usize,412
actions_id: &str,413
context: &CardContext,414
) -> Stateful<Div> {415
let button_id = format!("{actions_id}-{index}");416
let phase = context.state.phase(&button_id).cloned();417
let label = action_label(418
action,419
&phase,420
context.state.open_card(actions_id) == Some(index),421
);309
let button = div()422
let button = div()310
.id(ElementId::Name(id.into()))423
.id(ElementId::Name(button_id.clone().into()))311
.px(px(12.))424
.px(px(12.))312
.py(px(6.))425
.py(px(6.))313
.rounded(px(ACTION_RADIUS))426
.rounded(px(ACTION_RADIUS))314
.border_1()427
.border_1()315
.border_color(theme::border_strong())428
.border_color(match phase {429
Some(ActionPhase::Failed(_)) => theme::red(),430
_ => theme::border_strong(),431
})316
.text_size(px(ACTION_TEXT_SIZE))432
.text_size(px(ACTION_TEXT_SIZE))317
.font_weight(FontWeight::SEMIBOLD)433
.font_weight(FontWeight::SEMIBOLD)318
.child(action.title.clone());434
.child(label);435
if !action.is_clickable() {436
return button437
.text_color(theme::text_muted())438
.opacity(ACTION_DISABLED_OPACITY)439
.when(action.enabled, |button| {440
button.tooltip(|window, cx| Tooltip::new(ACTION_DISABLED_TOOLTIP).build(window, cx))441
})442
.on_click(|_, _, cx| cx.stop_propagation());443
}444
let enabled = button.text_color(theme::accent_text());445
if phase == Some(ActionPhase::Busy) {446
return enabled447
.opacity(ACTION_BUSY_OPACITY)448
.on_click(|_, _, cx| cx.stop_propagation());449
}450
let enabled = enabled451
.cursor_pointer()452
.hover(|button| button.bg(theme::row_hover()))453
.when_some(failure_reason(&phase), |button, reason| {454
button.tooltip(move |window, cx| Tooltip::new(reason.clone()).build(window, cx))455
});456
let scope = context.scope.clone();319
match &action.kind {457
match &action.kind {320
CardActionKind::OpenUrl(url) => {458
CardActionKind::OpenUrl(url) => {321
let url = url.clone();459
let url = url.clone();322
button460
enabled.on_click(move |_, _, cx| {323
.text_color(theme::accent_text())461
cx.stop_propagation();324
.cursor_pointer()462
cx.open_url(&url);325
.hover(|button| button.bg(theme::row_hover()))463
})326
.on_click(move |_, _, cx| {464
}327
cx.stop_propagation();465
CardActionKind::Submit(_) | CardActionKind::Execute(_) => {328
cx.open_url(&url);466
let action = action.clone();467
enabled.on_click(move |_, _, cx| {468
cx.stop_propagation();469
let (scope, action, button_id) = (scope.clone(), action.clone(), button_id.clone());470
cx.global::<AppHandle>().0.clone().update(cx, |state, cx| {471
state.run_card_action(scope, button_id, action, cx)472
});473
})474
}475
CardActionKind::ShowCard(_) => {476
let actions_id = actions_id.to_owned();477
enabled.on_click(move |_, _, cx| {478
cx.stop_propagation();479
let (scope, actions_id) = (scope.clone(), actions_id.clone());480
cx.global::<AppHandle>().0.clone().update(cx, |state, cx| {481
state.toggle_show_card(&scope, &actions_id, index, cx)482
});483
})484
}485
CardActionKind::ToggleVisibility(targets) => {486
let elements: Vec<(String, bool, Option<bool>)> = targets487
.iter()488
.map(|target| {489
let initial = context490
.initial_visibility491
.get(&target.element_id)492
.copied()493
.unwrap_or(true);494
(target.element_id.clone(), initial, target.visible)329
})495
})496
.collect();497
let root_key = context.root_key.clone();498
enabled.on_click(move |_, _, cx| {499
cx.stop_propagation();500
let (scope, root_key, elements) =501
(scope.clone(), root_key.clone(), elements.clone());502
cx.global::<AppHandle>().0.clone().update(cx, |state, cx| {503
state.toggle_card_elements(&scope, &root_key, elements, cx)504
});505
})330
}506
}331
CardActionKind::Unsupported => button507
CardActionKind::Unsupported => enabled,332
.text_color(theme::text_muted())508
}333
.opacity(ACTION_DISABLED_OPACITY)509
}334
.tooltip(|window, cx| Tooltip::new(ACTION_DISABLED_TOOLTIP).build(window, cx))510
335
.on_click(|_, _, cx| cx.stop_propagation()),511
fn failure_reason(phase: &Option<ActionPhase>) -> Option<String> {512
match phase {513
Some(ActionPhase::Failed(reason)) => Some(reason.clone()),514
_ => None,515
}516
}517
518
fn action_label(action: &CardAction, phase: &Option<ActionPhase>, open: bool) -> AnyElement {519
match phase {520
Some(ActionPhase::Busy) => format!("{}...", action.title).into_any_element(),521
Some(ActionPhase::Done) => h_flex()522
.gap(px(ACTION_ICON_GAP))523
.items_center()524
.child(symbol("done", ACTION_CHECK_SIZE, theme::green()))525
.child(action.title.clone())526
.into_any_element(),527
_ if open => format!("{} ^", action.title).into_any_element(),528
_ => action.title.clone().into_any_element(),336
}529
}337
}530
}@@ -5,6 +5,7 @@ use std::time::Duration;
5
5
6
6
use gpui_kit::assets::IconName;
7
7
8
use crate::card_state::BotIdentity;
8
9
use crate::data::{AvatarState, Directory, Presence, PresenceKind};
9
10
use crate::format;
10
11
use crate::sidebar_model::{AvatarSpec, Face};
@@ -87,6 +88,29 @@ pub fn person_avatar(
87
88
face_circle(directory, &face, size, INITIALS_RATIO)
88
89
}
89
90
91
pub fn bot_avatar(identity: &BotIdentity, size: f32) -> AnyElement {
92
let initials = {
93
let name = identity.name.clone();
94
move || initials_circle(&name, &name, size, false, INITIALS_RATIO).into_any_element()
95
};
96
match &identity.icon_url {
97
Some(url) => div()
98
.size(px(size))
99
.flex_none()
100
.rounded_full()
101
.overflow_hidden()
102
.child(
103
img(url.clone())
104
.size_full()
105
.object_fit(ObjectFit::Cover)
106
.with_loading(initials.clone())
107
.with_fallback(initials),
108
)
109
.into_any_element(),
110
None => initials(),
111
}
112
}
113
90
114
pub fn presence_size(avatar_size: f32) -> f32 {
91
115
(avatar_size * PRESENCE_RATIO)
92
116
.round()
@@ -5,6 +5,7 @@ use std::time::Duration;5
5
6
use gpui_kit::assets::IconName;6
use gpui_kit::assets::IconName;7
7
8
use crate::card_state::BotIdentity;8
use crate::data::{AvatarState, Directory, Presence, PresenceKind};9
use crate::data::{AvatarState, Directory, Presence, PresenceKind};9
use crate::format;10
use crate::format;10
use crate::sidebar_model::{AvatarSpec, Face};11
use crate::sidebar_model::{AvatarSpec, Face};@@ -87,6 +88,29 @@ pub fn person_avatar(87
face_circle(directory, &face, size, INITIALS_RATIO)88
face_circle(directory, &face, size, INITIALS_RATIO)88
}89
}89
90
91
pub fn bot_avatar(identity: &BotIdentity, size: f32) -> AnyElement {92
let initials = {93
let name = identity.name.clone();94
move || initials_circle(&name, &name, size, false, INITIALS_RATIO).into_any_element()95
};96
match &identity.icon_url {97
Some(url) => div()98
.size(px(size))99
.flex_none()100
.rounded_full()101
.overflow_hidden()102
.child(103
img(url.clone())104
.size_full()105
.object_fit(ObjectFit::Cover)106
.with_loading(initials.clone())107
.with_fallback(initials),108
)109
.into_any_element(),110
None => initials(),111
}112
}113
90
pub fn presence_size(avatar_size: f32) -> f32 {114
pub fn presence_size(avatar_size: f32) -> f32 {91
(avatar_size * PRESENCE_RATIO)115
(avatar_size * PRESENCE_RATIO)92
.round()116
.round()@@ -441,6 +441,7 @@ impl ConversationView {
441
441
}
442
442
}
443
443
AppEvent::Images(keys) => self.remeasure_images(keys, cx),
444
AppEvent::Cards(conversation_id) => self.refresh_cards(conversation_id, cx),
444
445
AppEvent::Jump => self.apply_pending_jump(cx),
445
446
AppEvent::Status => {
446
447
if let Some(current) = self.current.as_mut()
@@ -454,6 +455,7 @@ impl ConversationView {
454
455
self.refresh_reactor_names(cx);
455
456
cx.notify();
456
457
}
458
AppEvent::TaskDialog => {}
457
459
AppEvent::Sidebar => {
458
460
self.mark_read(ReadTrigger::Incoming, cx);
459
461
self.refresh_reactor_names(cx);
@@ -663,6 +665,33 @@ impl ConversationView {
663
665
cx.notify();
664
666
}
665
667
668
fn refresh_cards(&mut self, conversation_id: &str, cx: &mut Context<Self>) {
669
let is_current = self
670
.current
671
.as_ref()
672
.is_some_and(|current| current.selection.conversation_id() == conversation_id);
673
if !is_current {
674
return;
675
}
676
self.rebuild(false, cx);
677
let indices: Vec<usize> = self
678
.rows
679
.borrow()
680
.iter()
681
.enumerate()
682
.filter_map(|(index, row)| match row {
683
Row::Message(message) if !message.adaptive_cards.is_empty() => Some(index),
684
_ => None,
685
})
686
.collect();
687
self.scroller.update(cx, |scroller, cx| {
688
for index in indices {
689
scroller.remeasure_items(index..index + 1, cx);
690
}
691
});
692
cx.notify();
693
}
694
666
695
fn apply_pending_jump(&mut self, cx: &mut Context<Self>) {
667
696
let Some(conversation_id) = self
668
697
.current
@@ -841,12 +870,18 @@ impl ConversationView {
841
870
for (user_id, name) in known_people {
842
871
names.entry(user_id).or_insert(name);
843
872
}
873
let card_overrides = self
874
.current
875
.as_ref()
876
.map(|current| app.cards.overrides_for(current.selection.conversation_id()))
877
.unwrap_or_default();
844
878
RowContext {
845
879
offset: now.offset().fix(),
846
880
today: now.date_naive(),
847
881
my_user_id: app.store.meta(META_USER_ID).ok().flatten(),
848
882
names,
849
883
pending_reactions: self.pending_reactions.clone(),
884
card_overrides,
850
885
}
851
886
}
852
887
@@ -1603,10 +1638,17 @@ impl ConversationView {
1603
1638
let key = format!("{PENDING_KEY_PREFIX}{}", self.pending_counter);
1604
1639
let my_user_id = self.row_context(cx).my_user_id;
1605
1640
self.pending_outgoing.insert(key.clone(), outgoing.clone());
1641
let conversation_id = self
1642
.current
1643
.as_ref()
1644
.map(|current| current.selection.conversation_id().to_owned())
1645
.unwrap_or_default();
1606
1646
self.pending.push(MessageRow {
1607
1647
key: key.clone(),
1648
conversation_id,
1608
1649
author: "You".to_owned(),
1609
1650
sender_id: my_user_id,
1651
application_id: None,
1610
1652
created_at: Utc::now(),
1611
1653
series: Series::default(),
1612
1654
card: false,
@@ -2651,11 +2693,30 @@ impl Render for ConversationView {
2651
2693
view.clone(),
2652
2694
)
2653
2695
});
2696
let bot = message
2697
.application_id
2698
.as_deref()
2699
.and_then(|application_id| {
2700
let known = app
2701
.read(cx)
2702
.bot_identity(&message.conversation_id, application_id);
2703
if known.is_none() {
2704
let (app, conversation_id) =
2705
(app.clone(), message.conversation_id.clone());
2706
cx.defer(move |cx| {
2707
app.update(cx, |state, cx| {
2708
state.request_chat_apps(&conversation_id, cx)
2709
});
2710
});
2711
}
2712
known
2713
});
2654
2714
let state = app.read(cx);
2655
2715
render_message_row(
2656
2716
message,
2657
2717
index,
2658
2718
RowActions {
2719
bot,
2659
2720
open_thread,
2660
2721
retry,
2661
2722
reply,
@@ -441,6 +441,7 @@ impl ConversationView {441
}441
}442
}442
}443
AppEvent::Images(keys) => self.remeasure_images(keys, cx),443
AppEvent::Images(keys) => self.remeasure_images(keys, cx),444
AppEvent::Cards(conversation_id) => self.refresh_cards(conversation_id, cx),444
AppEvent::Jump => self.apply_pending_jump(cx),445
AppEvent::Jump => self.apply_pending_jump(cx),445
AppEvent::Status => {446
AppEvent::Status => {446
if let Some(current) = self.current.as_mut()447
if let Some(current) = self.current.as_mut()@@ -454,6 +455,7 @@ impl ConversationView {454
self.refresh_reactor_names(cx);455
self.refresh_reactor_names(cx);455
cx.notify();456
cx.notify();456
}457
}458
AppEvent::TaskDialog => {}457
AppEvent::Sidebar => {459
AppEvent::Sidebar => {458
self.mark_read(ReadTrigger::Incoming, cx);460
self.mark_read(ReadTrigger::Incoming, cx);459
self.refresh_reactor_names(cx);461
self.refresh_reactor_names(cx);@@ -663,6 +665,33 @@ impl ConversationView {663
cx.notify();665
cx.notify();664
}666
}665
667
668
fn refresh_cards(&mut self, conversation_id: &str, cx: &mut Context<Self>) {669
let is_current = self670
.current671
.as_ref()672
.is_some_and(|current| current.selection.conversation_id() == conversation_id);673
if !is_current {674
return;675
}676
self.rebuild(false, cx);677
let indices: Vec<usize> = self678
.rows679
.borrow()680
.iter()681
.enumerate()682
.filter_map(|(index, row)| match row {683
Row::Message(message) if !message.adaptive_cards.is_empty() => Some(index),684
_ => None,685
})686
.collect();687
self.scroller.update(cx, |scroller, cx| {688
for index in indices {689
scroller.remeasure_items(index..index + 1, cx);690
}691
});692
cx.notify();693
}694
666
fn apply_pending_jump(&mut self, cx: &mut Context<Self>) {695
fn apply_pending_jump(&mut self, cx: &mut Context<Self>) {667
let Some(conversation_id) = self696
let Some(conversation_id) = self668
.current697
.current@@ -841,12 +870,18 @@ impl ConversationView {841
for (user_id, name) in known_people {870
for (user_id, name) in known_people {842
names.entry(user_id).or_insert(name);871
names.entry(user_id).or_insert(name);843
}872
}873
let card_overrides = self874
.current875
.as_ref()876
.map(|current| app.cards.overrides_for(current.selection.conversation_id()))877
.unwrap_or_default();844
RowContext {878
RowContext {845
offset: now.offset().fix(),879
offset: now.offset().fix(),846
today: now.date_naive(),880
today: now.date_naive(),847
my_user_id: app.store.meta(META_USER_ID).ok().flatten(),881
my_user_id: app.store.meta(META_USER_ID).ok().flatten(),848
names,882
names,849
pending_reactions: self.pending_reactions.clone(),883
pending_reactions: self.pending_reactions.clone(),884
card_overrides,850
}885
}851
}886
}852
887
@@ -1603,10 +1638,17 @@ impl ConversationView {1603
let key = format!("{PENDING_KEY_PREFIX}{}", self.pending_counter);1638
let key = format!("{PENDING_KEY_PREFIX}{}", self.pending_counter);1604
let my_user_id = self.row_context(cx).my_user_id;1639
let my_user_id = self.row_context(cx).my_user_id;1605
self.pending_outgoing.insert(key.clone(), outgoing.clone());1640
self.pending_outgoing.insert(key.clone(), outgoing.clone());1641
let conversation_id = self1642
.current1643
.as_ref()1644
.map(|current| current.selection.conversation_id().to_owned())1645
.unwrap_or_default();1606
self.pending.push(MessageRow {1646
self.pending.push(MessageRow {1607
key: key.clone(),1647
key: key.clone(),1648
conversation_id,1608
author: "You".to_owned(),1649
author: "You".to_owned(),1609
sender_id: my_user_id,1650
sender_id: my_user_id,1651
application_id: None,1610
created_at: Utc::now(),1652
created_at: Utc::now(),1611
series: Series::default(),1653
series: Series::default(),1612
card: false,1654
card: false,@@ -2651,11 +2693,30 @@ impl Render for ConversationView {2651
view.clone(),2693
view.clone(),2652
)2694
)2653
});2695
});2696
let bot = message2697
.application_id2698
.as_deref()2699
.and_then(|application_id| {2700
let known = app2701
.read(cx)2702
.bot_identity(&message.conversation_id, application_id);2703
if known.is_none() {2704
let (app, conversation_id) =2705
(app.clone(), message.conversation_id.clone());2706
cx.defer(move |cx| {2707
app.update(cx, |state, cx| {2708
state.request_chat_apps(&conversation_id, cx)2709
});2710
});2711
}2712
known2713
});2654
let state = app.read(cx);2714
let state = app.read(cx);2655
render_message_row(2715
render_message_row(2656
message,2716
message,2657
index,2717
index,2658
RowActions {2718
RowActions {2719
bot,2659
open_thread,2720
open_thread,2660
retry,2721
retry,2661
reply,2722
reply,@@ -0,0 +1,108 @@
1
use gpui_kit::component::{h_flex, v_flex};
2
use gpui_kit::*;
3
4
use super::adaptive_card::card_view;
5
use super::widgets::symbol;
6
use crate::app_state::{AppHandle, AppState};
7
use crate::card_state::TaskDialogState;
8
use crate::theme;
9
10
const BACKDROP_OPACITY: f32 = 0.55;
11
const PANEL_MARGIN: f32 = 32.;
12
const PANEL_RADIUS: f32 = 12.;
13
const PANEL_PADDING: f32 = 16.;
14
const HEADER_GAP: f32 = 12.;
15
const TITLE_SIZE: f32 = 15.;
16
const CLOSE_SIZE: f32 = 28.;
17
const CLOSE_ICON_SIZE: f32 = 16.;
18
const MIN_WIDTH: f32 = 360.;
19
const CARD_CHROME: f32 = 2. * 12. + 2.;
20
21
pub fn render_task_dialog(state: &AppState, cx: &App) -> Option<AnyElement> {
22
let dialog = state.task_dialog.as_ref()?;
23
Some(
24
div()
25
.id("task-dialog-layer")
26
.absolute()
27
.top_0()
28
.left_0()
29
.size_full()
30
.flex()
31
.items_center()
32
.justify_center()
33
.child(
34
div()
35
.id("task-dialog-backdrop")
36
.absolute()
37
.top_0()
38
.left_0()
39
.size_full()
40
.bg(black().opacity(BACKDROP_OPACITY))
41
.occlude()
42
.on_click(|_, _, cx| close(cx)),
43
)
44
.child(panel(dialog, cx))
45
.into_any_element(),
46
)
47
}
48
49
fn panel(dialog: &TaskDialogState, cx: &App) -> Div {
50
let width = (dialog.width as f32 + CARD_CHROME).max(MIN_WIDTH);
51
v_flex()
52
.w(px(width))
53
.max_w(relative(1.))
54
.max_h(relative(1.))
55
.m(px(PANEL_MARGIN))
56
.p(px(PANEL_PADDING))
57
.gap(px(HEADER_GAP))
58
.rounded(px(PANEL_RADIUS))
59
.bg(theme::background())
60
.border_1()
61
.border_color(theme::border_strong())
62
.text_color(theme::text())
63
.occlude()
64
.child(
65
h_flex()
66
.w_full()
67
.items_center()
68
.gap(px(HEADER_GAP))
69
.child(
70
div()
71
.flex_1()
72
.min_w(px(0.))
73
.text_size(px(TITLE_SIZE))
74
.font_weight(FontWeight::SEMIBOLD)
75
.child(dialog.title.clone()),
76
)
77
.child(
78
div()
79
.id("task-dialog-close")
80
.size(px(CLOSE_SIZE))
81
.flex_none()
82
.flex()
83
.items_center()
84
.justify_center()
85
.rounded_full()
86
.cursor_pointer()
87
.hover(|button| button.bg(theme::row_hover()))
88
.on_click(|_, _, cx| close(cx))
89
.child(symbol("close", CLOSE_ICON_SIZE, theme::text_muted())),
90
),
91
)
92
.child(
93
div()
94
.id("task-dialog-body")
95
.w_full()
96
.flex_1()
97
.min_h(px(0.))
98
.overflow_y_scroll()
99
.child(card_view(&dialog.card, &dialog.scope, cx)),
100
)
101
}
102
103
fn close(cx: &mut App) {
104
cx.global::<AppHandle>()
105
.0
106
.clone()
107
.update(cx, |state, cx| state.close_task_dialog(cx));
108
}
@@ -0,0 +1,108 @@1
use gpui_kit::component::{h_flex, v_flex};2
use gpui_kit::*;3
4
use super::adaptive_card::card_view;5
use super::widgets::symbol;6
use crate::app_state::{AppHandle, AppState};7
use crate::card_state::TaskDialogState;8
use crate::theme;9
10
const BACKDROP_OPACITY: f32 = 0.55;11
const PANEL_MARGIN: f32 = 32.;12
const PANEL_RADIUS: f32 = 12.;13
const PANEL_PADDING: f32 = 16.;14
const HEADER_GAP: f32 = 12.;15
const TITLE_SIZE: f32 = 15.;16
const CLOSE_SIZE: f32 = 28.;17
const CLOSE_ICON_SIZE: f32 = 16.;18
const MIN_WIDTH: f32 = 360.;19
const CARD_CHROME: f32 = 2. * 12. + 2.;20
21
pub fn render_task_dialog(state: &AppState, cx: &App) -> Option<AnyElement> {22
let dialog = state.task_dialog.as_ref()?;23
Some(24
div()25
.id("task-dialog-layer")26
.absolute()27
.top_0()28
.left_0()29
.size_full()30
.flex()31
.items_center()32
.justify_center()33
.child(34
div()35
.id("task-dialog-backdrop")36
.absolute()37
.top_0()38
.left_0()39
.size_full()40
.bg(black().opacity(BACKDROP_OPACITY))41
.occlude()42
.on_click(|_, _, cx| close(cx)),43
)44
.child(panel(dialog, cx))45
.into_any_element(),46
)47
}48
49
fn panel(dialog: &TaskDialogState, cx: &App) -> Div {50
let width = (dialog.width as f32 + CARD_CHROME).max(MIN_WIDTH);51
v_flex()52
.w(px(width))53
.max_w(relative(1.))54
.max_h(relative(1.))55
.m(px(PANEL_MARGIN))56
.p(px(PANEL_PADDING))57
.gap(px(HEADER_GAP))58
.rounded(px(PANEL_RADIUS))59
.bg(theme::background())60
.border_1()61
.border_color(theme::border_strong())62
.text_color(theme::text())63
.occlude()64
.child(65
h_flex()66
.w_full()67
.items_center()68
.gap(px(HEADER_GAP))69
.child(70
div()71
.flex_1()72
.min_w(px(0.))73
.text_size(px(TITLE_SIZE))74
.font_weight(FontWeight::SEMIBOLD)75
.child(dialog.title.clone()),76
)77
.child(78
div()79
.id("task-dialog-close")80
.size(px(CLOSE_SIZE))81
.flex_none()82
.flex()83
.items_center()84
.justify_center()85
.rounded_full()86
.cursor_pointer()87
.hover(|button| button.bg(theme::row_hover()))88
.on_click(|_, _, cx| close(cx))89
.child(symbol("close", CLOSE_ICON_SIZE, theme::text_muted())),90
),91
)92
.child(93
div()94
.id("task-dialog-body")95
.w_full()96
.flex_1()97
.min_h(px(0.))98
.overflow_y_scroll()99
.child(card_view(&dialog.card, &dialog.scope, cx)),100
)101
}102
103
fn close(cx: &mut App) {104
cx.global::<AppHandle>()105
.0106
.clone()107
.update(cx, |state, cx| state.close_task_dialog(cx));108
}@@ -7,11 +7,12 @@ use std::time::Duration;
7
7
8
8
use super::adaptive_card::cards_view;
9
9
use super::attachments::{FileActions, attachments_view, message_body};
10
use super::avatar::{member_stack, person_avatar};
10
use super::avatar::{bot_avatar, member_stack, person_avatar};
11
11
use super::message_actions::{HoverChange, MessageMenu, message_toolbar};
12
12
use super::reaction_picker::PickHandler;
13
13
use super::reaction_pills::{ReactionControls, reaction_pills};
14
14
use super::widgets::{icon, symbol};
15
use crate::card_state::BotIdentity;
15
16
use crate::data::Directory;
16
17
use crate::render::Block;
17
18
use crate::rows::{Delivery, MessageRow, Receipt, Skeleton, bubble_corners};
@@ -36,6 +37,7 @@ const PULSE_PERIOD: Duration = Duration::from_millis(1600);
36
37
const SKELETON_LINE_HEIGHT: f32 = 20.;
37
38
38
39
pub struct RowActions {
40
pub bot: Option<BotIdentity>,
39
41
pub open_thread: RowAction,
40
42
pub retry: RowAction,
41
43
pub reply: RowAction,
@@ -151,7 +153,8 @@ fn bubble(
151
153
));
152
154
content = content.children(cards_view(
153
155
&row.adaptive_cards,
154
&format!("message-{index}"),
156
&row.conversation_id,
157
&row.key,
155
158
cx,
156
159
));
157
160
if has_reactions {
@@ -489,7 +492,8 @@ fn post_card(
489
492
));
490
493
body = body.children(cards_view(
491
494
&row.adaptive_cards,
492
&format!("message-{index}"),
495
&row.conversation_id,
496
&row.key,
493
497
cx,
494
498
));
495
499
if !row.reactions.is_empty() {
@@ -523,11 +527,13 @@ fn others_row(
523
527
row: &MessageRow,
524
528
index: usize,
525
529
directory: &Directory,
530
bot: Option<&BotIdentity>,
526
531
retry: RowAction,
527
532
extras: BubbleExtras,
528
533
cx: &App,
529
534
) -> Div {
530
535
let first = !row.series.has_prev;
536
let author = bot.map_or_else(|| row.author.clone(), |bot| bot.name.clone());
531
537
let mut column = v_flex()
532
538
.gap(px(2.))
533
539
.max_w(relative(MAX_WIDTH_RATIO))
@@ -539,7 +545,7 @@ fn others_row(
539
545
.text_size(px(12.))
540
546
.font_weight(FontWeight::SEMIBOLD)
541
547
.text_color(theme::text_soft())
542
.child(row.author.clone()),
548
.child(author.clone()),
543
549
),
544
550
);
545
551
}
@@ -547,7 +553,9 @@ fn others_row(
547
553
if let Some(note) = delivery_note(row, retry, index) {
548
554
column = column.child(note);
549
555
}
550
let lead = if first || row.card {
556
let lead = if let Some(bot) = bot.filter(|_| first || row.card) {
557
bot_avatar(bot, AVATAR_SIZE)
558
} else if first || row.card {
551
559
person_avatar(
552
560
directory,
553
561
row.sender_id.as_deref(),
@@ -593,6 +601,7 @@ pub fn render_message_row(
593
601
cx: &App,
594
602
) -> AnyElement {
595
603
let RowActions {
604
bot,
596
605
open_thread,
597
606
retry,
598
607
reply,
@@ -631,7 +640,7 @@ pub fn render_message_row(
631
640
} else if own {
632
641
own_row(row, index, directory, retry, extras, cx)
633
642
} else {
634
others_row(row, index, directory, retry, extras, cx)
643
others_row(row, index, directory, bot.as_ref(), retry, extras, cx)
635
644
};
636
645
container
637
646
.child(
@@ -7,11 +7,12 @@ use std::time::Duration;7
7
8
use super::adaptive_card::cards_view;8
use super::adaptive_card::cards_view;9
use super::attachments::{FileActions, attachments_view, message_body};9
use super::attachments::{FileActions, attachments_view, message_body};10
use super::avatar::{member_stack, person_avatar};10
use super::avatar::{bot_avatar, member_stack, person_avatar};11
use super::message_actions::{HoverChange, MessageMenu, message_toolbar};11
use super::message_actions::{HoverChange, MessageMenu, message_toolbar};12
use super::reaction_picker::PickHandler;12
use super::reaction_picker::PickHandler;13
use super::reaction_pills::{ReactionControls, reaction_pills};13
use super::reaction_pills::{ReactionControls, reaction_pills};14
use super::widgets::{icon, symbol};14
use super::widgets::{icon, symbol};15
use crate::card_state::BotIdentity;15
use crate::data::Directory;16
use crate::data::Directory;16
use crate::render::Block;17
use crate::render::Block;17
use crate::rows::{Delivery, MessageRow, Receipt, Skeleton, bubble_corners};18
use crate::rows::{Delivery, MessageRow, Receipt, Skeleton, bubble_corners};@@ -36,6 +37,7 @@ const PULSE_PERIOD: Duration = Duration::from_millis(1600);36
const SKELETON_LINE_HEIGHT: f32 = 20.;37
const SKELETON_LINE_HEIGHT: f32 = 20.;37
38
38
pub struct RowActions {39
pub struct RowActions {40
pub bot: Option<BotIdentity>,39
pub open_thread: RowAction,41
pub open_thread: RowAction,40
pub retry: RowAction,42
pub retry: RowAction,41
pub reply: RowAction,43
pub reply: RowAction,@@ -151,7 +153,8 @@ fn bubble(151
));153
));152
content = content.children(cards_view(154
content = content.children(cards_view(153
&row.adaptive_cards,155
&row.adaptive_cards,154
&format!("message-{index}"),156
&row.conversation_id,157
&row.key,155
cx,158
cx,156
));159
));157
if has_reactions {160
if has_reactions {@@ -489,7 +492,8 @@ fn post_card(489
));492
));490
body = body.children(cards_view(493
body = body.children(cards_view(491
&row.adaptive_cards,494
&row.adaptive_cards,492
&format!("message-{index}"),495
&row.conversation_id,496
&row.key,493
cx,497
cx,494
));498
));495
if !row.reactions.is_empty() {499
if !row.reactions.is_empty() {@@ -523,11 +527,13 @@ fn others_row(523
row: &MessageRow,527
row: &MessageRow,524
index: usize,528
index: usize,525
directory: &Directory,529
directory: &Directory,530
bot: Option<&BotIdentity>,526
retry: RowAction,531
retry: RowAction,527
extras: BubbleExtras,532
extras: BubbleExtras,528
cx: &App,533
cx: &App,529
) -> Div {534
) -> Div {530
let first = !row.series.has_prev;535
let first = !row.series.has_prev;536
let author = bot.map_or_else(|| row.author.clone(), |bot| bot.name.clone());531
let mut column = v_flex()537
let mut column = v_flex()532
.gap(px(2.))538
.gap(px(2.))533
.max_w(relative(MAX_WIDTH_RATIO))539
.max_w(relative(MAX_WIDTH_RATIO))@@ -539,7 +545,7 @@ fn others_row(539
.text_size(px(12.))545
.text_size(px(12.))540
.font_weight(FontWeight::SEMIBOLD)546
.font_weight(FontWeight::SEMIBOLD)541
.text_color(theme::text_soft())547
.text_color(theme::text_soft())542
.child(row.author.clone()),548
.child(author.clone()),543
),549
),544
);550
);545
}551
}@@ -547,7 +553,9 @@ fn others_row(547
if let Some(note) = delivery_note(row, retry, index) {553
if let Some(note) = delivery_note(row, retry, index) {548
column = column.child(note);554
column = column.child(note);549
}555
}550
let lead = if first || row.card {556
let lead = if let Some(bot) = bot.filter(|_| first || row.card) {557
bot_avatar(bot, AVATAR_SIZE)558
} else if first || row.card {551
person_avatar(559
person_avatar(552
directory,560
directory,553
row.sender_id.as_deref(),561
row.sender_id.as_deref(),@@ -593,6 +601,7 @@ pub fn render_message_row(593
cx: &App,601
cx: &App,594
) -> AnyElement {602
) -> AnyElement {595
let RowActions {603
let RowActions {604
bot,596
open_thread,605
open_thread,597
retry,606
retry,598
reply,607
reply,@@ -631,7 +640,7 @@ pub fn render_message_row(631
} else if own {640
} else if own {632
own_row(row, index, directory, retry, extras, cx)641
own_row(row, index, directory, retry, extras, cx)633
} else {642
} else {634
others_row(row, index, directory, retry, extras, cx)643
others_row(row, index, directory, bot.as_ref(), retry, extras, cx)635
};644
};636
container645
container637
.child(646
.child(@@ -4,6 +4,7 @@ pub mod attachments;
4
4
pub mod avatar;
5
5
pub mod composer;
6
6
pub mod conversation;
7
pub mod dialog_overlay;
7
8
pub mod draft_style;
8
9
pub mod emoji_popup;
9
10
pub mod format_toolbar;
@@ -4,6 +4,7 @@ pub mod attachments;4
pub mod avatar;4
pub mod avatar;5
pub mod composer;5
pub mod composer;6
pub mod conversation;6
pub mod conversation;7
pub mod dialog_overlay;7
pub mod draft_style;8
pub mod draft_style;8
pub mod emoji_popup;9
pub mod emoji_popup;9
pub mod format_toolbar;10
pub mod format_toolbar;@@ -2,6 +2,7 @@ use gpui_kit::component::{h_flex, v_flex};
2
2
use gpui_kit::*;
3
3
4
4
use super::conversation::{ConversationView, ReplyToHovered};
5
use super::dialog_overlay::render_task_dialog;
5
6
use super::sidebar::SidebarView;
6
7
use super::status_bar::render_status_bar;
7
8
use super::switcher::{Switcher, SwitcherEvent, candidates_from};
@@ -288,6 +289,7 @@ impl Render for AppShell {
288
289
.child(status),
289
290
)
290
291
.children(self.switcher.clone())
292
.children(render_task_dialog(self.state.read(cx), cx))
291
293
.child(crate::frame_log::probe("last"))
292
294
}
293
295
}
@@ -2,6 +2,7 @@ use gpui_kit::component::{h_flex, v_flex};2
use gpui_kit::*;2
use gpui_kit::*;3
3
4
use super::conversation::{ConversationView, ReplyToHovered};4
use super::conversation::{ConversationView, ReplyToHovered};5
use super::dialog_overlay::render_task_dialog;5
use super::sidebar::SidebarView;6
use super::sidebar::SidebarView;6
use super::status_bar::render_status_bar;7
use super::status_bar::render_status_bar;7
use super::switcher::{Switcher, SwitcherEvent, candidates_from};8
use super::switcher::{Switcher, SwitcherEvent, candidates_from};@@ -288,6 +289,7 @@ impl Render for AppShell {288
.child(status),289
.child(status),289
)290
)290
.children(self.switcher.clone())291
.children(self.switcher.clone())292
.children(render_task_dialog(self.state.read(cx), cx))291
.child(crate::frame_log::probe("last"))293
.child(crate::frame_log::probe("last"))292
}294
}293
}295
}@@ -0,0 +1,607 @@
1
use serde_json::{Value, json};
2
use session::{ApiResponse, Method, Request, SPACES, Scope, Session};
3
4
use crate::error::{Error, Result};
5
use crate::messages::{encode, messages_scope};
6
use crate::pins::DEFAULT_REGION;
7
8
pub const DEFAULT_MT_REGION: &str = "emea";
9
pub const FALLBACK_INVOKE_REGION: &str = "de";
10
const SPACES_SCOPE: &str = "user_impersonation";
11
const TOKEN_PLACEHOLDER: &str = "@@rusty-teams-user-aad-token@@";
12
const BOT_MRI_PREFIX: &str = "28:";
13
const CARD_MESSAGE_TYPE: &str = "RichText/Media_Card";
14
const ADAPTIVE_CARD_TYPE: &str = "application/vnd.microsoft.card.adaptive";
15
const MESSAGE_TYPE: &str = "application/vnd.microsoft.activity.message";
16
const ERROR_STATUS_FLOOR: u64 = 400;
17
18
pub fn spaces_scope() -> Scope {
19
Scope::new(SPACES, SPACES_SCOPE)
20
}
21
22
pub fn bot_mri(bot_id: &str) -> String {
23
if bot_id.starts_with(BOT_MRI_PREFIX) {
24
bot_id.to_owned()
25
} else {
26
format!("{BOT_MRI_PREFIX}{bot_id}")
27
}
28
}
29
30
pub fn bot_guid(bot_id: &str) -> &str {
31
bot_id.strip_prefix(BOT_MRI_PREFIX).unwrap_or(bot_id)
32
}
33
34
pub trait CardTransport {
35
fn send(
36
&self,
37
request: Request,
38
scope: Scope,
39
) -> impl std::future::Future<Output = Result<ApiResponse>>;
40
}
41
42
pub struct SessionCardTransport {
43
session: Session,
44
}
45
46
impl SessionCardTransport {
47
pub fn new(session: &Session) -> Self {
48
SessionCardTransport {
49
session: session.clone(),
50
}
51
}
52
}
53
54
impl CardTransport for SessionCardTransport {
55
async fn send(&self, request: Request, scope: Scope) -> Result<ApiResponse> {
56
let mut answers = self.session.batch(&[request], &scope).await?;
57
Ok(answers.remove(0))
58
}
59
}
60
61
#[derive(Debug, Clone, PartialEq)]
62
pub struct InvokeRequest {
63
pub bot_id: String,
64
pub app_id: String,
65
pub name: String,
66
pub value: Value,
67
pub display_name: String,
68
pub server_message_id: String,
69
pub client_message_id: Option<String>,
70
pub conversation_id: String,
71
}
72
73
#[derive(Debug, Clone, PartialEq)]
74
pub enum InvokeResponse {
75
Empty,
76
Card(Value),
77
Message(String),
78
Task(TaskResponse),
79
Failed { status_code: u16, message: String },
80
}
81
82
#[derive(Debug, Clone, PartialEq)]
83
pub enum TaskResponse {
84
Continue(TaskContinue),
85
Message(String),
86
}
87
88
#[derive(Debug, Clone, PartialEq)]
89
pub struct TaskContinue {
90
pub title: Option<String>,
91
pub width: Option<u32>,
92
pub height: Option<u32>,
93
pub content: TaskContent,
94
}
95
96
#[derive(Debug, Clone, PartialEq)]
97
pub enum TaskContent {
98
Url {
99
url: String,
100
fallback_url: Option<String>,
101
},
102
Card(Value),
103
}
104
105
#[derive(Debug, Clone, PartialEq, Eq)]
106
pub struct ChatApp {
107
pub app_id: String,
108
pub name: String,
109
pub bot_ids: Vec<String>,
110
pub small_image_url: Option<String>,
111
pub accent_color: Option<String>,
112
pub web_application_resource: Option<String>,
113
}
114
115
impl ChatApp {
116
pub fn has_bot(&self, bot_id: &str) -> bool {
117
self.bot_ids
118
.iter()
119
.any(|known| bot_guid(known).eq_ignore_ascii_case(bot_guid(bot_id)))
120
}
121
}
122
123
pub struct CardActions<T: CardTransport = SessionCardTransport> {
124
transport: T,
125
chatsvc_base: String,
126
fallback_chatsvc_base: String,
127
mt_base: String,
128
}
129
130
impl CardActions<SessionCardTransport> {
131
pub fn new(session: &Session) -> Self {
132
CardActions::with_transport(
133
SessionCardTransport::new(session),
134
DEFAULT_REGION,
135
DEFAULT_MT_REGION,
136
)
137
}
138
}
139
140
impl<T: CardTransport> CardActions<T> {
141
pub fn with_transport(transport: T, region: &str, mt_region: &str) -> Self {
142
CardActions {
143
transport,
144
chatsvc_base: chatsvc_base(region),
145
fallback_chatsvc_base: chatsvc_base(FALLBACK_INVOKE_REGION),
146
mt_base: format!("https://teams.cloud.microsoft/api/mt/{mt_region}/beta/chats"),
147
}
148
}
149
150
pub fn invoke_url(&self, bot_id: &str) -> String {
151
invoke_url(&self.chatsvc_base, bot_id)
152
}
153
154
pub fn entitlements_url(&self, chat_id: &str) -> String {
155
format!("{}/{}/apps/chatentitlements", self.mt_base, encode(chat_id))
156
}
157
158
pub async fn invoke(&self, invoke: InvokeRequest) -> Result<InvokeResponse> {
159
let body = invoke_body(&invoke);
160
let mut answer = self.post(&self.invoke_url(&invoke.bot_id), &body).await?;
161
if answer.status == 404 && self.fallback_chatsvc_base != self.chatsvc_base {
162
let url = invoke_url(&self.fallback_chatsvc_base, &invoke.bot_id);
163
answer = self.post(&url, &body).await?;
164
}
165
if !answer.is_success() {
166
return Err(Error::Session(session::Error::api(
167
answer.status,
168
"chatsvc",
169
answer.body,
170
)));
171
}
172
Ok(parse_invoke_response(&answer.body))
173
}
174
175
pub async fn chat_apps(&self, chat_id: &str) -> Result<Vec<ChatApp>> {
176
let answer = self
177
.transport
178
.send(Request::get(self.entitlements_url(chat_id)), spaces_scope())
179
.await?;
180
if !answer.is_success() {
181
return Err(Error::Session(session::Error::api(
182
answer.status,
183
"chatentitlements",
184
answer.body,
185
)));
186
}
187
parse_chat_apps(&answer.body)
188
}
189
190
async fn post(&self, url: &str, body: &Value) -> Result<ApiResponse> {
191
let mut request = Request::with_body(Method::Post, url, body.clone()).with_body_token(
192
SPACES,
193
SPACES_SCOPE,
194
TOKEN_PLACEHOLDER,
195
);
196
request.headers = vec![
197
("x-ms-migration".to_owned(), "True".to_owned()),
198
("behavioroverride".to_owned(), "redirectAs404".to_owned()),
199
("content-type".to_owned(), "application/json".to_owned()),
200
];
201
self.transport.send(request, messages_scope()).await
202
}
203
}
204
205
fn chatsvc_base(region: &str) -> String {
206
format!("https://teams.cloud.microsoft/api/chatsvc/{region}/v1/agents")
207
}
208
209
fn invoke_url(base: &str, bot_id: &str) -> String {
210
format!("{base}/{}/invoke", encode(&bot_mri(bot_id)))
211
}
212
213
pub fn invoke_body(invoke: &InvokeRequest) -> Value {
214
let mut body = json!({
215
"name": invoke.name,
216
"appId": invoke.app_id,
217
"messageType": CARD_MESSAGE_TYPE,
218
"value": invoke.value,
219
"imdisplayname": invoke.display_name,
220
"userAadToken": TOKEN_PLACEHOLDER,
221
"serverMessageId": invoke.server_message_id,
222
"conversation": {"id": invoke.conversation_id},
223
});
224
if let Some(client_message_id) = &invoke.client_message_id {
225
body["clientMessageId"] = json!(client_message_id);
226
}
227
body
228
}
229
230
pub fn parse_invoke_response(body: &Value) -> InvokeResponse {
231
let Some(object) = body.as_object() else {
232
return InvokeResponse::Empty;
233
};
234
if let Some(task) = object.get("task") {
235
return parse_task(task);
236
}
237
let status_code = object.get("statusCode").and_then(Value::as_u64);
238
let value = object.get("value");
239
if let Some(status_code) = status_code.filter(|code| *code >= ERROR_STATUS_FLOOR) {
240
return InvokeResponse::Failed {
241
status_code: status_code as u16,
242
message: value.map(text_of).unwrap_or_default(),
243
};
244
}
245
match object.get("type").and_then(Value::as_str) {
246
Some(ADAPTIVE_CARD_TYPE) => value
247
.map(|card| InvokeResponse::Card(card.clone()))
248
.unwrap_or(InvokeResponse::Empty),
249
Some(MESSAGE_TYPE) => InvokeResponse::Message(value.map(text_of).unwrap_or_default()),
250
_ => InvokeResponse::Empty,
251
}
252
}
253
254
fn parse_task(task: &Value) -> InvokeResponse {
255
let value = task.get("value");
256
match task.get("type").and_then(Value::as_str) {
257
Some("message") => InvokeResponse::Task(TaskResponse::Message(
258
value.map(text_of).unwrap_or_default(),
259
)),
260
Some("continue") => {
261
let Some(value) = value else {
262
return InvokeResponse::Empty;
263
};
264
let content = match value.get("card") {
265
Some(card) => TaskContent::Card(card_content(card)),
266
None => match value.get("url").and_then(Value::as_str) {
267
Some(url) => TaskContent::Url {
268
url: url.to_owned(),
269
fallback_url: value
270
.get("fallbackUrl")
271
.and_then(Value::as_str)
272
.map(str::to_owned),
273
},
274
None => return InvokeResponse::Empty,
275
},
276
};
277
InvokeResponse::Task(TaskResponse::Continue(TaskContinue {
278
title: value
279
.get("title")
280
.and_then(Value::as_str)
281
.map(str::to_owned),
282
width: dimension(value.get("width")),
283
height: dimension(value.get("height")),
284
content,
285
}))
286
}
287
_ => InvokeResponse::Empty,
288
}
289
}
290
291
fn dimension(value: Option<&Value>) -> Option<u32> {
292
let pixels = value?.as_u64()?;
293
u32::try_from(pixels).ok().filter(|pixels| *pixels > 0)
294
}
295
296
fn card_content(card: &Value) -> Value {
297
match card.get("content") {
298
Some(Value::String(text)) => serde_json::from_str(text).unwrap_or_else(|_| card.clone()),
299
Some(content) => content.clone(),
300
None => card.clone(),
301
}
302
}
303
304
fn text_of(value: &Value) -> String {
305
match value.as_str() {
306
Some(text) => text.to_owned(),
307
None => value.to_string(),
308
}
309
}
310
311
pub fn parse_chat_apps(body: &Value) -> Result<Vec<ChatApp>> {
312
let definitions = body
313
.pointer("/value/definitions")
314
.and_then(Value::as_array)
315
.ok_or_else(|| Error::UnexpectedAnswer("no app definitions".into()))?;
316
Ok(definitions
317
.iter()
318
.filter_map(|definition| {
319
let text = |key: &str| {
320
definition
321
.get(key)
322
.and_then(Value::as_str)
323
.filter(|text| !text.is_empty())
324
.map(str::to_owned)
325
};
326
Some(ChatApp {
327
app_id: text("id")?,
328
name: text("name")?,
329
bot_ids: definition
330
.get("bots")
331
.and_then(Value::as_array)
332
.into_iter()
333
.flatten()
334
.filter_map(|bot| bot.get("id")?.as_str().map(str::to_owned))
335
.collect(),
336
small_image_url: text("smallImageUrl"),
337
accent_color: text("accentColor"),
338
web_application_resource: definition
339
.pointer("/webApplicationInfo/resource")
340
.and_then(Value::as_str)
341
.map(str::to_owned),
342
})
343
})
344
.collect())
345
}
346
347
#[cfg(test)]
348
mod tests {
349
use std::sync::Mutex;
350
351
use session::IC3;
352
353
use super::*;
354
355
struct Canned {
356
answers: Mutex<Vec<(u16, Value)>>,
357
sent: Mutex<Vec<(Request, Scope)>>,
358
}
359
360
impl CardTransport for Canned {
361
async fn send(&self, request: Request, scope: Scope) -> Result<ApiResponse> {
362
self.sent.lock().unwrap().push((request, scope));
363
let (status, body) = self.answers.lock().unwrap().remove(0);
364
Ok(ApiResponse {
365
status,
366
body,
367
retry_after: None,
368
})
369
}
370
}
371
372
fn canned(answers: Vec<(u16, Value)>) -> CardActions<Canned> {
373
CardActions::with_transport(
374
Canned {
375
answers: Mutex::new(answers),
376
sent: Mutex::new(Vec::new()),
377
},
378
"emea",
379
"emea",
380
)
381
}
382
383
fn sample_request() -> InvokeRequest {
384
InvokeRequest {
385
bot_id: "0000aaaa-0000-0000-0000-000000000001".into(),
386
app_id: "app-1".into(),
387
name: "messageback".into(),
388
value: json!({"type": "unwatch", "page": "p1"}),
389
display_name: "Test User".into(),
390
server_message_id: "1700000000001".into(),
391
client_message_id: None,
392
conversation_id: "19:chat@unq.gbl.spaces".into(),
393
}
394
}
395
396
fn entitlements() -> Value {
397
json!({"value": {"definitions": [
398
{
399
"id": "app-1",
400
"name": "Wiki Bot",
401
"smallImageUrl": "https://cdn.example/small.png",
402
"largeImageUrl": "https://cdn.example/large.png",
403
"accentColor": "#0052CC",
404
"bots": [{"id": "0000aaaa-0000-0000-0000-000000000001"}],
405
"webApplicationInfo": {"id": "web-1", "resource": "https://bot.example"}
406
},
407
{"id": "app-2", "name": "Tabs Only"},
408
{"name": "No Id"}
409
]}})
410
}
411
412
#[tokio::test]
413
async fn invoke_posts_to_the_bot_with_the_card_body() {
414
let actions = canned(vec![(200, Value::Null)]);
415
let response = actions.invoke(sample_request()).await.unwrap();
416
assert_eq!(response, InvokeResponse::Empty);
417
let sent = actions.transport.sent.lock().unwrap();
418
let (request, scope) = &sent[0];
419
assert_eq!(
420
request.url,
421
"https://teams.cloud.microsoft/api/chatsvc/emea/v1/agents/28%3A0000aaaa-0000-0000-0000-000000000001/invoke"
422
);
423
assert_eq!(scope.resource, IC3);
424
assert!(
425
request
426
.headers
427
.contains(&("x-ms-migration".into(), "True".into()))
428
);
429
assert!(
430
request
431
.headers
432
.contains(&("behavioroverride".into(), "redirectAs404".into()))
433
);
434
assert_eq!(request.body_tokens[0].resource, SPACES);
435
let body = request.body.as_ref().unwrap();
436
assert_eq!(body["name"], "messageback");
437
assert_eq!(body["appId"], "app-1");
438
assert_eq!(body["messageType"], "RichText/Media_Card");
439
assert_eq!(body["value"]["type"], "unwatch");
440
assert_eq!(body["serverMessageId"], "1700000000001");
441
assert_eq!(body["conversation"]["id"], "19:chat@unq.gbl.spaces");
442
assert_eq!(body["userAadToken"], request.body_tokens[0].placeholder);
443
assert!(body.get("clientMessageId").is_none());
444
}
445
446
#[tokio::test]
447
async fn invoke_keeps_a_known_client_message_id() {
448
let actions = canned(vec![(200, Value::Null)]);
449
let request = InvokeRequest {
450
client_message_id: Some("client-1".into()),
451
..sample_request()
452
};
453
actions.invoke(request).await.unwrap();
454
let sent = actions.transport.sent.lock().unwrap();
455
assert_eq!(
456
sent[0].0.body.as_ref().unwrap()["clientMessageId"],
457
"client-1"
458
);
459
}
460
461
#[tokio::test]
462
async fn invoke_retries_a_missing_route_in_the_fallback_region() {
463
let actions = canned(vec![(404, Value::Null), (200, Value::Null)]);
464
actions.invoke(sample_request()).await.unwrap();
465
let sent = actions.transport.sent.lock().unwrap();
466
assert!(sent[1].0.url.contains("/chatsvc/de/"));
467
}
468
469
#[tokio::test]
470
async fn invoke_failure_is_an_error_without_retry() {
471
let actions = canned(vec![(500, json!({"message": "boom"}))]);
472
assert!(actions.invoke(sample_request()).await.is_err());
473
assert_eq!(actions.transport.sent.lock().unwrap().len(), 1);
474
}
475
476
#[test]
477
fn empty_and_unknown_answers_are_empty() {
478
assert_eq!(parse_invoke_response(&Value::Null), InvokeResponse::Empty);
479
assert_eq!(parse_invoke_response(&json!("")), InvokeResponse::Empty);
480
assert_eq!(
481
parse_invoke_response(&json!({"other": 1})),
482
InvokeResponse::Empty
483
);
484
}
485
486
#[test]
487
fn task_with_a_url() {
488
let response = parse_invoke_response(&json!({
489
"responseType": "task",
490
"task": {"type": "continue", "value": {
491
"url": "https://bot.example/task", "fallbackUrl": "https://bot.example/fallback",
492
"height": 380, "width": 620, "title": "Settings"
493
}}
494
}));
495
assert_eq!(
496
response,
497
InvokeResponse::Task(TaskResponse::Continue(TaskContinue {
498
title: Some("Settings".into()),
499
width: Some(620),
500
height: Some(380),
501
content: TaskContent::Url {
502
url: "https://bot.example/task".into(),
503
fallback_url: Some("https://bot.example/fallback".into()),
504
},
505
}))
506
);
507
}
508
509
#[test]
510
fn task_with_a_card_attachment() {
511
let response = parse_invoke_response(&json!({
512
"task": {"type": "continue", "value": {
513
"size": "medium",
514
"card": {"contentType": "application/vnd.microsoft.card.adaptive", "content": {"type": "AdaptiveCard"}}
515
}}
516
}));
517
let InvokeResponse::Task(TaskResponse::Continue(task)) = response else {
518
panic!("expected a continue task");
519
};
520
assert_eq!(
521
task.content,
522
TaskContent::Card(json!({"type": "AdaptiveCard"}))
523
);
524
assert_eq!(task.width, None);
525
}
526
527
#[test]
528
fn task_message_and_unusable_continue() {
529
assert_eq!(
530
parse_invoke_response(&json!({"task": {"type": "message", "value": "Done"}})),
531
InvokeResponse::Task(TaskResponse::Message("Done".into()))
532
);
533
assert_eq!(
534
parse_invoke_response(&json!({"task": {"type": "continue", "value": {}}})),
535
InvokeResponse::Empty
536
);
537
}
538
539
#[test]
540
fn universal_action_answers() {
541
assert_eq!(
542
parse_invoke_response(&json!({
543
"statusCode": 200,
544
"type": "application/vnd.microsoft.card.adaptive",
545
"value": {"type": "AdaptiveCard"}
546
})),
547
InvokeResponse::Card(json!({"type": "AdaptiveCard"}))
548
);
549
assert_eq!(
550
parse_invoke_response(&json!({
551
"statusCode": 200,
552
"type": "application/vnd.microsoft.activity.message",
553
"value": "Saved"
554
})),
555
InvokeResponse::Message("Saved".into())
556
);
557
assert_eq!(
558
parse_invoke_response(&json!({"statusCode": 500, "type": "x", "value": "Broken"})),
559
InvokeResponse::Failed {
560
status_code: 500,
561
message: "Broken".into()
562
}
563
);
564
}
565
566
#[tokio::test]
567
async fn chat_apps_use_the_spaces_scope_and_parse_definitions() {
568
let actions = canned(vec![(200, entitlements())]);
569
let apps = actions.chat_apps("19:chat@unq.gbl.spaces").await.unwrap();
570
assert_eq!(apps.len(), 2);
571
let wiki = &apps[0];
572
assert_eq!(wiki.name, "Wiki Bot");
573
assert_eq!(
574
wiki.small_image_url.as_deref(),
575
Some("https://cdn.example/small.png")
576
);
577
assert_eq!(wiki.accent_color.as_deref(), Some("#0052CC"));
578
assert_eq!(
579
wiki.web_application_resource.as_deref(),
580
Some("https://bot.example")
581
);
582
assert!(wiki.has_bot("0000AAAA-0000-0000-0000-000000000001"));
583
assert!(wiki.has_bot("28:0000aaaa-0000-0000-0000-000000000001"));
584
assert!(!apps[1].has_bot("0000aaaa-0000-0000-0000-000000000001"));
585
let sent = actions.transport.sent.lock().unwrap();
586
assert_eq!(
587
sent[0].0.url,
588
"https://teams.cloud.microsoft/api/mt/emea/beta/chats/19%3Achat%40unq.gbl.spaces/apps/chatentitlements"
589
);
590
assert_eq!(sent[0].1, spaces_scope());
591
}
592
593
#[test]
594
fn entitlements_without_definitions_are_unexpected() {
595
assert!(matches!(
596
parse_chat_apps(&json!({"value": {}})),
597
Err(Error::UnexpectedAnswer(_))
598
));
599
}
600
601
#[test]
602
fn bot_ids_convert_both_ways() {
603
assert_eq!(bot_mri("abc"), "28:abc");
604
assert_eq!(bot_mri("28:abc"), "28:abc");
605
assert_eq!(bot_guid("28:abc"), "abc");
606
}
607
}
@@ -0,0 +1,607 @@1
use serde_json::{Value, json};2
use session::{ApiResponse, Method, Request, SPACES, Scope, Session};3
4
use crate::error::{Error, Result};5
use crate::messages::{encode, messages_scope};6
use crate::pins::DEFAULT_REGION;7
8
pub const DEFAULT_MT_REGION: &str = "emea";9
pub const FALLBACK_INVOKE_REGION: &str = "de";10
const SPACES_SCOPE: &str = "user_impersonation";11
const TOKEN_PLACEHOLDER: &str = "@@rusty-teams-user-aad-token@@";12
const BOT_MRI_PREFIX: &str = "28:";13
const CARD_MESSAGE_TYPE: &str = "RichText/Media_Card";14
const ADAPTIVE_CARD_TYPE: &str = "application/vnd.microsoft.card.adaptive";15
const MESSAGE_TYPE: &str = "application/vnd.microsoft.activity.message";16
const ERROR_STATUS_FLOOR: u64 = 400;17
18
pub fn spaces_scope() -> Scope {19
Scope::new(SPACES, SPACES_SCOPE)20
}21
22
pub fn bot_mri(bot_id: &str) -> String {23
if bot_id.starts_with(BOT_MRI_PREFIX) {24
bot_id.to_owned()25
} else {26
format!("{BOT_MRI_PREFIX}{bot_id}")27
}28
}29
30
pub fn bot_guid(bot_id: &str) -> &str {31
bot_id.strip_prefix(BOT_MRI_PREFIX).unwrap_or(bot_id)32
}33
34
pub trait CardTransport {35
fn send(36
&self,37
request: Request,38
scope: Scope,39
) -> impl std::future::Future<Output = Result<ApiResponse>>;40
}41
42
pub struct SessionCardTransport {43
session: Session,44
}45
46
impl SessionCardTransport {47
pub fn new(session: &Session) -> Self {48
SessionCardTransport {49
session: session.clone(),50
}51
}52
}53
54
impl CardTransport for SessionCardTransport {55
async fn send(&self, request: Request, scope: Scope) -> Result<ApiResponse> {56
let mut answers = self.session.batch(&[request], &scope).await?;57
Ok(answers.remove(0))58
}59
}60
61
#[derive(Debug, Clone, PartialEq)]62
pub struct InvokeRequest {63
pub bot_id: String,64
pub app_id: String,65
pub name: String,66
pub value: Value,67
pub display_name: String,68
pub server_message_id: String,69
pub client_message_id: Option<String>,70
pub conversation_id: String,71
}72
73
#[derive(Debug, Clone, PartialEq)]74
pub enum InvokeResponse {75
Empty,76
Card(Value),77
Message(String),78
Task(TaskResponse),79
Failed { status_code: u16, message: String },80
}81
82
#[derive(Debug, Clone, PartialEq)]83
pub enum TaskResponse {84
Continue(TaskContinue),85
Message(String),86
}87
88
#[derive(Debug, Clone, PartialEq)]89
pub struct TaskContinue {90
pub title: Option<String>,91
pub width: Option<u32>,92
pub height: Option<u32>,93
pub content: TaskContent,94
}95
96
#[derive(Debug, Clone, PartialEq)]97
pub enum TaskContent {98
Url {99
url: String,100
fallback_url: Option<String>,101
},102
Card(Value),103
}104
105
#[derive(Debug, Clone, PartialEq, Eq)]106
pub struct ChatApp {107
pub app_id: String,108
pub name: String,109
pub bot_ids: Vec<String>,110
pub small_image_url: Option<String>,111
pub accent_color: Option<String>,112
pub web_application_resource: Option<String>,113
}114
115
impl ChatApp {116
pub fn has_bot(&self, bot_id: &str) -> bool {117
self.bot_ids118
.iter()119
.any(|known| bot_guid(known).eq_ignore_ascii_case(bot_guid(bot_id)))120
}121
}122
123
pub struct CardActions<T: CardTransport = SessionCardTransport> {124
transport: T,125
chatsvc_base: String,126
fallback_chatsvc_base: String,127
mt_base: String,128
}129
130
impl CardActions<SessionCardTransport> {131
pub fn new(session: &Session) -> Self {132
CardActions::with_transport(133
SessionCardTransport::new(session),134
DEFAULT_REGION,135
DEFAULT_MT_REGION,136
)137
}138
}139
140
impl<T: CardTransport> CardActions<T> {141
pub fn with_transport(transport: T, region: &str, mt_region: &str) -> Self {142
CardActions {143
transport,144
chatsvc_base: chatsvc_base(region),145
fallback_chatsvc_base: chatsvc_base(FALLBACK_INVOKE_REGION),146
mt_base: format!("https://teams.cloud.microsoft/api/mt/{mt_region}/beta/chats"),147
}148
}149
150
pub fn invoke_url(&self, bot_id: &str) -> String {151
invoke_url(&self.chatsvc_base, bot_id)152
}153
154
pub fn entitlements_url(&self, chat_id: &str) -> String {155
format!("{}/{}/apps/chatentitlements", self.mt_base, encode(chat_id))156
}157
158
pub async fn invoke(&self, invoke: InvokeRequest) -> Result<InvokeResponse> {159
let body = invoke_body(&invoke);160
let mut answer = self.post(&self.invoke_url(&invoke.bot_id), &body).await?;161
if answer.status == 404 && self.fallback_chatsvc_base != self.chatsvc_base {162
let url = invoke_url(&self.fallback_chatsvc_base, &invoke.bot_id);163
answer = self.post(&url, &body).await?;164
}165
if !answer.is_success() {166
return Err(Error::Session(session::Error::api(167
answer.status,168
"chatsvc",169
answer.body,170
)));171
}172
Ok(parse_invoke_response(&answer.body))173
}174
175
pub async fn chat_apps(&self, chat_id: &str) -> Result<Vec<ChatApp>> {176
let answer = self177
.transport178
.send(Request::get(self.entitlements_url(chat_id)), spaces_scope())179
.await?;180
if !answer.is_success() {181
return Err(Error::Session(session::Error::api(182
answer.status,183
"chatentitlements",184
answer.body,185
)));186
}187
parse_chat_apps(&answer.body)188
}189
190
async fn post(&self, url: &str, body: &Value) -> Result<ApiResponse> {191
let mut request = Request::with_body(Method::Post, url, body.clone()).with_body_token(192
SPACES,193
SPACES_SCOPE,194
TOKEN_PLACEHOLDER,195
);196
request.headers = vec![197
("x-ms-migration".to_owned(), "True".to_owned()),198
("behavioroverride".to_owned(), "redirectAs404".to_owned()),199
("content-type".to_owned(), "application/json".to_owned()),200
];201
self.transport.send(request, messages_scope()).await202
}203
}204
205
fn chatsvc_base(region: &str) -> String {206
format!("https://teams.cloud.microsoft/api/chatsvc/{region}/v1/agents")207
}208
209
fn invoke_url(base: &str, bot_id: &str) -> String {210
format!("{base}/{}/invoke", encode(&bot_mri(bot_id)))211
}212
213
pub fn invoke_body(invoke: &InvokeRequest) -> Value {214
let mut body = json!({215
"name": invoke.name,216
"appId": invoke.app_id,217
"messageType": CARD_MESSAGE_TYPE,218
"value": invoke.value,219
"imdisplayname": invoke.display_name,220
"userAadToken": TOKEN_PLACEHOLDER,221
"serverMessageId": invoke.server_message_id,222
"conversation": {"id": invoke.conversation_id},223
});224
if let Some(client_message_id) = &invoke.client_message_id {225
body["clientMessageId"] = json!(client_message_id);226
}227
body228
}229
230
pub fn parse_invoke_response(body: &Value) -> InvokeResponse {231
let Some(object) = body.as_object() else {232
return InvokeResponse::Empty;233
};234
if let Some(task) = object.get("task") {235
return parse_task(task);236
}237
let status_code = object.get("statusCode").and_then(Value::as_u64);238
let value = object.get("value");239
if let Some(status_code) = status_code.filter(|code| *code >= ERROR_STATUS_FLOOR) {240
return InvokeResponse::Failed {241
status_code: status_code as u16,242
message: value.map(text_of).unwrap_or_default(),243
};244
}245
match object.get("type").and_then(Value::as_str) {246
Some(ADAPTIVE_CARD_TYPE) => value247
.map(|card| InvokeResponse::Card(card.clone()))248
.unwrap_or(InvokeResponse::Empty),249
Some(MESSAGE_TYPE) => InvokeResponse::Message(value.map(text_of).unwrap_or_default()),250
_ => InvokeResponse::Empty,251
}252
}253
254
fn parse_task(task: &Value) -> InvokeResponse {255
let value = task.get("value");256
match task.get("type").and_then(Value::as_str) {257
Some("message") => InvokeResponse::Task(TaskResponse::Message(258
value.map(text_of).unwrap_or_default(),259
)),260
Some("continue") => {261
let Some(value) = value else {262
return InvokeResponse::Empty;263
};264
let content = match value.get("card") {265
Some(card) => TaskContent::Card(card_content(card)),266
None => match value.get("url").and_then(Value::as_str) {267
Some(url) => TaskContent::Url {268
url: url.to_owned(),269
fallback_url: value270
.get("fallbackUrl")271
.and_then(Value::as_str)272
.map(str::to_owned),273
},274
None => return InvokeResponse::Empty,275
},276
};277
InvokeResponse::Task(TaskResponse::Continue(TaskContinue {278
title: value279
.get("title")280
.and_then(Value::as_str)281
.map(str::to_owned),282
width: dimension(value.get("width")),283
height: dimension(value.get("height")),284
content,285
}))286
}287
_ => InvokeResponse::Empty,288
}289
}290
291
fn dimension(value: Option<&Value>) -> Option<u32> {292
let pixels = value?.as_u64()?;293
u32::try_from(pixels).ok().filter(|pixels| *pixels > 0)294
}295
296
fn card_content(card: &Value) -> Value {297
match card.get("content") {298
Some(Value::String(text)) => serde_json::from_str(text).unwrap_or_else(|_| card.clone()),299
Some(content) => content.clone(),300
None => card.clone(),301
}302
}303
304
fn text_of(value: &Value) -> String {305
match value.as_str() {306
Some(text) => text.to_owned(),307
None => value.to_string(),308
}309
}310
311
pub fn parse_chat_apps(body: &Value) -> Result<Vec<ChatApp>> {312
let definitions = body313
.pointer("/value/definitions")314
.and_then(Value::as_array)315
.ok_or_else(|| Error::UnexpectedAnswer("no app definitions".into()))?;316
Ok(definitions317
.iter()318
.filter_map(|definition| {319
let text = |key: &str| {320
definition321
.get(key)322
.and_then(Value::as_str)323
.filter(|text| !text.is_empty())324
.map(str::to_owned)325
};326
Some(ChatApp {327
app_id: text("id")?,328
name: text("name")?,329
bot_ids: definition330
.get("bots")331
.and_then(Value::as_array)332
.into_iter()333
.flatten()334
.filter_map(|bot| bot.get("id")?.as_str().map(str::to_owned))335
.collect(),336
small_image_url: text("smallImageUrl"),337
accent_color: text("accentColor"),338
web_application_resource: definition339
.pointer("/webApplicationInfo/resource")340
.and_then(Value::as_str)341
.map(str::to_owned),342
})343
})344
.collect())345
}346
347
#[cfg(test)]348
mod tests {349
use std::sync::Mutex;350
351
use session::IC3;352
353
use super::*;354
355
struct Canned {356
answers: Mutex<Vec<(u16, Value)>>,357
sent: Mutex<Vec<(Request, Scope)>>,358
}359
360
impl CardTransport for Canned {361
async fn send(&self, request: Request, scope: Scope) -> Result<ApiResponse> {362
self.sent.lock().unwrap().push((request, scope));363
let (status, body) = self.answers.lock().unwrap().remove(0);364
Ok(ApiResponse {365
status,366
body,367
retry_after: None,368
})369
}370
}371
372
fn canned(answers: Vec<(u16, Value)>) -> CardActions<Canned> {373
CardActions::with_transport(374
Canned {375
answers: Mutex::new(answers),376
sent: Mutex::new(Vec::new()),377
},378
"emea",379
"emea",380
)381
}382
383
fn sample_request() -> InvokeRequest {384
InvokeRequest {385
bot_id: "0000aaaa-0000-0000-0000-000000000001".into(),386
app_id: "app-1".into(),387
name: "messageback".into(),388
value: json!({"type": "unwatch", "page": "p1"}),389
display_name: "Test User".into(),390
server_message_id: "1700000000001".into(),391
client_message_id: None,392
conversation_id: "19:chat@unq.gbl.spaces".into(),393
}394
}395
396
fn entitlements() -> Value {397
json!({"value": {"definitions": [398
{399
"id": "app-1",400
"name": "Wiki Bot",401
"smallImageUrl": "https://cdn.example/small.png",402
"largeImageUrl": "https://cdn.example/large.png",403
"accentColor": "#0052CC",404
"bots": [{"id": "0000aaaa-0000-0000-0000-000000000001"}],405
"webApplicationInfo": {"id": "web-1", "resource": "https://bot.example"}406
},407
{"id": "app-2", "name": "Tabs Only"},408
{"name": "No Id"}409
]}})410
}411
412
#[tokio::test]413
async fn invoke_posts_to_the_bot_with_the_card_body() {414
let actions = canned(vec![(200, Value::Null)]);415
let response = actions.invoke(sample_request()).await.unwrap();416
assert_eq!(response, InvokeResponse::Empty);417
let sent = actions.transport.sent.lock().unwrap();418
let (request, scope) = &sent[0];419
assert_eq!(420
request.url,421
"https://teams.cloud.microsoft/api/chatsvc/emea/v1/agents/28%3A0000aaaa-0000-0000-0000-000000000001/invoke"422
);423
assert_eq!(scope.resource, IC3);424
assert!(425
request426
.headers427
.contains(&("x-ms-migration".into(), "True".into()))428
);429
assert!(430
request431
.headers432
.contains(&("behavioroverride".into(), "redirectAs404".into()))433
);434
assert_eq!(request.body_tokens[0].resource, SPACES);435
let body = request.body.as_ref().unwrap();436
assert_eq!(body["name"], "messageback");437
assert_eq!(body["appId"], "app-1");438
assert_eq!(body["messageType"], "RichText/Media_Card");439
assert_eq!(body["value"]["type"], "unwatch");440
assert_eq!(body["serverMessageId"], "1700000000001");441
assert_eq!(body["conversation"]["id"], "19:chat@unq.gbl.spaces");442
assert_eq!(body["userAadToken"], request.body_tokens[0].placeholder);443
assert!(body.get("clientMessageId").is_none());444
}445
446
#[tokio::test]447
async fn invoke_keeps_a_known_client_message_id() {448
let actions = canned(vec![(200, Value::Null)]);449
let request = InvokeRequest {450
client_message_id: Some("client-1".into()),451
..sample_request()452
};453
actions.invoke(request).await.unwrap();454
let sent = actions.transport.sent.lock().unwrap();455
assert_eq!(456
sent[0].0.body.as_ref().unwrap()["clientMessageId"],457
"client-1"458
);459
}460
461
#[tokio::test]462
async fn invoke_retries_a_missing_route_in_the_fallback_region() {463
let actions = canned(vec![(404, Value::Null), (200, Value::Null)]);464
actions.invoke(sample_request()).await.unwrap();465
let sent = actions.transport.sent.lock().unwrap();466
assert!(sent[1].0.url.contains("/chatsvc/de/"));467
}468
469
#[tokio::test]470
async fn invoke_failure_is_an_error_without_retry() {471
let actions = canned(vec![(500, json!({"message": "boom"}))]);472
assert!(actions.invoke(sample_request()).await.is_err());473
assert_eq!(actions.transport.sent.lock().unwrap().len(), 1);474
}475
476
#[test]477
fn empty_and_unknown_answers_are_empty() {478
assert_eq!(parse_invoke_response(&Value::Null), InvokeResponse::Empty);479
assert_eq!(parse_invoke_response(&json!("")), InvokeResponse::Empty);480
assert_eq!(481
parse_invoke_response(&json!({"other": 1})),482
InvokeResponse::Empty483
);484
}485
486
#[test]487
fn task_with_a_url() {488
let response = parse_invoke_response(&json!({489
"responseType": "task",490
"task": {"type": "continue", "value": {491
"url": "https://bot.example/task", "fallbackUrl": "https://bot.example/fallback",492
"height": 380, "width": 620, "title": "Settings"493
}}494
}));495
assert_eq!(496
response,497
InvokeResponse::Task(TaskResponse::Continue(TaskContinue {498
title: Some("Settings".into()),499
width: Some(620),500
height: Some(380),501
content: TaskContent::Url {502
url: "https://bot.example/task".into(),503
fallback_url: Some("https://bot.example/fallback".into()),504
},505
}))506
);507
}508
509
#[test]510
fn task_with_a_card_attachment() {511
let response = parse_invoke_response(&json!({512
"task": {"type": "continue", "value": {513
"size": "medium",514
"card": {"contentType": "application/vnd.microsoft.card.adaptive", "content": {"type": "AdaptiveCard"}}515
}}516
}));517
let InvokeResponse::Task(TaskResponse::Continue(task)) = response else {518
panic!("expected a continue task");519
};520
assert_eq!(521
task.content,522
TaskContent::Card(json!({"type": "AdaptiveCard"}))523
);524
assert_eq!(task.width, None);525
}526
527
#[test]528
fn task_message_and_unusable_continue() {529
assert_eq!(530
parse_invoke_response(&json!({"task": {"type": "message", "value": "Done"}})),531
InvokeResponse::Task(TaskResponse::Message("Done".into()))532
);533
assert_eq!(534
parse_invoke_response(&json!({"task": {"type": "continue", "value": {}}})),535
InvokeResponse::Empty536
);537
}538
539
#[test]540
fn universal_action_answers() {541
assert_eq!(542
parse_invoke_response(&json!({543
"statusCode": 200,544
"type": "application/vnd.microsoft.card.adaptive",545
"value": {"type": "AdaptiveCard"}546
})),547
InvokeResponse::Card(json!({"type": "AdaptiveCard"}))548
);549
assert_eq!(550
parse_invoke_response(&json!({551
"statusCode": 200,552
"type": "application/vnd.microsoft.activity.message",553
"value": "Saved"554
})),555
InvokeResponse::Message("Saved".into())556
);557
assert_eq!(558
parse_invoke_response(&json!({"statusCode": 500, "type": "x", "value": "Broken"})),559
InvokeResponse::Failed {560
status_code: 500,561
message: "Broken".into()562
}563
);564
}565
566
#[tokio::test]567
async fn chat_apps_use_the_spaces_scope_and_parse_definitions() {568
let actions = canned(vec![(200, entitlements())]);569
let apps = actions.chat_apps("19:chat@unq.gbl.spaces").await.unwrap();570
assert_eq!(apps.len(), 2);571
let wiki = &apps[0];572
assert_eq!(wiki.name, "Wiki Bot");573
assert_eq!(574
wiki.small_image_url.as_deref(),575
Some("https://cdn.example/small.png")576
);577
assert_eq!(wiki.accent_color.as_deref(), Some("#0052CC"));578
assert_eq!(579
wiki.web_application_resource.as_deref(),580
Some("https://bot.example")581
);582
assert!(wiki.has_bot("0000AAAA-0000-0000-0000-000000000001"));583
assert!(wiki.has_bot("28:0000aaaa-0000-0000-0000-000000000001"));584
assert!(!apps[1].has_bot("0000aaaa-0000-0000-0000-000000000001"));585
let sent = actions.transport.sent.lock().unwrap();586
assert_eq!(587
sent[0].0.url,588
"https://teams.cloud.microsoft/api/mt/emea/beta/chats/19%3Achat%40unq.gbl.spaces/apps/chatentitlements"589
);590
assert_eq!(sent[0].1, spaces_scope());591
}592
593
#[test]594
fn entitlements_without_definitions_are_unexpected() {595
assert!(matches!(596
parse_chat_apps(&json!({"value": {}})),597
Err(Error::UnexpectedAnswer(_))598
));599
}600
601
#[test]602
fn bot_ids_convert_both_ways() {603
assert_eq!(bot_mri("abc"), "28:abc");604
assert_eq!(bot_mri("28:abc"), "28:abc");605
assert_eq!(bot_guid("28:abc"), "abc");606
}607
}@@ -1,3 +1,4 @@
1
pub mod cards;
1
2
mod error;
2
3
mod mask;
3
4
pub mod messages;
@@ -5,6 +6,9 @@ pub mod pins;
5
6
pub mod realtime;
6
7
pub mod receipts;
7
8
9
pub use cards::{
10
CardActions, ChatApp, InvokeRequest, InvokeResponse, TaskContent, TaskContinue, TaskResponse,
11
};
8
12
pub use error::{Error, Result};
9
13
pub use mask::mask_conversation_id;
10
14
pub use messages::{ConversationRef, Messages};
@@ -1,3 +1,4 @@1
pub mod cards;1
mod error;2
mod error;2
mod mask;3
mod mask;3
pub mod messages;4
pub mod messages;@@ -5,6 +6,9 @@ pub mod pins;5
pub mod realtime;6
pub mod realtime;6
pub mod receipts;7
pub mod receipts;7
8
9
pub use cards::{10
CardActions, ChatApp, InvokeRequest, InvokeResponse, TaskContent, TaskContinue, TaskResponse,11
};8
pub use error::{Error, Result};12
pub use error::{Error, Result};9
pub use mask::mask_conversation_id;13
pub use mask::mask_conversation_id;10
pub use messages::{ConversationRef, Messages};14
pub use messages::{ConversationRef, Messages};@@ -1,4 +1,6 @@
1
use serde_json::Value;
1
use std::collections::HashMap;
2
3
use serde_json::{Map, Value, json};
2
4
3
5
use crate::markdown::markdown_to_html;
4
6
use crate::spans::{Span, html_to_spans};
@@ -8,6 +10,15 @@ const SUPPORTED_URL_SCHEMES: [&str; 2] = ["https://", "http://"];
8
10
const IMAGE_URL_SCHEME: &str = "https://";
9
11
const ACTION_TYPE_PREFIX: &str = "Action.";
10
12
const OPEN_URL_ACTION: &str = "Action.OpenUrl";
13
const SUBMIT_ACTION: &str = "Action.Submit";
14
const EXECUTE_ACTION: &str = "Action.Execute";
15
const SHOW_CARD_ACTION: &str = "Action.ShowCard";
16
const TOGGLE_VISIBILITY_ACTION: &str = "Action.ToggleVisibility";
17
const TEAMS_SETTINGS_KEY: &str = "msteams";
18
pub const CARD_THEME: &str = "dark";
19
const MESSAGE_BACK_NAME: &str = "messageback";
20
const TASK_FETCH_NAME: &str = "task/fetch";
21
const EXECUTE_NAME: &str = "adaptiveCard/action";
11
22
const PIXEL_SUFFIX: &str = "px";
12
23
13
24
#[derive(Debug, Clone, PartialEq)]
@@ -19,6 +30,8 @@ pub struct AdaptiveCard {
19
30
20
31
#[derive(Debug, Clone, PartialEq)]
21
32
pub struct CardItem {
33
pub id: Option<String>,
34
pub visible: bool,
22
35
pub separator: bool,
23
36
pub spacing: CardSpacing,
24
37
pub element: CardElement,
@@ -137,24 +150,128 @@ pub struct CardFact {
137
150
138
151
#[derive(Debug, Clone, PartialEq)]
139
152
pub struct CardAction {
153
pub id: Option<String>,
140
154
pub title: String,
141
155
pub kind: CardActionKind,
156
pub enabled: bool,
157
pub visible: bool,
142
158
}
143
159
144
#[derive(Debug, Clone, PartialEq, Eq)]
160
#[derive(Debug, Clone, PartialEq)]
145
161
pub enum CardActionKind {
146
162
OpenUrl(String),
163
Submit(SubmitAction),
164
Execute(ExecuteAction),
165
ShowCard(Box<AdaptiveCard>),
166
ToggleVisibility(Vec<ToggleTarget>),
147
167
Unsupported,
148
168
}
149
169
170
#[derive(Debug, Clone, PartialEq, Eq)]
171
pub struct SubmitAction {
172
pub data: Value,
173
}
174
175
#[derive(Debug, Clone, PartialEq, Eq)]
176
pub struct ExecuteAction {
177
pub id: Option<String>,
178
pub verb: String,
179
pub data: Value,
180
}
181
182
#[derive(Debug, Clone, PartialEq, Eq)]
183
pub struct ToggleTarget {
184
pub element_id: String,
185
pub visible: Option<bool>,
186
}
187
188
#[derive(Debug, Clone, PartialEq)]
189
pub struct InvokePayload {
190
pub name: &'static str,
191
pub value: Value,
192
}
193
194
impl SubmitAction {
195
fn teams_settings(&self) -> Option<&Value> {
196
self.data.get(TEAMS_SETTINGS_KEY)
197
}
198
199
pub fn is_task_fetch(&self) -> bool {
200
self.teams_settings()
201
.and_then(|settings| string_field(settings, "type"))
202
.is_some_and(|kind| kind == TASK_FETCH_NAME)
203
}
204
205
pub fn payload(&self) -> InvokePayload {
206
if self.is_task_fetch() {
207
let mut data = self.data.as_object().cloned().unwrap_or_default();
208
data.remove(TEAMS_SETTINGS_KEY);
209
data.insert("type".to_owned(), json!(TASK_FETCH_NAME));
210
return InvokePayload {
211
name: TASK_FETCH_NAME,
212
value: task_value(Value::Object(data)),
213
};
214
}
215
let message_back = self
216
.teams_settings()
217
.filter(|settings| {
218
string_field(settings, "type").is_some_and(|kind| {
219
kind.eq_ignore_ascii_case("messageBack") || kind.eq_ignore_ascii_case("imBack")
220
})
221
})
222
.and_then(|settings| settings.get("value"));
223
InvokePayload {
224
name: MESSAGE_BACK_NAME,
225
value: message_back.unwrap_or(&self.data).clone(),
226
}
227
}
228
}
229
230
impl ExecuteAction {
231
pub fn payload(&self) -> InvokePayload {
232
let mut action = Map::new();
233
action.insert("type".to_owned(), json!(EXECUTE_ACTION));
234
if let Some(id) = &self.id {
235
action.insert("id".to_owned(), json!(id));
236
}
237
action.insert("verb".to_owned(), json!(self.verb));
238
action.insert("data".to_owned(), self.data.clone());
239
InvokePayload {
240
name: EXECUTE_NAME,
241
value: json!({"action": action, "trigger": "manual"}),
242
}
243
}
244
}
245
246
pub fn task_value(data: Value) -> Value {
247
json!({"data": data, "context": {"theme": CARD_THEME}})
248
}
249
250
impl CardAction {
251
pub fn invoke_payload(&self) -> Option<InvokePayload> {
252
match &self.kind {
253
CardActionKind::Submit(submit) => Some(submit.payload()),
254
CardActionKind::Execute(execute) => Some(execute.payload()),
255
_ => None,
256
}
257
}
258
259
pub fn is_clickable(&self) -> bool {
260
self.enabled && !matches!(self.kind, CardActionKind::Unsupported)
261
}
262
}
263
150
264
impl AdaptiveCard {
151
265
pub fn parse(content: &str) -> Option<AdaptiveCard> {
152
let root: Value = serde_json::from_str(content).ok()?;
266
Self::from_value(&serde_json::from_str(content).ok()?)
267
}
268
269
fn from_value(root: &Value) -> Option<AdaptiveCard> {
153
270
let object = root.as_object()?;
154
271
let mut items = parse_items(object.get("body"));
155
272
let actions = parse_actions(object.get("actions"));
156
273
if items.is_empty()
157
&& let Some(item) = fallback_item(&root)
274
&& let Some(item) = fallback_item(root)
158
275
{
159
276
items.push(item);
160
277
}
@@ -172,6 +289,13 @@ impl AdaptiveCard {
172
289
})
173
290
}
174
291
292
/// Initial visibility of every element and action that has an id, nested cards included.
293
pub fn element_visibility(&self) -> HashMap<String, bool> {
294
let mut visibility = HashMap::new();
295
collect_visibility(&self.items, &self.actions, &mut visibility);
296
visibility
297
}
298
175
299
pub fn plain_text(&self) -> Option<String> {
176
300
let mut lines = Vec::new();
177
301
collect_lines(&self.items, &mut lines);
@@ -179,12 +303,40 @@ impl AdaptiveCard {
179
303
}
180
304
}
181
305
306
fn collect_visibility(
307
items: &[CardItem],
308
actions: &[CardAction],
309
visibility: &mut HashMap<String, bool>,
310
) {
311
for item in items {
312
if let Some(id) = &item.id {
313
visibility.insert(id.clone(), item.visible);
314
}
315
match &item.element {
316
CardElement::Columns(columns) => columns
317
.iter()
318
.for_each(|column| collect_visibility(&column.items, &[], visibility)),
319
CardElement::Container { items, .. } => collect_visibility(items, &[], visibility),
320
CardElement::Actions(actions) => collect_visibility(&[], actions, visibility),
321
_ => {}
322
}
323
}
324
for action in actions {
325
if let Some(id) = &action.id {
326
visibility.insert(id.clone(), action.visible);
327
}
328
if let CardActionKind::ShowCard(card) = &action.kind {
329
collect_visibility(&card.items, &card.actions, visibility);
330
}
331
}
332
}
333
182
334
pub fn card_content_text(content: &str) -> Option<String> {
183
335
AdaptiveCard::parse(content)?.plain_text()
184
336
}
185
337
186
338
fn collect_lines(items: &[CardItem], lines: &mut Vec<String>) {
187
for item in items {
339
for item in items.iter().filter(|item| item.visible) {
188
340
match &item.element {
189
341
CardElement::Text(text) => push_line(lines, &text.spans),
190
342
CardElement::Columns(columns) => columns
@@ -222,7 +374,9 @@ fn parse_items(value: Option<&Value>) -> Vec<CardItem> {
222
374
}
223
375
224
376
fn parse_item(value: &Value) -> Option<CardItem> {
225
if !is_visible(value) {
377
let id = string_field(value, "id").map(str::to_owned);
378
let visible = is_visible(value);
379
if !visible && id.is_none() {
226
380
return None;
227
381
}
228
382
let element = match string_field(value, "type")? {
@@ -238,6 +392,8 @@ fn parse_item(value: &Value) -> Option<CardItem> {
238
392
};
239
393
let element = element.or_else(|| fallback_item(value).map(|item| item.element))?;
240
394
Some(CardItem {
395
id,
396
visible,
241
397
separator: value
242
398
.get("separator")
243
399
.and_then(Value::as_bool)
@@ -250,6 +406,8 @@ fn parse_item(value: &Value) -> Option<CardItem> {
250
406
fn fallback_item(value: &Value) -> Option<CardItem> {
251
407
let text = string_field(value, "fallbackText").filter(|text| !text.trim().is_empty())?;
252
408
Some(CardItem {
409
id: None,
410
visible: true,
253
411
separator: false,
254
412
spacing: CardSpacing::Default,
255
413
element: CardElement::Text(plain_text_block(vec![Span::Text(text.to_owned())])),
@@ -410,7 +568,9 @@ fn parse_actions(value: Option<&Value>) -> Vec<CardAction> {
410
568
}
411
569
412
570
fn parse_action(value: &Value) -> Option<CardAction> {
413
if !is_visible(value) {
571
let id = string_field(value, "id").map(str::to_owned);
572
let visible = is_visible(value);
573
if !visible && id.is_none() {
414
574
return None;
415
575
}
416
576
let action_type = string_field(value, "type")?;
@@ -420,18 +580,67 @@ fn parse_action(value: &Value) -> Option<CardAction> {
420
580
let title = string_field(value, "title")
421
581
.map(str::trim)
422
582
.filter(|title| !title.is_empty())?;
423
let kind = match string_field(value, "url") {
424
Some(url) if action_type == OPEN_URL_ACTION && is_supported_url(url) => {
425
CardActionKind::OpenUrl(url.to_owned())
583
let data = || value.get("data").cloned().unwrap_or(Value::Null);
584
let kind = match action_type {
585
OPEN_URL_ACTION => string_field(value, "url")
586
.filter(|url| is_supported_url(url))
587
.map_or(CardActionKind::Unsupported, |url| {
588
CardActionKind::OpenUrl(url.to_owned())
589
}),
590
SUBMIT_ACTION => CardActionKind::Submit(SubmitAction { data: data() }),
591
EXECUTE_ACTION => string_field(value, "verb").map_or(CardActionKind::Unsupported, |verb| {
592
CardActionKind::Execute(ExecuteAction {
593
id: id.clone(),
594
verb: verb.to_owned(),
595
data: data(),
596
})
597
}),
598
SHOW_CARD_ACTION => value
599
.get("card")
600
.and_then(AdaptiveCard::from_value)
601
.map_or(CardActionKind::Unsupported, |card| {
602
CardActionKind::ShowCard(Box::new(card))
603
}),
604
TOGGLE_VISIBILITY_ACTION => {
605
let targets = parse_toggle_targets(value.get("targetElements"));
606
if targets.is_empty() {
607
CardActionKind::Unsupported
608
} else {
609
CardActionKind::ToggleVisibility(targets)
610
}
426
611
}
427
612
_ => CardActionKind::Unsupported,
428
613
};
429
614
Some(CardAction {
615
id,
430
616
title: title.to_owned(),
431
617
kind,
618
enabled: value
619
.get("isEnabled")
620
.and_then(Value::as_bool)
621
.unwrap_or(true),
622
visible,
432
623
})
433
624
}
434
625
626
fn parse_toggle_targets(value: Option<&Value>) -> Vec<ToggleTarget> {
627
value
628
.and_then(Value::as_array)
629
.into_iter()
630
.flatten()
631
.filter_map(|target| match target.as_str() {
632
Some(element_id) => Some(ToggleTarget {
633
element_id: element_id.to_owned(),
634
visible: None,
635
}),
636
None => Some(ToggleTarget {
637
element_id: string_field(target, "elementId")?.to_owned(),
638
visible: target.get("isVisible").and_then(Value::as_bool),
639
}),
640
})
641
.collect()
642
}
643
435
644
fn is_bold_weight(weight: &str) -> bool {
436
645
weight.eq_ignore_ascii_case("bolder") || weight.eq_ignore_ascii_case("bold")
437
646
}
@@ -1,4 +1,6 @@1
use serde_json::Value;1
use std::collections::HashMap;2
3
use serde_json::{Map, Value, json};2
4
3
use crate::markdown::markdown_to_html;5
use crate::markdown::markdown_to_html;4
use crate::spans::{Span, html_to_spans};6
use crate::spans::{Span, html_to_spans};@@ -8,6 +10,15 @@ const SUPPORTED_URL_SCHEMES: [&str; 2] = ["https://", "http://"];8
const IMAGE_URL_SCHEME: &str = "https://";10
const IMAGE_URL_SCHEME: &str = "https://";9
const ACTION_TYPE_PREFIX: &str = "Action.";11
const ACTION_TYPE_PREFIX: &str = "Action.";10
const OPEN_URL_ACTION: &str = "Action.OpenUrl";12
const OPEN_URL_ACTION: &str = "Action.OpenUrl";13
const SUBMIT_ACTION: &str = "Action.Submit";14
const EXECUTE_ACTION: &str = "Action.Execute";15
const SHOW_CARD_ACTION: &str = "Action.ShowCard";16
const TOGGLE_VISIBILITY_ACTION: &str = "Action.ToggleVisibility";17
const TEAMS_SETTINGS_KEY: &str = "msteams";18
pub const CARD_THEME: &str = "dark";19
const MESSAGE_BACK_NAME: &str = "messageback";20
const TASK_FETCH_NAME: &str = "task/fetch";21
const EXECUTE_NAME: &str = "adaptiveCard/action";11
const PIXEL_SUFFIX: &str = "px";22
const PIXEL_SUFFIX: &str = "px";12
23
13
#[derive(Debug, Clone, PartialEq)]24
#[derive(Debug, Clone, PartialEq)]@@ -19,6 +30,8 @@ pub struct AdaptiveCard {19
30
20
#[derive(Debug, Clone, PartialEq)]31
#[derive(Debug, Clone, PartialEq)]21
pub struct CardItem {32
pub struct CardItem {33
pub id: Option<String>,34
pub visible: bool,22
pub separator: bool,35
pub separator: bool,23
pub spacing: CardSpacing,36
pub spacing: CardSpacing,24
pub element: CardElement,37
pub element: CardElement,@@ -137,24 +150,128 @@ pub struct CardFact {137
150
138
#[derive(Debug, Clone, PartialEq)]151
#[derive(Debug, Clone, PartialEq)]139
pub struct CardAction {152
pub struct CardAction {153
pub id: Option<String>,140
pub title: String,154
pub title: String,141
pub kind: CardActionKind,155
pub kind: CardActionKind,156
pub enabled: bool,157
pub visible: bool,142
}158
}143
159
144
#[derive(Debug, Clone, PartialEq, Eq)]160
#[derive(Debug, Clone, PartialEq)]145
pub enum CardActionKind {161
pub enum CardActionKind {146
OpenUrl(String),162
OpenUrl(String),163
Submit(SubmitAction),164
Execute(ExecuteAction),165
ShowCard(Box<AdaptiveCard>),166
ToggleVisibility(Vec<ToggleTarget>),147
Unsupported,167
Unsupported,148
}168
}149
169
170
#[derive(Debug, Clone, PartialEq, Eq)]171
pub struct SubmitAction {172
pub data: Value,173
}174
175
#[derive(Debug, Clone, PartialEq, Eq)]176
pub struct ExecuteAction {177
pub id: Option<String>,178
pub verb: String,179
pub data: Value,180
}181
182
#[derive(Debug, Clone, PartialEq, Eq)]183
pub struct ToggleTarget {184
pub element_id: String,185
pub visible: Option<bool>,186
}187
188
#[derive(Debug, Clone, PartialEq)]189
pub struct InvokePayload {190
pub name: &'static str,191
pub value: Value,192
}193
194
impl SubmitAction {195
fn teams_settings(&self) -> Option<&Value> {196
self.data.get(TEAMS_SETTINGS_KEY)197
}198
199
pub fn is_task_fetch(&self) -> bool {200
self.teams_settings()201
.and_then(|settings| string_field(settings, "type"))202
.is_some_and(|kind| kind == TASK_FETCH_NAME)203
}204
205
pub fn payload(&self) -> InvokePayload {206
if self.is_task_fetch() {207
let mut data = self.data.as_object().cloned().unwrap_or_default();208
data.remove(TEAMS_SETTINGS_KEY);209
data.insert("type".to_owned(), json!(TASK_FETCH_NAME));210
return InvokePayload {211
name: TASK_FETCH_NAME,212
value: task_value(Value::Object(data)),213
};214
}215
let message_back = self216
.teams_settings()217
.filter(|settings| {218
string_field(settings, "type").is_some_and(|kind| {219
kind.eq_ignore_ascii_case("messageBack") || kind.eq_ignore_ascii_case("imBack")220
})221
})222
.and_then(|settings| settings.get("value"));223
InvokePayload {224
name: MESSAGE_BACK_NAME,225
value: message_back.unwrap_or(&self.data).clone(),226
}227
}228
}229
230
impl ExecuteAction {231
pub fn payload(&self) -> InvokePayload {232
let mut action = Map::new();233
action.insert("type".to_owned(), json!(EXECUTE_ACTION));234
if let Some(id) = &self.id {235
action.insert("id".to_owned(), json!(id));236
}237
action.insert("verb".to_owned(), json!(self.verb));238
action.insert("data".to_owned(), self.data.clone());239
InvokePayload {240
name: EXECUTE_NAME,241
value: json!({"action": action, "trigger": "manual"}),242
}243
}244
}245
246
pub fn task_value(data: Value) -> Value {247
json!({"data": data, "context": {"theme": CARD_THEME}})248
}249
250
impl CardAction {251
pub fn invoke_payload(&self) -> Option<InvokePayload> {252
match &self.kind {253
CardActionKind::Submit(submit) => Some(submit.payload()),254
CardActionKind::Execute(execute) => Some(execute.payload()),255
_ => None,256
}257
}258
259
pub fn is_clickable(&self) -> bool {260
self.enabled && !matches!(self.kind, CardActionKind::Unsupported)261
}262
}263
150
impl AdaptiveCard {264
impl AdaptiveCard {151
pub fn parse(content: &str) -> Option<AdaptiveCard> {265
pub fn parse(content: &str) -> Option<AdaptiveCard> {152
let root: Value = serde_json::from_str(content).ok()?;266
Self::from_value(&serde_json::from_str(content).ok()?)267
}268
269
fn from_value(root: &Value) -> Option<AdaptiveCard> {153
let object = root.as_object()?;270
let object = root.as_object()?;154
let mut items = parse_items(object.get("body"));271
let mut items = parse_items(object.get("body"));155
let actions = parse_actions(object.get("actions"));272
let actions = parse_actions(object.get("actions"));156
if items.is_empty()273
if items.is_empty()157
&& let Some(item) = fallback_item(&root)274
&& let Some(item) = fallback_item(root)158
{275
{159
items.push(item);276
items.push(item);160
}277
}@@ -172,6 +289,13 @@ impl AdaptiveCard {172
})289
})173
}290
}174
291
292
/// Initial visibility of every element and action that has an id, nested cards included.293
pub fn element_visibility(&self) -> HashMap<String, bool> {294
let mut visibility = HashMap::new();295
collect_visibility(&self.items, &self.actions, &mut visibility);296
visibility297
}298
175
pub fn plain_text(&self) -> Option<String> {299
pub fn plain_text(&self) -> Option<String> {176
let mut lines = Vec::new();300
let mut lines = Vec::new();177
collect_lines(&self.items, &mut lines);301
collect_lines(&self.items, &mut lines);@@ -179,12 +303,40 @@ impl AdaptiveCard {179
}303
}180
}304
}181
305
306
fn collect_visibility(307
items: &[CardItem],308
actions: &[CardAction],309
visibility: &mut HashMap<String, bool>,310
) {311
for item in items {312
if let Some(id) = &item.id {313
visibility.insert(id.clone(), item.visible);314
}315
match &item.element {316
CardElement::Columns(columns) => columns317
.iter()318
.for_each(|column| collect_visibility(&column.items, &[], visibility)),319
CardElement::Container { items, .. } => collect_visibility(items, &[], visibility),320
CardElement::Actions(actions) => collect_visibility(&[], actions, visibility),321
_ => {}322
}323
}324
for action in actions {325
if let Some(id) = &action.id {326
visibility.insert(id.clone(), action.visible);327
}328
if let CardActionKind::ShowCard(card) = &action.kind {329
collect_visibility(&card.items, &card.actions, visibility);330
}331
}332
}333
182
pub fn card_content_text(content: &str) -> Option<String> {334
pub fn card_content_text(content: &str) -> Option<String> {183
AdaptiveCard::parse(content)?.plain_text()335
AdaptiveCard::parse(content)?.plain_text()184
}336
}185
337
186
fn collect_lines(items: &[CardItem], lines: &mut Vec<String>) {338
fn collect_lines(items: &[CardItem], lines: &mut Vec<String>) {187
for item in items {339
for item in items.iter().filter(|item| item.visible) {188
match &item.element {340
match &item.element {189
CardElement::Text(text) => push_line(lines, &text.spans),341
CardElement::Text(text) => push_line(lines, &text.spans),190
CardElement::Columns(columns) => columns342
CardElement::Columns(columns) => columns@@ -222,7 +374,9 @@ fn parse_items(value: Option<&Value>) -> Vec<CardItem> {222
}374
}223
375
224
fn parse_item(value: &Value) -> Option<CardItem> {376
fn parse_item(value: &Value) -> Option<CardItem> {225
if !is_visible(value) {377
let id = string_field(value, "id").map(str::to_owned);378
let visible = is_visible(value);379
if !visible && id.is_none() {226
return None;380
return None;227
}381
}228
let element = match string_field(value, "type")? {382
let element = match string_field(value, "type")? {@@ -238,6 +392,8 @@ fn parse_item(value: &Value) -> Option<CardItem> {238
};392
};239
let element = element.or_else(|| fallback_item(value).map(|item| item.element))?;393
let element = element.or_else(|| fallback_item(value).map(|item| item.element))?;240
Some(CardItem {394
Some(CardItem {395
id,396
visible,241
separator: value397
separator: value242
.get("separator")398
.get("separator")243
.and_then(Value::as_bool)399
.and_then(Value::as_bool)@@ -250,6 +406,8 @@ fn parse_item(value: &Value) -> Option<CardItem> {250
fn fallback_item(value: &Value) -> Option<CardItem> {406
fn fallback_item(value: &Value) -> Option<CardItem> {251
let text = string_field(value, "fallbackText").filter(|text| !text.trim().is_empty())?;407
let text = string_field(value, "fallbackText").filter(|text| !text.trim().is_empty())?;252
Some(CardItem {408
Some(CardItem {409
id: None,410
visible: true,253
separator: false,411
separator: false,254
spacing: CardSpacing::Default,412
spacing: CardSpacing::Default,255
element: CardElement::Text(plain_text_block(vec![Span::Text(text.to_owned())])),413
element: CardElement::Text(plain_text_block(vec![Span::Text(text.to_owned())])),@@ -410,7 +568,9 @@ fn parse_actions(value: Option<&Value>) -> Vec<CardAction> {410
}568
}411
569
412
fn parse_action(value: &Value) -> Option<CardAction> {570
fn parse_action(value: &Value) -> Option<CardAction> {413
if !is_visible(value) {571
let id = string_field(value, "id").map(str::to_owned);572
let visible = is_visible(value);573
if !visible && id.is_none() {414
return None;574
return None;415
}575
}416
let action_type = string_field(value, "type")?;576
let action_type = string_field(value, "type")?;@@ -420,18 +580,67 @@ fn parse_action(value: &Value) -> Option<CardAction> {420
let title = string_field(value, "title")580
let title = string_field(value, "title")421
.map(str::trim)581
.map(str::trim)422
.filter(|title| !title.is_empty())?;582
.filter(|title| !title.is_empty())?;423
let kind = match string_field(value, "url") {583
let data = || value.get("data").cloned().unwrap_or(Value::Null);424
Some(url) if action_type == OPEN_URL_ACTION && is_supported_url(url) => {584
let kind = match action_type {425
CardActionKind::OpenUrl(url.to_owned())585
OPEN_URL_ACTION => string_field(value, "url")586
.filter(|url| is_supported_url(url))587
.map_or(CardActionKind::Unsupported, |url| {588
CardActionKind::OpenUrl(url.to_owned())589
}),590
SUBMIT_ACTION => CardActionKind::Submit(SubmitAction { data: data() }),591
EXECUTE_ACTION => string_field(value, "verb").map_or(CardActionKind::Unsupported, |verb| {592
CardActionKind::Execute(ExecuteAction {593
id: id.clone(),594
verb: verb.to_owned(),595
data: data(),596
})597
}),598
SHOW_CARD_ACTION => value599
.get("card")600
.and_then(AdaptiveCard::from_value)601
.map_or(CardActionKind::Unsupported, |card| {602
CardActionKind::ShowCard(Box::new(card))603
}),604
TOGGLE_VISIBILITY_ACTION => {605
let targets = parse_toggle_targets(value.get("targetElements"));606
if targets.is_empty() {607
CardActionKind::Unsupported608
} else {609
CardActionKind::ToggleVisibility(targets)610
}426
}611
}427
_ => CardActionKind::Unsupported,612
_ => CardActionKind::Unsupported,428
};613
};429
Some(CardAction {614
Some(CardAction {615
id,430
title: title.to_owned(),616
title: title.to_owned(),431
kind,617
kind,618
enabled: value619
.get("isEnabled")620
.and_then(Value::as_bool)621
.unwrap_or(true),622
visible,432
})623
})433
}624
}434
625
626
fn parse_toggle_targets(value: Option<&Value>) -> Vec<ToggleTarget> {627
value628
.and_then(Value::as_array)629
.into_iter()630
.flatten()631
.filter_map(|target| match target.as_str() {632
Some(element_id) => Some(ToggleTarget {633
element_id: element_id.to_owned(),634
visible: None,635
}),636
None => Some(ToggleTarget {637
element_id: string_field(target, "elementId")?.to_owned(),638
visible: target.get("isVisible").and_then(Value::as_bool),639
}),640
})641
.collect()642
}643
435
fn is_bold_weight(weight: &str) -> bool {644
fn is_bold_weight(weight: &str) -> bool {436
weight.eq_ignore_ascii_case("bolder") || weight.eq_ignore_ascii_case("bold")645
weight.eq_ignore_ascii_case("bolder") || weight.eq_ignore_ascii_case("bold")437
}646
}@@ -0,0 +1,186 @@
1
use chatsvc::{ChatApp, InvokeRequest, InvokeResponse, TaskContent, TaskContinue, TaskResponse};
2
use serde_json::Value;
3
4
use crate::adaptive_card::{CardAction, task_value};
5
use crate::engine::SyncEngine;
6
use crate::error::{Error, Result};
7
use crate::receipts::locked;
8
use crate::remote::Remote;
9
10
const TASK_SUBMIT_NAME: &str = "task/submit";
11
const DEFAULT_DIALOG_WIDTH: u32 = 520;
12
const DEFAULT_DIALOG_HEIGHT: u32 = 400;
13
const MAX_FAILURE_CHARS: usize = 200;
14
15
#[derive(Debug, Clone, PartialEq)]
16
pub enum CardActionOutcome {
17
Sent,
18
ReplaceCard(String),
19
Dialog(TaskDialog),
20
Message(String),
21
Failed(String),
22
}
23
24
#[derive(Debug, Clone, PartialEq)]
25
pub struct TaskDialog {
26
pub title: Option<String>,
27
pub width: u32,
28
pub height: u32,
29
pub kind: TaskDialogKind,
30
}
31
32
#[derive(Debug, Clone, PartialEq)]
33
pub enum TaskDialogKind {
34
Url { url: String, fallback_url: String },
35
Card(String),
36
}
37
38
#[derive(Debug, Clone, PartialEq, Eq)]
39
pub struct DialogIdentity {
40
pub user_id: String,
41
pub display_name: String,
42
pub tenant_id: String,
43
}
44
45
impl<R: Remote> SyncEngine<R> {
46
/// Cached per conversation after the first successful lookup.
47
pub async fn chat_apps(&self, conversation_id: &str) -> Result<Vec<ChatApp>> {
48
if let Some(cached) = locked(&self.chat_apps).get(conversation_id) {
49
return Ok(cached.clone());
50
}
51
let apps = self.remote.chat_apps(conversation_id).await?;
52
locked(&self.chat_apps).insert(conversation_id.to_owned(), apps.clone());
53
Ok(apps)
54
}
55
56
pub fn cached_chat_apps(&self, conversation_id: &str) -> Option<Vec<ChatApp>> {
57
locked(&self.chat_apps).get(conversation_id).cloned()
58
}
59
60
pub async fn dialog_identity(&self, conversation_id: &str) -> Result<DialogIdentity> {
61
let user_id = self.my_user_id().await?;
62
self.ensure_display_name().await?;
63
let tenant_id = self.my_tenant_id(conversation_id).await?;
64
Ok(DialogIdentity {
65
user_id,
66
display_name: self.me().map(|me| me.display_name).unwrap_or_default(),
67
tenant_id,
68
})
69
}
70
71
pub async fn card_action(
72
&self,
73
conversation_id: &str,
74
message_id: &str,
75
action: &CardAction,
76
) -> Result<CardActionOutcome> {
77
let payload = action
78
.invoke_payload()
79
.ok_or(Error::Unsupported("this card action"))?;
80
self.invoke_card(conversation_id, message_id, payload.name, payload.value)
81
.await
82
}
83
84
pub async fn task_submit(
85
&self,
86
conversation_id: &str,
87
message_id: &str,
88
data: Value,
89
) -> Result<CardActionOutcome> {
90
self.invoke_card(
91
conversation_id,
92
message_id,
93
TASK_SUBMIT_NAME,
94
task_value(data),
95
)
96
.await
97
}
98
99
async fn invoke_card(
100
&self,
101
conversation_id: &str,
102
message_id: &str,
103
name: &str,
104
value: Value,
105
) -> Result<CardActionOutcome> {
106
let (app, bot_id) = self.card_app(conversation_id, message_id).await?;
107
self.ensure_display_name().await?;
108
let display_name = self.me().map(|me| me.display_name).unwrap_or_default();
109
let response = self
110
.remote
111
.invoke_card(InvokeRequest {
112
bot_id,
113
app_id: app.app_id,
114
name: name.to_owned(),
115
value,
116
display_name,
117
server_message_id: message_id.to_owned(),
118
client_message_id: None,
119
conversation_id: conversation_id.to_owned(),
120
})
121
.await?;
122
Ok(outcome_of(response))
123
}
124
125
pub async fn card_app(
126
&self,
127
conversation_id: &str,
128
message_id: &str,
129
) -> Result<(ChatApp, String)> {
130
let sender_application_id = self
131
.store
132
.messages_by_id(conversation_id, &[message_id.to_owned()])?
133
.remove(message_id)
134
.and_then(|record| record.sender_application_id);
135
let apps = self.chat_apps(conversation_id).await?;
136
let matched = sender_application_id.as_deref().and_then(|sender| {
137
apps.iter()
138
.find(|app| app.has_bot(sender) || app.app_id == sender)
139
});
140
let mut with_bots = apps.iter().filter(|app| !app.bot_ids.is_empty());
141
let app = match (matched, with_bots.next(), with_bots.next()) {
142
(Some(app), _, _) | (None, Some(app), None) => app,
143
_ => return Err(Error::Unsupported("a card from an unknown app")),
144
};
145
let bot_id = sender_application_id
146
.filter(|sender| app.has_bot(sender))
147
.or_else(|| app.bot_ids.first().cloned())
148
.ok_or(Error::Unsupported("a card from an app without a bot"))?;
149
Ok((app.clone(), bot_id))
150
}
151
}
152
153
fn outcome_of(response: InvokeResponse) -> CardActionOutcome {
154
match response {
155
InvokeResponse::Empty => CardActionOutcome::Sent,
156
InvokeResponse::Card(card) => CardActionOutcome::ReplaceCard(card.to_string()),
157
InvokeResponse::Message(text) | InvokeResponse::Task(TaskResponse::Message(text)) => {
158
CardActionOutcome::Message(text)
159
}
160
InvokeResponse::Task(TaskResponse::Continue(task)) => {
161
CardActionOutcome::Dialog(dialog_of(task))
162
}
163
InvokeResponse::Failed {
164
status_code,
165
message,
166
} => {
167
let detail: String = message.chars().take(MAX_FAILURE_CHARS).collect();
168
CardActionOutcome::Failed(format!("The app answered {status_code}: {detail}"))
169
}
170
}
171
}
172
173
fn dialog_of(task: TaskContinue) -> TaskDialog {
174
TaskDialog {
175
title: task.title,
176
width: task.width.unwrap_or(DEFAULT_DIALOG_WIDTH),
177
height: task.height.unwrap_or(DEFAULT_DIALOG_HEIGHT),
178
kind: match task.content {
179
TaskContent::Url { url, fallback_url } => TaskDialogKind::Url {
180
fallback_url: fallback_url.unwrap_or_else(|| url.clone()),
181
url,
182
},
183
TaskContent::Card(card) => TaskDialogKind::Card(card.to_string()),
184
},
185
}
186
}
@@ -0,0 +1,186 @@1
use chatsvc::{ChatApp, InvokeRequest, InvokeResponse, TaskContent, TaskContinue, TaskResponse};2
use serde_json::Value;3
4
use crate::adaptive_card::{CardAction, task_value};5
use crate::engine::SyncEngine;6
use crate::error::{Error, Result};7
use crate::receipts::locked;8
use crate::remote::Remote;9
10
const TASK_SUBMIT_NAME: &str = "task/submit";11
const DEFAULT_DIALOG_WIDTH: u32 = 520;12
const DEFAULT_DIALOG_HEIGHT: u32 = 400;13
const MAX_FAILURE_CHARS: usize = 200;14
15
#[derive(Debug, Clone, PartialEq)]16
pub enum CardActionOutcome {17
Sent,18
ReplaceCard(String),19
Dialog(TaskDialog),20
Message(String),21
Failed(String),22
}23
24
#[derive(Debug, Clone, PartialEq)]25
pub struct TaskDialog {26
pub title: Option<String>,27
pub width: u32,28
pub height: u32,29
pub kind: TaskDialogKind,30
}31
32
#[derive(Debug, Clone, PartialEq)]33
pub enum TaskDialogKind {34
Url { url: String, fallback_url: String },35
Card(String),36
}37
38
#[derive(Debug, Clone, PartialEq, Eq)]39
pub struct DialogIdentity {40
pub user_id: String,41
pub display_name: String,42
pub tenant_id: String,43
}44
45
impl<R: Remote> SyncEngine<R> {46
/// Cached per conversation after the first successful lookup.47
pub async fn chat_apps(&self, conversation_id: &str) -> Result<Vec<ChatApp>> {48
if let Some(cached) = locked(&self.chat_apps).get(conversation_id) {49
return Ok(cached.clone());50
}51
let apps = self.remote.chat_apps(conversation_id).await?;52
locked(&self.chat_apps).insert(conversation_id.to_owned(), apps.clone());53
Ok(apps)54
}55
56
pub fn cached_chat_apps(&self, conversation_id: &str) -> Option<Vec<ChatApp>> {57
locked(&self.chat_apps).get(conversation_id).cloned()58
}59
60
pub async fn dialog_identity(&self, conversation_id: &str) -> Result<DialogIdentity> {61
let user_id = self.my_user_id().await?;62
self.ensure_display_name().await?;63
let tenant_id = self.my_tenant_id(conversation_id).await?;64
Ok(DialogIdentity {65
user_id,66
display_name: self.me().map(|me| me.display_name).unwrap_or_default(),67
tenant_id,68
})69
}70
71
pub async fn card_action(72
&self,73
conversation_id: &str,74
message_id: &str,75
action: &CardAction,76
) -> Result<CardActionOutcome> {77
let payload = action78
.invoke_payload()79
.ok_or(Error::Unsupported("this card action"))?;80
self.invoke_card(conversation_id, message_id, payload.name, payload.value)81
.await82
}83
84
pub async fn task_submit(85
&self,86
conversation_id: &str,87
message_id: &str,88
data: Value,89
) -> Result<CardActionOutcome> {90
self.invoke_card(91
conversation_id,92
message_id,93
TASK_SUBMIT_NAME,94
task_value(data),95
)96
.await97
}98
99
async fn invoke_card(100
&self,101
conversation_id: &str,102
message_id: &str,103
name: &str,104
value: Value,105
) -> Result<CardActionOutcome> {106
let (app, bot_id) = self.card_app(conversation_id, message_id).await?;107
self.ensure_display_name().await?;108
let display_name = self.me().map(|me| me.display_name).unwrap_or_default();109
let response = self110
.remote111
.invoke_card(InvokeRequest {112
bot_id,113
app_id: app.app_id,114
name: name.to_owned(),115
value,116
display_name,117
server_message_id: message_id.to_owned(),118
client_message_id: None,119
conversation_id: conversation_id.to_owned(),120
})121
.await?;122
Ok(outcome_of(response))123
}124
125
pub async fn card_app(126
&self,127
conversation_id: &str,128
message_id: &str,129
) -> Result<(ChatApp, String)> {130
let sender_application_id = self131
.store132
.messages_by_id(conversation_id, &[message_id.to_owned()])?133
.remove(message_id)134
.and_then(|record| record.sender_application_id);135
let apps = self.chat_apps(conversation_id).await?;136
let matched = sender_application_id.as_deref().and_then(|sender| {137
apps.iter()138
.find(|app| app.has_bot(sender) || app.app_id == sender)139
});140
let mut with_bots = apps.iter().filter(|app| !app.bot_ids.is_empty());141
let app = match (matched, with_bots.next(), with_bots.next()) {142
(Some(app), _, _) | (None, Some(app), None) => app,143
_ => return Err(Error::Unsupported("a card from an unknown app")),144
};145
let bot_id = sender_application_id146
.filter(|sender| app.has_bot(sender))147
.or_else(|| app.bot_ids.first().cloned())148
.ok_or(Error::Unsupported("a card from an app without a bot"))?;149
Ok((app.clone(), bot_id))150
}151
}152
153
fn outcome_of(response: InvokeResponse) -> CardActionOutcome {154
match response {155
InvokeResponse::Empty => CardActionOutcome::Sent,156
InvokeResponse::Card(card) => CardActionOutcome::ReplaceCard(card.to_string()),157
InvokeResponse::Message(text) | InvokeResponse::Task(TaskResponse::Message(text)) => {158
CardActionOutcome::Message(text)159
}160
InvokeResponse::Task(TaskResponse::Continue(task)) => {161
CardActionOutcome::Dialog(dialog_of(task))162
}163
InvokeResponse::Failed {164
status_code,165
message,166
} => {167
let detail: String = message.chars().take(MAX_FAILURE_CHARS).collect();168
CardActionOutcome::Failed(format!("The app answered {status_code}: {detail}"))169
}170
}171
}172
173
fn dialog_of(task: TaskContinue) -> TaskDialog {174
TaskDialog {175
title: task.title,176
width: task.width.unwrap_or(DEFAULT_DIALOG_WIDTH),177
height: task.height.unwrap_or(DEFAULT_DIALOG_HEIGHT),178
kind: match task.content {179
TaskContent::Url { url, fallback_url } => TaskDialogKind::Url {180
fallback_url: fallback_url.unwrap_or_else(|| url.clone()),181
url,182
},183
TaskContent::Card(card) => TaskDialogKind::Card(card.to_string()),184
},185
}186
}@@ -2,7 +2,7 @@ use std::collections::{HashMap, HashSet};
2
2
use std::sync::atomic::{AtomicBool, Ordering};
3
3
use std::sync::{Arc, Mutex};
4
4
5
use chatsvc::TrouterEndpoint;
5
use chatsvc::{ChatApp, TrouterEndpoint};
6
6
use chrono::{DateTime, Duration, Utc};
7
7
use graph::{DriveFolder, Graph, MESSAGE_PAGE_SIZE, Message};
8
8
use store::{ImageFileCache, MessageRecord, Sidebar, Store, SyncState};
@@ -122,6 +122,7 @@ pub struct SyncEngine<R: Remote = Graph> {
122
122
preview_changed: AtomicBool,
123
123
pub(crate) receipts: ReceiptCache,
124
124
pub(crate) channel_folders: Mutex<HashMap<String, DriveFolder>>,
125
pub(crate) chat_apps: Mutex<HashMap<String, Vec<ChatApp>>>,
125
126
}
126
127
127
128
impl<R: Remote> SyncEngine<R> {
@@ -149,6 +150,7 @@ impl<R: Remote> SyncEngine<R> {
149
150
preview_changed: AtomicBool::new(false),
150
151
receipts: ReceiptCache::default(),
151
152
channel_folders: Mutex::new(HashMap::new()),
153
chat_apps: Mutex::new(HashMap::new()),
152
154
}
153
155
}
154
156
@@ -2,7 +2,7 @@ use std::collections::{HashMap, HashSet};2
use std::sync::atomic::{AtomicBool, Ordering};2
use std::sync::atomic::{AtomicBool, Ordering};3
use std::sync::{Arc, Mutex};3
use std::sync::{Arc, Mutex};4
4
5
use chatsvc::TrouterEndpoint;5
use chatsvc::{ChatApp, TrouterEndpoint};6
use chrono::{DateTime, Duration, Utc};6
use chrono::{DateTime, Duration, Utc};7
use graph::{DriveFolder, Graph, MESSAGE_PAGE_SIZE, Message};7
use graph::{DriveFolder, Graph, MESSAGE_PAGE_SIZE, Message};8
use store::{ImageFileCache, MessageRecord, Sidebar, Store, SyncState};8
use store::{ImageFileCache, MessageRecord, Sidebar, Store, SyncState};@@ -122,6 +122,7 @@ pub struct SyncEngine<R: Remote = Graph> {122
preview_changed: AtomicBool,122
preview_changed: AtomicBool,123
pub(crate) receipts: ReceiptCache,123
pub(crate) receipts: ReceiptCache,124
pub(crate) channel_folders: Mutex<HashMap<String, DriveFolder>>,124
pub(crate) channel_folders: Mutex<HashMap<String, DriveFolder>>,125
pub(crate) chat_apps: Mutex<HashMap<String, Vec<ChatApp>>>,125
}126
}126
127
127
impl<R: Remote> SyncEngine<R> {128
impl<R: Remote> SyncEngine<R> {@@ -149,6 +150,7 @@ impl<R: Remote> SyncEngine<R> {149
preview_changed: AtomicBool::new(false),150
preview_changed: AtomicBool::new(false),150
receipts: ReceiptCache::default(),151
receipts: ReceiptCache::default(),151
channel_folders: Mutex::new(HashMap::new()),152
channel_folders: Mutex::new(HashMap::new()),153
chat_apps: Mutex::new(HashMap::new()),152
}154
}153
}155
}154
156
@@ -1,6 +1,7 @@
1
1
mod actions;
2
2
mod adaptive_card;
3
3
mod avatars;
4
mod card_actions;
4
5
mod channel_sync;
5
6
mod download;
6
7
mod draft;
@@ -24,11 +25,14 @@ mod spans;
24
25
mod stored;
25
26
26
27
pub use adaptive_card::{
27
AdaptiveCard, CardAction, CardActionKind, CardColumn, CardElement, CardFact, CardImage,
28
CardItem, CardSpacing, CardText, ColumnWidth, ContainerStyle, ImageSize, TextColor, TextSize,
29
VerticalAlignment, card_content_text,
28
AdaptiveCard, CARD_THEME, CardAction, CardActionKind, CardColumn, CardElement, CardFact,
29
CardImage, CardItem, CardSpacing, CardText, ColumnWidth, ContainerStyle, ExecuteAction,
30
ImageSize, InvokePayload, SubmitAction, TextColor, TextSize, ToggleTarget, VerticalAlignment,
31
card_content_text, task_value,
30
32
};
31
33
pub use avatars::Avatar;
34
pub use card_actions::{CardActionOutcome, DialogIdentity, TaskDialog, TaskDialogKind};
35
pub use chatsvc::ChatApp;
32
36
pub use draft::{
33
37
Draft, DraftLine, Edit, FormatState, LineKind, MAX_DEPTH, Mark, MarkKind, OBJECT_MARK,
34
38
TypingStyle, changed_span, has_markdown, link_url, map_offset, reverse_edits,
@@ -1,6 +1,7 @@1
mod actions;1
mod actions;2
mod adaptive_card;2
mod adaptive_card;3
mod avatars;3
mod avatars;4
mod card_actions;4
mod channel_sync;5
mod channel_sync;5
mod download;6
mod download;6
mod draft;7
mod draft;@@ -24,11 +25,14 @@ mod spans;24
mod stored;25
mod stored;25
26
26
pub use adaptive_card::{27
pub use adaptive_card::{27
AdaptiveCard, CardAction, CardActionKind, CardColumn, CardElement, CardFact, CardImage,28
AdaptiveCard, CARD_THEME, CardAction, CardActionKind, CardColumn, CardElement, CardFact,28
CardItem, CardSpacing, CardText, ColumnWidth, ContainerStyle, ImageSize, TextColor, TextSize,29
CardImage, CardItem, CardSpacing, CardText, ColumnWidth, ContainerStyle, ExecuteAction,29
VerticalAlignment, card_content_text,30
ImageSize, InvokePayload, SubmitAction, TextColor, TextSize, ToggleTarget, VerticalAlignment,31
card_content_text, task_value,30
};32
};31
pub use avatars::Avatar;33
pub use avatars::Avatar;34
pub use card_actions::{CardActionOutcome, DialogIdentity, TaskDialog, TaskDialogKind};35
pub use chatsvc::ChatApp;32
pub use draft::{36
pub use draft::{33
Draft, DraftLine, Edit, FormatState, LineKind, MAX_DEPTH, Mark, MarkKind, OBJECT_MARK,37
Draft, DraftLine, Edit, FormatState, LineKind, MAX_DEPTH, Mark, MarkKind, OBJECT_MARK,34
TypingStyle, changed_span, has_markdown, link_url, map_offset, reverse_edits,38
TypingStyle, changed_span, has_markdown, link_url, map_offset, reverse_edits,@@ -129,6 +129,9 @@ pub fn message_record(conversation_id: &str, message: &Message) -> Option<Messag
129
129
sender_name: sender
130
130
.and_then(|sender| sender.display_name())
131
131
.map(str::to_owned),
132
sender_application_id: sender
133
.and_then(|sender| sender.application_id())
134
.map(str::to_owned),
132
135
created_at,
133
136
edited_at: message.last_edited_date_time,
134
137
deleted,
@@ -129,6 +129,9 @@ pub fn message_record(conversation_id: &str, message: &Message) -> Option<Messag129
sender_name: sender129
sender_name: sender130
.and_then(|sender| sender.display_name())130
.and_then(|sender| sender.display_name())131
.map(str::to_owned),131
.map(str::to_owned),132
sender_application_id: sender133
.and_then(|sender| sender.application_id())134
.map(str::to_owned),132
created_at,135
created_at,133
edited_at: message.last_edited_date_time,136
edited_at: message.last_edited_date_time,134
deleted,137
deleted,@@ -1,4 +1,7 @@
1
use chatsvc::{ConversationRef, MemberHorizon, Messages, Receipts};
1
use chatsvc::{
2
CardActions, ChatApp, ConversationRef, InvokeRequest, InvokeResponse, MemberHorizon, Messages,
3
Receipts,
4
};
2
5
use chrono::{DateTime, Utc};
3
6
use graph::{
4
7
Channel, Chat, DriveFolder, Graph, Member, Message, MessageExtras, MessageTarget,
@@ -193,6 +196,14 @@ pub trait Remote {
193
196
async fn consumption_horizons(&self, _conversation_id: &str) -> Result<Vec<MemberHorizon>> {
194
197
Err(Error::Unsupported("read receipts"))
195
198
}
199
200
async fn chat_apps(&self, _chat_id: &str) -> Result<Vec<ChatApp>> {
201
Err(Error::Unsupported("chat apps"))
202
}
203
204
async fn invoke_card(&self, _invoke: InvokeRequest) -> Result<InvokeResponse> {
205
Err(Error::Unsupported("card actions"))
206
}
196
207
}
197
208
198
209
impl Remote for Graph {
@@ -486,6 +497,14 @@ impl Remote for Graph {
486
497
.consumption_horizons(conversation_id)
487
498
.await?)
488
499
}
500
501
async fn chat_apps(&self, chat_id: &str) -> Result<Vec<ChatApp>> {
502
Ok(CardActions::new(self.session()).chat_apps(chat_id).await?)
503
}
504
505
async fn invoke_card(&self, invoke: InvokeRequest) -> Result<InvokeResponse> {
506
Ok(CardActions::new(self.session()).invoke(invoke).await?)
507
}
489
508
}
490
509
491
510
fn chatsvc_conversation(target: &MessageTarget) -> Option<ConversationRef> {
@@ -1,4 +1,7 @@1
use chatsvc::{ConversationRef, MemberHorizon, Messages, Receipts};1
use chatsvc::{2
CardActions, ChatApp, ConversationRef, InvokeRequest, InvokeResponse, MemberHorizon, Messages,3
Receipts,4
};2
use chrono::{DateTime, Utc};5
use chrono::{DateTime, Utc};3
use graph::{6
use graph::{4
Channel, Chat, DriveFolder, Graph, Member, Message, MessageExtras, MessageTarget,7
Channel, Chat, DriveFolder, Graph, Member, Message, MessageExtras, MessageTarget,@@ -193,6 +196,14 @@ pub trait Remote {193
async fn consumption_horizons(&self, _conversation_id: &str) -> Result<Vec<MemberHorizon>> {196
async fn consumption_horizons(&self, _conversation_id: &str) -> Result<Vec<MemberHorizon>> {194
Err(Error::Unsupported("read receipts"))197
Err(Error::Unsupported("read receipts"))195
}198
}199
200
async fn chat_apps(&self, _chat_id: &str) -> Result<Vec<ChatApp>> {201
Err(Error::Unsupported("chat apps"))202
}203
204
async fn invoke_card(&self, _invoke: InvokeRequest) -> Result<InvokeResponse> {205
Err(Error::Unsupported("card actions"))206
}196
}207
}197
208
198
impl Remote for Graph {209
impl Remote for Graph {@@ -486,6 +497,14 @@ impl Remote for Graph {486
.consumption_horizons(conversation_id)497
.consumption_horizons(conversation_id)487
.await?)498
.await?)488
}499
}500
501
async fn chat_apps(&self, chat_id: &str) -> Result<Vec<ChatApp>> {502
Ok(CardActions::new(self.session()).chat_apps(chat_id).await?)503
}504
505
async fn invoke_card(&self, invoke: InvokeRequest) -> Result<InvokeResponse> {506
Ok(CardActions::new(self.session()).invoke(invoke).await?)507
}489
}508
}490
509
491
fn chatsvc_conversation(target: &MessageTarget) -> Option<ConversationRef> {510
fn chatsvc_conversation(target: &MessageTarget) -> Option<ConversationRef> {@@ -552,6 +552,7 @@ mod tests {
552
552
reply_to_id: None,
553
553
sender_id: Some("u".to_owned()),
554
554
sender_name: None,
555
sender_application_id: None,
555
556
created_at: Utc::now(),
556
557
edited_at: None,
557
558
deleted: false,
@@ -552,6 +552,7 @@ mod tests {552
reply_to_id: None,552
reply_to_id: None,553
sender_id: Some("u".to_owned()),553
sender_id: Some("u".to_owned()),554
sender_name: None,554
sender_name: None,555
sender_application_id: None,555
created_at: Utc::now(),556
created_at: Utc::now(),556
edited_at: None,557
edited_at: None,557
deleted: false,558
deleted: false,@@ -1,7 +1,7 @@
1
1
use serde_json::json;
2
2
use teams_core::{
3
AdaptiveCard, CardActionKind, CardElement, ColumnWidth, ImageSize, Span, TextColor, TextSize,
4
VerticalAlignment, card_content_text,
3
AdaptiveCard, CardAction, CardActionKind, CardElement, ColumnWidth, ImageSize, Span, TextColor,
4
TextSize, ToggleTarget, VerticalAlignment, card_content_text,
5
5
};
6
6
7
7
fn digest_card() -> String {
@@ -92,9 +92,126 @@ fn digest_card_keeps_layout_text_and_actions() {
92
92
);
93
93
assert_eq!(actions[1].kind, CardActionKind::Unsupported);
94
94
assert_eq!(actions[2].title, "Watch");
95
let CardActionKind::Submit(submit) = &actions[2].kind else {
96
panic!("watch is a submit action");
97
};
98
assert_eq!(submit.data, json!({"action": "watch"}));
99
assert!(actions[2].is_clickable());
100
}
101
102
fn card_actions(actions: serde_json::Value) -> Vec<CardAction> {
103
let card = json!({"body": [{"type": "TextBlock", "text": "x"}], "actions": actions});
104
AdaptiveCard::parse(&card.to_string()).unwrap().actions
105
}
106
107
#[test]
108
fn plain_submit_sends_its_data_as_a_message_back() {
109
let actions = card_actions(json!([
110
{"type": "Action.Submit", "title": "Unwatch", "data": {"type": "unwatch", "page": "p1"}}
111
]));
112
let payload = actions[0].invoke_payload().unwrap();
113
assert_eq!(payload.name, "messageback");
114
assert_eq!(payload.value, json!({"type": "unwatch", "page": "p1"}));
115
}
116
117
#[test]
118
fn task_fetch_submit_wraps_data_without_the_teams_settings() {
119
let actions = card_actions(json!([
120
{"type": "Action.Submit", "title": "Bell", "data": {"cardType": "n", "msteams": {"type": "task/fetch"}}}
121
]));
122
let payload = actions[0].invoke_payload().unwrap();
123
assert_eq!(payload.name, "task/fetch");
124
assert_eq!(
125
payload.value,
126
json!({"data": {"cardType": "n", "type": "task/fetch"}, "context": {"theme": "dark"}})
127
);
128
}
129
130
#[test]
131
fn message_back_and_im_back_send_the_teams_value() {
132
let actions = card_actions(json!([
133
{"type": "Action.Submit", "title": "A", "data": {"msteams": {"type": "messageBack", "value": {"k": 1}}}},
134
{"type": "Action.Submit", "title": "B", "data": {"msteams": {"type": "imBack"}, "k": 2}}
135
]));
136
let first = actions[0].invoke_payload().unwrap();
137
assert_eq!((first.name, first.value), ("messageback", json!({"k": 1})));
138
let second = actions[1].invoke_payload().unwrap();
139
assert_eq!(second.value, json!({"msteams": {"type": "imBack"}, "k": 2}));
140
}
141
142
#[test]
143
fn execute_action_carries_verb_id_and_data() {
144
let actions = card_actions(json!([
145
{"type": "Action.Execute", "id": "a1", "title": "Approve", "verb": "approve", "data": {"n": 3}},
146
{"type": "Action.Execute", "title": "No verb"}
147
]));
148
let payload = actions[0].invoke_payload().unwrap();
149
assert_eq!(payload.name, "adaptiveCard/action");
150
assert_eq!(
151
payload.value,
152
json!({
153
"action": {"type": "Action.Execute", "id": "a1", "verb": "approve", "data": {"n": 3}},
154
"trigger": "manual"
155
})
156
);
157
assert_eq!(actions[1].kind, CardActionKind::Unsupported);
158
}
159
160
#[test]
161
fn show_card_and_toggle_actions_are_parsed_locally() {
162
let actions = card_actions(json!([
163
{"type": "Action.ShowCard", "title": "More", "card": {"body": [{"type": "TextBlock", "text": "nested"}]}},
164
{"type": "Action.ToggleVisibility", "title": "Toggle", "targetElements": ["a", {"elementId": "b", "isVisible": true}]},
165
{"type": "Action.ToggleVisibility", "title": "Empty", "targetElements": []}
166
]));
167
let CardActionKind::ShowCard(nested) = &actions[0].kind else {
168
panic!("show card expected");
169
};
170
assert_eq!(nested.plain_text().as_deref(), Some("nested"));
171
assert!(actions[0].invoke_payload().is_none());
172
assert_eq!(
173
actions[1].kind,
174
CardActionKind::ToggleVisibility(vec![
175
ToggleTarget {
176
element_id: "a".to_owned(),
177
visible: None
178
},
179
ToggleTarget {
180
element_id: "b".to_owned(),
181
visible: Some(true)
182
},
183
])
184
);
95
185
assert_eq!(actions[2].kind, CardActionKind::Unsupported);
96
186
}
97
187
188
#[test]
189
fn disabled_actions_stay_disabled_and_hidden_ones_need_an_id() {
190
let actions = card_actions(json!([
191
{"type": "Action.Submit", "title": "Off", "isEnabled": false, "data": {}},
192
{"type": "Action.Submit", "title": "Gone", "isVisible": false},
193
{"type": "Action.Submit", "title": "Later", "id": "later", "isVisible": false}
194
]));
195
assert_eq!(actions.len(), 2);
196
assert!(!actions[0].is_clickable());
197
assert!(!actions[1].visible);
198
assert_eq!(actions[1].id.as_deref(), Some("later"));
199
}
200
201
#[test]
202
fn toggled_items_keep_their_id_and_stay_out_of_the_text() {
203
let card = json!({"body": [
204
{"type": "TextBlock", "text": "shown"},
205
{"type": "TextBlock", "id": "details", "isVisible": false, "text": "secret"}
206
]})
207
.to_string();
208
let parsed = AdaptiveCard::parse(&card).unwrap();
209
assert_eq!(parsed.items.len(), 2);
210
assert_eq!(parsed.items[1].id.as_deref(), Some("details"));
211
assert!(!parsed.items[1].visible);
212
assert_eq!(parsed.plain_text().as_deref(), Some("shown"));
213
}
214
98
215
#[test]
99
216
fn plain_text_drops_urls_images_and_buttons() {
100
217
assert_eq!(
@@ -151,3 +268,28 @@ fn cards_without_content_are_none() {
151
268
assert!(AdaptiveCard::parse(r#"{"body": []}"#).is_none());
152
269
assert!(AdaptiveCard::parse("[1]").is_none());
153
270
}
271
272
#[test]
273
fn element_visibility_covers_items_actions_and_nested_cards() {
274
let card = json!({
275
"body": [
276
{"type": "TextBlock", "id": "title", "text": "t"},
277
{"type": "Container", "items": [
278
{"type": "TextBlock", "id": "details", "isVisible": false, "text": "d"}
279
]},
280
{"type": "ActionSet", "actions": [
281
{"type": "Action.Submit", "id": "later", "isVisible": false, "title": "Later"},
282
{"type": "Action.ShowCard", "title": "More", "card": {"body": [
283
{"type": "TextBlock", "id": "nested", "isVisible": false, "text": "n"}
284
]}}
285
]}
286
]
287
})
288
.to_string();
289
let visibility = AdaptiveCard::parse(&card).unwrap().element_visibility();
290
assert_eq!(visibility.len(), 4);
291
assert!(visibility["title"]);
292
assert!(!visibility["details"]);
293
assert!(!visibility["later"]);
294
assert!(!visibility["nested"]);
295
}
@@ -1,7 +1,7 @@1
use serde_json::json;1
use serde_json::json;2
use teams_core::{2
use teams_core::{3
AdaptiveCard, CardActionKind, CardElement, ColumnWidth, ImageSize, Span, TextColor, TextSize,3
AdaptiveCard, CardAction, CardActionKind, CardElement, ColumnWidth, ImageSize, Span, TextColor,4
VerticalAlignment, card_content_text,4
TextSize, ToggleTarget, VerticalAlignment, card_content_text,5
};5
};6
6
7
fn digest_card() -> String {7
fn digest_card() -> String {@@ -92,9 +92,126 @@ fn digest_card_keeps_layout_text_and_actions() {92
);92
);93
assert_eq!(actions[1].kind, CardActionKind::Unsupported);93
assert_eq!(actions[1].kind, CardActionKind::Unsupported);94
assert_eq!(actions[2].title, "Watch");94
assert_eq!(actions[2].title, "Watch");95
let CardActionKind::Submit(submit) = &actions[2].kind else {96
panic!("watch is a submit action");97
};98
assert_eq!(submit.data, json!({"action": "watch"}));99
assert!(actions[2].is_clickable());100
}101
102
fn card_actions(actions: serde_json::Value) -> Vec<CardAction> {103
let card = json!({"body": [{"type": "TextBlock", "text": "x"}], "actions": actions});104
AdaptiveCard::parse(&card.to_string()).unwrap().actions105
}106
107
#[test]108
fn plain_submit_sends_its_data_as_a_message_back() {109
let actions = card_actions(json!([110
{"type": "Action.Submit", "title": "Unwatch", "data": {"type": "unwatch", "page": "p1"}}111
]));112
let payload = actions[0].invoke_payload().unwrap();113
assert_eq!(payload.name, "messageback");114
assert_eq!(payload.value, json!({"type": "unwatch", "page": "p1"}));115
}116
117
#[test]118
fn task_fetch_submit_wraps_data_without_the_teams_settings() {119
let actions = card_actions(json!([120
{"type": "Action.Submit", "title": "Bell", "data": {"cardType": "n", "msteams": {"type": "task/fetch"}}}121
]));122
let payload = actions[0].invoke_payload().unwrap();123
assert_eq!(payload.name, "task/fetch");124
assert_eq!(125
payload.value,126
json!({"data": {"cardType": "n", "type": "task/fetch"}, "context": {"theme": "dark"}})127
);128
}129
130
#[test]131
fn message_back_and_im_back_send_the_teams_value() {132
let actions = card_actions(json!([133
{"type": "Action.Submit", "title": "A", "data": {"msteams": {"type": "messageBack", "value": {"k": 1}}}},134
{"type": "Action.Submit", "title": "B", "data": {"msteams": {"type": "imBack"}, "k": 2}}135
]));136
let first = actions[0].invoke_payload().unwrap();137
assert_eq!((first.name, first.value), ("messageback", json!({"k": 1})));138
let second = actions[1].invoke_payload().unwrap();139
assert_eq!(second.value, json!({"msteams": {"type": "imBack"}, "k": 2}));140
}141
142
#[test]143
fn execute_action_carries_verb_id_and_data() {144
let actions = card_actions(json!([145
{"type": "Action.Execute", "id": "a1", "title": "Approve", "verb": "approve", "data": {"n": 3}},146
{"type": "Action.Execute", "title": "No verb"}147
]));148
let payload = actions[0].invoke_payload().unwrap();149
assert_eq!(payload.name, "adaptiveCard/action");150
assert_eq!(151
payload.value,152
json!({153
"action": {"type": "Action.Execute", "id": "a1", "verb": "approve", "data": {"n": 3}},154
"trigger": "manual"155
})156
);157
assert_eq!(actions[1].kind, CardActionKind::Unsupported);158
}159
160
#[test]161
fn show_card_and_toggle_actions_are_parsed_locally() {162
let actions = card_actions(json!([163
{"type": "Action.ShowCard", "title": "More", "card": {"body": [{"type": "TextBlock", "text": "nested"}]}},164
{"type": "Action.ToggleVisibility", "title": "Toggle", "targetElements": ["a", {"elementId": "b", "isVisible": true}]},165
{"type": "Action.ToggleVisibility", "title": "Empty", "targetElements": []}166
]));167
let CardActionKind::ShowCard(nested) = &actions[0].kind else {168
panic!("show card expected");169
};170
assert_eq!(nested.plain_text().as_deref(), Some("nested"));171
assert!(actions[0].invoke_payload().is_none());172
assert_eq!(173
actions[1].kind,174
CardActionKind::ToggleVisibility(vec![175
ToggleTarget {176
element_id: "a".to_owned(),177
visible: None178
},179
ToggleTarget {180
element_id: "b".to_owned(),181
visible: Some(true)182
},183
])184
);95
assert_eq!(actions[2].kind, CardActionKind::Unsupported);185
assert_eq!(actions[2].kind, CardActionKind::Unsupported);96
}186
}97
187
188
#[test]189
fn disabled_actions_stay_disabled_and_hidden_ones_need_an_id() {190
let actions = card_actions(json!([191
{"type": "Action.Submit", "title": "Off", "isEnabled": false, "data": {}},192
{"type": "Action.Submit", "title": "Gone", "isVisible": false},193
{"type": "Action.Submit", "title": "Later", "id": "later", "isVisible": false}194
]));195
assert_eq!(actions.len(), 2);196
assert!(!actions[0].is_clickable());197
assert!(!actions[1].visible);198
assert_eq!(actions[1].id.as_deref(), Some("later"));199
}200
201
#[test]202
fn toggled_items_keep_their_id_and_stay_out_of_the_text() {203
let card = json!({"body": [204
{"type": "TextBlock", "text": "shown"},205
{"type": "TextBlock", "id": "details", "isVisible": false, "text": "secret"}206
]})207
.to_string();208
let parsed = AdaptiveCard::parse(&card).unwrap();209
assert_eq!(parsed.items.len(), 2);210
assert_eq!(parsed.items[1].id.as_deref(), Some("details"));211
assert!(!parsed.items[1].visible);212
assert_eq!(parsed.plain_text().as_deref(), Some("shown"));213
}214
98
#[test]215
#[test]99
fn plain_text_drops_urls_images_and_buttons() {216
fn plain_text_drops_urls_images_and_buttons() {100
assert_eq!(217
assert_eq!(@@ -151,3 +268,28 @@ fn cards_without_content_are_none() {151
assert!(AdaptiveCard::parse(r#"{"body": []}"#).is_none());268
assert!(AdaptiveCard::parse(r#"{"body": []}"#).is_none());152
assert!(AdaptiveCard::parse("[1]").is_none());269
assert!(AdaptiveCard::parse("[1]").is_none());153
}270
}271
272
#[test]273
fn element_visibility_covers_items_actions_and_nested_cards() {274
let card = json!({275
"body": [276
{"type": "TextBlock", "id": "title", "text": "t"},277
{"type": "Container", "items": [278
{"type": "TextBlock", "id": "details", "isVisible": false, "text": "d"}279
]},280
{"type": "ActionSet", "actions": [281
{"type": "Action.Submit", "id": "later", "isVisible": false, "title": "Later"},282
{"type": "Action.ShowCard", "title": "More", "card": {"body": [283
{"type": "TextBlock", "id": "nested", "isVisible": false, "text": "n"}284
]}}285
]}286
]287
})288
.to_string();289
let visibility = AdaptiveCard::parse(&card).unwrap().element_visibility();290
assert_eq!(visibility.len(), 4);291
assert!(visibility["title"]);292
assert!(!visibility["details"]);293
assert!(!visibility["later"]);294
assert!(!visibility["nested"]);295
}@@ -87,6 +87,10 @@ struct Fake {
87
87
directory_users: Mutex<Vec<User>>,
88
88
horizons: Mutex<Vec<chatsvc::MemberHorizon>>,
89
89
horizon_calls: Mutex<usize>,
90
apps: Mutex<Vec<chatsvc::ChatApp>>,
91
app_calls: Mutex<usize>,
92
invokes: Mutex<Vec<chatsvc::InvokeRequest>>,
93
invoke_answer: Mutex<Option<chatsvc::InvokeResponse>>,
90
94
}
91
95
92
96
impl Fake {
@@ -554,6 +558,21 @@ impl Remote for Handle {
554
558
Ok(self.horizons.lock().unwrap().clone())
555
559
}
556
560
561
async fn chat_apps(&self, _chat_id: &str) -> Result<Vec<chatsvc::ChatApp>> {
562
*self.app_calls.lock().unwrap() += 1;
563
Ok(self.apps.lock().unwrap().clone())
564
}
565
566
async fn invoke_card(&self, invoke: chatsvc::InvokeRequest) -> Result<chatsvc::InvokeResponse> {
567
self.invokes.lock().unwrap().push(invoke);
568
Ok(self
569
.invoke_answer
570
.lock()
571
.unwrap()
572
.clone()
573
.unwrap_or(chatsvc::InvokeResponse::Empty))
574
}
575
557
576
async fn presences(&self, user_ids: &[String]) -> Result<Vec<Presence>> {
558
577
let answers = self.presence_answers.lock().unwrap();
559
578
Ok(answers
@@ -2617,3 +2636,230 @@ async fn reconnect_refetches_known_chats_only() {
2617
2636
CoreEvent::ReceiptsChanged { .. }
2618
2637
));
2619
2638
}
2639
2640
const BOT_GUID: &str = "0000aaaa-0000-0000-0000-000000000001";
2641
2642
fn chat_app(app_id: &str, name: &str, bot_ids: &[&str]) -> chatsvc::ChatApp {
2643
chatsvc::ChatApp {
2644
app_id: app_id.to_owned(),
2645
name: name.to_owned(),
2646
bot_ids: bot_ids.iter().map(|bot| (*bot).to_owned()).collect(),
2647
small_image_url: None,
2648
accent_color: None,
2649
web_application_resource: None,
2650
}
2651
}
2652
2653
fn bot_message(application_id: &str) -> Message {
2654
serde_json::from_value(json!({
2655
"id": "m0001",
2656
"messageType": "message",
2657
"createdDateTime": base().to_rfc3339(),
2658
"from": {"application": {"id": application_id, "displayName": "Wiki Bot"}},
2659
"body": {"contentType": "html", "content": "<attachment id=\"a1\"></attachment>"},
2660
}))
2661
.unwrap()
2662
}
2663
2664
async fn card_engine(fake: &Arc<Fake>, application_id: &str) -> SyncEngine<Handle> {
2665
let engine = chat_engine(fake, small_pages()).await;
2666
fake.set_chat_messages(vec![bot_message(application_id)]);
2667
engine.fetch_newer(CHAT).await.unwrap();
2668
engine
2669
}
2670
2671
fn submit_action(data: serde_json::Value) -> teams_core::CardAction {
2672
let card = json!({"body": [{"type": "TextBlock", "text": "x"}], "actions": [
2673
{"type": "Action.Submit", "title": "Go", "data": data}
2674
]});
2675
teams_core::AdaptiveCard::parse(&card.to_string())
2676
.unwrap()
2677
.actions
2678
.remove(0)
2679
}
2680
2681
#[tokio::test]
2682
async fn card_submit_invokes_the_matching_bot_and_caches_the_apps() {
2683
let fake = Arc::new(Fake::default());
2684
*fake.apps.lock().unwrap() = vec![
2685
chat_app(
2686
"app-other",
2687
"Other",
2688
&["0000bbbb-0000-0000-0000-000000000002"],
2689
),
2690
chat_app("app-wiki", "Wiki", &[BOT_GUID]),
2691
];
2692
let engine = card_engine(&fake, BOT_GUID).await;
2693
let action = submit_action(json!({"type": "unwatch"}));
2694
2695
let first = engine.card_action(CHAT, "m0001", &action).await.unwrap();
2696
let second = engine.card_action(CHAT, "m0001", &action).await.unwrap();
2697
2698
assert_eq!(first, teams_core::CardActionOutcome::Sent);
2699
assert_eq!(second, first);
2700
assert_eq!(*fake.app_calls.lock().unwrap(), 1);
2701
let invokes = fake.invokes.lock().unwrap();
2702
assert_eq!(invokes[0].app_id, "app-wiki");
2703
assert_eq!(invokes[0].bot_id, BOT_GUID);
2704
assert_eq!(invokes[0].name, "messageback");
2705
assert_eq!(invokes[0].value, json!({"type": "unwatch"}));
2706
assert_eq!(invokes[0].server_message_id, "m0001");
2707
assert_eq!(invokes[0].conversation_id, CHAT);
2708
assert_eq!(invokes[0].display_name, "Me Myself");
2709
}
2710
2711
#[tokio::test]
2712
async fn card_action_falls_back_to_the_only_bot_app() {
2713
let fake = Arc::new(Fake::default());
2714
*fake.apps.lock().unwrap() = vec![
2715
chat_app("app-tabs", "Tabs", &[]),
2716
chat_app("app-wiki", "Wiki", &[BOT_GUID]),
2717
];
2718
let engine = card_engine(&fake, "unrelated-id").await;
2719
engine
2720
.card_action(CHAT, "m0001", &submit_action(json!({})))
2721
.await
2722
.unwrap();
2723
let invokes = fake.invokes.lock().unwrap();
2724
assert_eq!(invokes[0].app_id, "app-wiki");
2725
assert_eq!(invokes[0].bot_id, BOT_GUID);
2726
}
2727
2728
#[tokio::test]
2729
async fn card_action_with_several_unmatched_bot_apps_is_an_error() {
2730
let fake = Arc::new(Fake::default());
2731
*fake.apps.lock().unwrap() = vec![
2732
chat_app("app-one", "One", &["bot-1"]),
2733
chat_app("app-two", "Two", &["bot-2"]),
2734
];
2735
let engine = card_engine(&fake, "unrelated-id").await;
2736
let outcome = engine
2737
.card_action(CHAT, "m0001", &submit_action(json!({})))
2738
.await;
2739
assert!(outcome.is_err());
2740
assert!(fake.invokes.lock().unwrap().is_empty());
2741
}
2742
2743
#[tokio::test]
2744
async fn card_answers_map_to_outcomes() {
2745
use chatsvc::{InvokeResponse, TaskContent, TaskContinue, TaskResponse};
2746
use teams_core::{CardActionOutcome, TaskDialog, TaskDialogKind};
2747
2748
let fake = Arc::new(Fake::default());
2749
*fake.apps.lock().unwrap() = vec![chat_app("app-wiki", "Wiki", &[BOT_GUID])];
2750
let engine = card_engine(&fake, BOT_GUID).await;
2751
let action = submit_action(json!({"msteams": {"type": "task/fetch"}}));
2752
let answers = [
2753
(
2754
InvokeResponse::Card(json!({"type": "AdaptiveCard"})),
2755
CardActionOutcome::ReplaceCard(json!({"type": "AdaptiveCard"}).to_string()),
2756
),
2757
(
2758
InvokeResponse::Message("Saved".into()),
2759
CardActionOutcome::Message("Saved".into()),
2760
),
2761
(
2762
InvokeResponse::Task(TaskResponse::Message("Done".into())),
2763
CardActionOutcome::Message("Done".into()),
2764
),
2765
(
2766
InvokeResponse::Failed {
2767
status_code: 500,
2768
message: "Broken".into(),
2769
},
2770
CardActionOutcome::Failed("The app answered 500: Broken".into()),
2771
),
2772
(
2773
InvokeResponse::Task(TaskResponse::Continue(TaskContinue {
2774
title: Some("Settings".into()),
2775
width: None,
2776
height: Some(300),
2777
content: TaskContent::Url {
2778
url: "https://bot.example/task".into(),
2779
fallback_url: None,
2780
},
2781
})),
2782
CardActionOutcome::Dialog(TaskDialog {
2783
title: Some("Settings".into()),
2784
width: 520,
2785
height: 300,
2786
kind: TaskDialogKind::Url {
2787
url: "https://bot.example/task".into(),
2788
fallback_url: "https://bot.example/task".into(),
2789
},
2790
}),
2791
),
2792
(
2793
InvokeResponse::Task(TaskResponse::Continue(TaskContinue {
2794
title: None,
2795
width: Some(600),
2796
height: Some(400),
2797
content: TaskContent::Card(json!({"type": "AdaptiveCard"})),
2798
})),
2799
CardActionOutcome::Dialog(TaskDialog {
2800
title: None,
2801
width: 600,
2802
height: 400,
2803
kind: TaskDialogKind::Card(json!({"type": "AdaptiveCard"}).to_string()),
2804
}),
2805
),
2806
];
2807
for (answer, expected) in answers {
2808
*fake.invoke_answer.lock().unwrap() = Some(answer);
2809
assert_eq!(
2810
engine.card_action(CHAT, "m0001", &action).await.unwrap(),
2811
expected
2812
);
2813
}
2814
assert_eq!(fake.invokes.lock().unwrap()[0].name, "task/fetch");
2815
}
2816
2817
#[tokio::test]
2818
async fn task_submit_wraps_the_data_for_the_dialog() {
2819
let fake = Arc::new(Fake::default());
2820
*fake.apps.lock().unwrap() = vec![chat_app("app-wiki", "Wiki", &[BOT_GUID])];
2821
let engine = card_engine(&fake, BOT_GUID).await;
2822
engine
2823
.task_submit(CHAT, "m0001", json!({"choice": "a"}))
2824
.await
2825
.unwrap();
2826
let invokes = fake.invokes.lock().unwrap();
2827
assert_eq!(invokes[0].name, "task/submit");
2828
assert_eq!(
2829
invokes[0].value,
2830
json!({"data": {"choice": "a"}, "context": {"theme": "dark"}})
2831
);
2832
}
2833
2834
#[tokio::test]
2835
async fn dialog_identity_names_the_user_and_the_tenant() {
2836
let fake = Arc::new(Fake::default());
2837
let engine = card_engine(&fake, BOT_GUID).await;
2838
let identity = engine.dialog_identity(CHAT).await.unwrap();
2839
assert_eq!(identity.user_id, ME);
2840
assert_eq!(identity.display_name, "Me Myself");
2841
assert_eq!(identity.tenant_id, "tenant-1");
2842
}
2843
2844
#[tokio::test]
2845
async fn card_actions_without_a_payload_are_rejected() {
2846
let fake = Arc::new(Fake::default());
2847
let engine = card_engine(&fake, BOT_GUID).await;
2848
let card = json!({"body": [{"type": "TextBlock", "text": "x"}], "actions": [
2849
{"type": "Action.OpenUrl", "title": "Open", "url": "https://example.com"}
2850
]});
2851
let action = teams_core::AdaptiveCard::parse(&card.to_string())
2852
.unwrap()
2853
.actions
2854
.remove(0);
2855
assert!(engine.card_action(CHAT, "m0001", &action).await.is_err());
2856
}
2857
2858
#[tokio::test]
2859
async fn bot_messages_remember_their_application() {
2860
let fake = Arc::new(Fake::default());
2861
let engine = card_engine(&fake, BOT_GUID).await;
2862
let record = engine.open_conversation(CHAT).unwrap().remove(0);
2863
assert_eq!(record.sender_application_id.as_deref(), Some(BOT_GUID));
2864
assert_eq!(record.sender_id, None);
2865
}
@@ -87,6 +87,10 @@ struct Fake {87
directory_users: Mutex<Vec<User>>,87
directory_users: Mutex<Vec<User>>,88
horizons: Mutex<Vec<chatsvc::MemberHorizon>>,88
horizons: Mutex<Vec<chatsvc::MemberHorizon>>,89
horizon_calls: Mutex<usize>,89
horizon_calls: Mutex<usize>,90
apps: Mutex<Vec<chatsvc::ChatApp>>,91
app_calls: Mutex<usize>,92
invokes: Mutex<Vec<chatsvc::InvokeRequest>>,93
invoke_answer: Mutex<Option<chatsvc::InvokeResponse>>,90
}94
}91
95
92
impl Fake {96
impl Fake {@@ -554,6 +558,21 @@ impl Remote for Handle {554
Ok(self.horizons.lock().unwrap().clone())558
Ok(self.horizons.lock().unwrap().clone())555
}559
}556
560
561
async fn chat_apps(&self, _chat_id: &str) -> Result<Vec<chatsvc::ChatApp>> {562
*self.app_calls.lock().unwrap() += 1;563
Ok(self.apps.lock().unwrap().clone())564
}565
566
async fn invoke_card(&self, invoke: chatsvc::InvokeRequest) -> Result<chatsvc::InvokeResponse> {567
self.invokes.lock().unwrap().push(invoke);568
Ok(self569
.invoke_answer570
.lock()571
.unwrap()572
.clone()573
.unwrap_or(chatsvc::InvokeResponse::Empty))574
}575
557
async fn presences(&self, user_ids: &[String]) -> Result<Vec<Presence>> {576
async fn presences(&self, user_ids: &[String]) -> Result<Vec<Presence>> {558
let answers = self.presence_answers.lock().unwrap();577
let answers = self.presence_answers.lock().unwrap();559
Ok(answers578
Ok(answers@@ -2617,3 +2636,230 @@ async fn reconnect_refetches_known_chats_only() {2617
CoreEvent::ReceiptsChanged { .. }2636
CoreEvent::ReceiptsChanged { .. }2618
));2637
));2619
}2638
}2639
2640
const BOT_GUID: &str = "0000aaaa-0000-0000-0000-000000000001";2641
2642
fn chat_app(app_id: &str, name: &str, bot_ids: &[&str]) -> chatsvc::ChatApp {2643
chatsvc::ChatApp {2644
app_id: app_id.to_owned(),2645
name: name.to_owned(),2646
bot_ids: bot_ids.iter().map(|bot| (*bot).to_owned()).collect(),2647
small_image_url: None,2648
accent_color: None,2649
web_application_resource: None,2650
}2651
}2652
2653
fn bot_message(application_id: &str) -> Message {2654
serde_json::from_value(json!({2655
"id": "m0001",2656
"messageType": "message",2657
"createdDateTime": base().to_rfc3339(),2658
"from": {"application": {"id": application_id, "displayName": "Wiki Bot"}},2659
"body": {"contentType": "html", "content": "<attachment id=\"a1\"></attachment>"},2660
}))2661
.unwrap()2662
}2663
2664
async fn card_engine(fake: &Arc<Fake>, application_id: &str) -> SyncEngine<Handle> {2665
let engine = chat_engine(fake, small_pages()).await;2666
fake.set_chat_messages(vec![bot_message(application_id)]);2667
engine.fetch_newer(CHAT).await.unwrap();2668
engine2669
}2670
2671
fn submit_action(data: serde_json::Value) -> teams_core::CardAction {2672
let card = json!({"body": [{"type": "TextBlock", "text": "x"}], "actions": [2673
{"type": "Action.Submit", "title": "Go", "data": data}2674
]});2675
teams_core::AdaptiveCard::parse(&card.to_string())2676
.unwrap()2677
.actions2678
.remove(0)2679
}2680
2681
#[tokio::test]2682
async fn card_submit_invokes_the_matching_bot_and_caches_the_apps() {2683
let fake = Arc::new(Fake::default());2684
*fake.apps.lock().unwrap() = vec![2685
chat_app(2686
"app-other",2687
"Other",2688
&["0000bbbb-0000-0000-0000-000000000002"],2689
),2690
chat_app("app-wiki", "Wiki", &[BOT_GUID]),2691
];2692
let engine = card_engine(&fake, BOT_GUID).await;2693
let action = submit_action(json!({"type": "unwatch"}));2694
2695
let first = engine.card_action(CHAT, "m0001", &action).await.unwrap();2696
let second = engine.card_action(CHAT, "m0001", &action).await.unwrap();2697
2698
assert_eq!(first, teams_core::CardActionOutcome::Sent);2699
assert_eq!(second, first);2700
assert_eq!(*fake.app_calls.lock().unwrap(), 1);2701
let invokes = fake.invokes.lock().unwrap();2702
assert_eq!(invokes[0].app_id, "app-wiki");2703
assert_eq!(invokes[0].bot_id, BOT_GUID);2704
assert_eq!(invokes[0].name, "messageback");2705
assert_eq!(invokes[0].value, json!({"type": "unwatch"}));2706
assert_eq!(invokes[0].server_message_id, "m0001");2707
assert_eq!(invokes[0].conversation_id, CHAT);2708
assert_eq!(invokes[0].display_name, "Me Myself");2709
}2710
2711
#[tokio::test]2712
async fn card_action_falls_back_to_the_only_bot_app() {2713
let fake = Arc::new(Fake::default());2714
*fake.apps.lock().unwrap() = vec![2715
chat_app("app-tabs", "Tabs", &[]),2716
chat_app("app-wiki", "Wiki", &[BOT_GUID]),2717
];2718
let engine = card_engine(&fake, "unrelated-id").await;2719
engine2720
.card_action(CHAT, "m0001", &submit_action(json!({})))2721
.await2722
.unwrap();2723
let invokes = fake.invokes.lock().unwrap();2724
assert_eq!(invokes[0].app_id, "app-wiki");2725
assert_eq!(invokes[0].bot_id, BOT_GUID);2726
}2727
2728
#[tokio::test]2729
async fn card_action_with_several_unmatched_bot_apps_is_an_error() {2730
let fake = Arc::new(Fake::default());2731
*fake.apps.lock().unwrap() = vec![2732
chat_app("app-one", "One", &["bot-1"]),2733
chat_app("app-two", "Two", &["bot-2"]),2734
];2735
let engine = card_engine(&fake, "unrelated-id").await;2736
let outcome = engine2737
.card_action(CHAT, "m0001", &submit_action(json!({})))2738
.await;2739
assert!(outcome.is_err());2740
assert!(fake.invokes.lock().unwrap().is_empty());2741
}2742
2743
#[tokio::test]2744
async fn card_answers_map_to_outcomes() {2745
use chatsvc::{InvokeResponse, TaskContent, TaskContinue, TaskResponse};2746
use teams_core::{CardActionOutcome, TaskDialog, TaskDialogKind};2747
2748
let fake = Arc::new(Fake::default());2749
*fake.apps.lock().unwrap() = vec![chat_app("app-wiki", "Wiki", &[BOT_GUID])];2750
let engine = card_engine(&fake, BOT_GUID).await;2751
let action = submit_action(json!({"msteams": {"type": "task/fetch"}}));2752
let answers = [2753
(2754
InvokeResponse::Card(json!({"type": "AdaptiveCard"})),2755
CardActionOutcome::ReplaceCard(json!({"type": "AdaptiveCard"}).to_string()),2756
),2757
(2758
InvokeResponse::Message("Saved".into()),2759
CardActionOutcome::Message("Saved".into()),2760
),2761
(2762
InvokeResponse::Task(TaskResponse::Message("Done".into())),2763
CardActionOutcome::Message("Done".into()),2764
),2765
(2766
InvokeResponse::Failed {2767
status_code: 500,2768
message: "Broken".into(),2769
},2770
CardActionOutcome::Failed("The app answered 500: Broken".into()),2771
),2772
(2773
InvokeResponse::Task(TaskResponse::Continue(TaskContinue {2774
title: Some("Settings".into()),2775
width: None,2776
height: Some(300),2777
content: TaskContent::Url {2778
url: "https://bot.example/task".into(),2779
fallback_url: None,2780
},2781
})),2782
CardActionOutcome::Dialog(TaskDialog {2783
title: Some("Settings".into()),2784
width: 520,2785
height: 300,2786
kind: TaskDialogKind::Url {2787
url: "https://bot.example/task".into(),2788
fallback_url: "https://bot.example/task".into(),2789
},2790
}),2791
),2792
(2793
InvokeResponse::Task(TaskResponse::Continue(TaskContinue {2794
title: None,2795
width: Some(600),2796
height: Some(400),2797
content: TaskContent::Card(json!({"type": "AdaptiveCard"})),2798
})),2799
CardActionOutcome::Dialog(TaskDialog {2800
title: None,2801
width: 600,2802
height: 400,2803
kind: TaskDialogKind::Card(json!({"type": "AdaptiveCard"}).to_string()),2804
}),2805
),2806
];2807
for (answer, expected) in answers {2808
*fake.invoke_answer.lock().unwrap() = Some(answer);2809
assert_eq!(2810
engine.card_action(CHAT, "m0001", &action).await.unwrap(),2811
expected2812
);2813
}2814
assert_eq!(fake.invokes.lock().unwrap()[0].name, "task/fetch");2815
}2816
2817
#[tokio::test]2818
async fn task_submit_wraps_the_data_for_the_dialog() {2819
let fake = Arc::new(Fake::default());2820
*fake.apps.lock().unwrap() = vec![chat_app("app-wiki", "Wiki", &[BOT_GUID])];2821
let engine = card_engine(&fake, BOT_GUID).await;2822
engine2823
.task_submit(CHAT, "m0001", json!({"choice": "a"}))2824
.await2825
.unwrap();2826
let invokes = fake.invokes.lock().unwrap();2827
assert_eq!(invokes[0].name, "task/submit");2828
assert_eq!(2829
invokes[0].value,2830
json!({"data": {"choice": "a"}, "context": {"theme": "dark"}})2831
);2832
}2833
2834
#[tokio::test]2835
async fn dialog_identity_names_the_user_and_the_tenant() {2836
let fake = Arc::new(Fake::default());2837
let engine = card_engine(&fake, BOT_GUID).await;2838
let identity = engine.dialog_identity(CHAT).await.unwrap();2839
assert_eq!(identity.user_id, ME);2840
assert_eq!(identity.display_name, "Me Myself");2841
assert_eq!(identity.tenant_id, "tenant-1");2842
}2843
2844
#[tokio::test]2845
async fn card_actions_without_a_payload_are_rejected() {2846
let fake = Arc::new(Fake::default());2847
let engine = card_engine(&fake, BOT_GUID).await;2848
let card = json!({"body": [{"type": "TextBlock", "text": "x"}], "actions": [2849
{"type": "Action.OpenUrl", "title": "Open", "url": "https://example.com"}2850
]});2851
let action = teams_core::AdaptiveCard::parse(&card.to_string())2852
.unwrap()2853
.actions2854
.remove(0);2855
assert!(engine.card_action(CHAT, "m0001", &action).await.is_err());2856
}2857
2858
#[tokio::test]2859
async fn bot_messages_remember_their_application() {2860
let fake = Arc::new(Fake::default());2861
let engine = card_engine(&fake, BOT_GUID).await;2862
let record = engine.open_conversation(CHAT).unwrap().remove(0);2863
assert_eq!(record.sender_application_id.as_deref(), Some(BOT_GUID));2864
assert_eq!(record.sender_id, None);2865
}@@ -363,6 +363,7 @@ fn record_with(body_html: &str, attachments_json: &str) -> MessageRecord {
363
363
reply_to_id: None,
364
364
sender_id: None,
365
365
sender_name: None,
366
sender_application_id: None,
366
367
created_at: chrono::DateTime::from_timestamp(1_700_000_000, 0).unwrap(),
367
368
edited_at: None,
368
369
deleted: false,
@@ -363,6 +363,7 @@ fn record_with(body_html: &str, attachments_json: &str) -> MessageRecord {363
reply_to_id: None,363
reply_to_id: None,364
sender_id: None,364
sender_id: None,365
sender_name: None,365
sender_name: None,366
sender_application_id: None,366
created_at: chrono::DateTime::from_timestamp(1_700_000_000, 0).unwrap(),367
created_at: chrono::DateTime::from_timestamp(1_700_000_000, 0).unwrap(),367
edited_at: None,368
edited_at: None,368
deleted: false,369
deleted: false,@@ -54,6 +54,12 @@ impl Sender {
54
54
pub fn user_id(&self) -> Option<&str> {
55
55
self.user.as_ref().and_then(|user| user.id.as_deref())
56
56
}
57
58
pub fn application_id(&self) -> Option<&str> {
59
self.application
60
.as_ref()
61
.and_then(|application| application.id.as_deref())
62
}
57
63
}
58
64
59
65
#[derive(Debug, Clone, Deserialize, PartialEq)]
@@ -54,6 +54,12 @@ impl Sender {54
pub fn user_id(&self) -> Option<&str> {54
pub fn user_id(&self) -> Option<&str> {55
self.user.as_ref().and_then(|user| user.id.as_deref())55
self.user.as_ref().and_then(|user| user.id.as_deref())56
}56
}57
58
pub fn application_id(&self) -> Option<&str> {59
self.application60
.as_ref()61
.and_then(|application| application.id.as_deref())62
}57
}63
}58
64
59
#[derive(Debug, Clone, Deserialize, PartialEq)]65
#[derive(Debug, Clone, Deserialize, PartialEq)]@@ -129,3 +129,14 @@ fn a_tag_mention_exposes_its_target_id_and_name() {
129
129
assert_eq!(mentioned.display_name(), Some("Tip of the day"));
130
130
assert_eq!(mentioned.user_id(), None);
131
131
}
132
133
#[test]
134
fn an_application_sender_exposes_its_id_but_no_user_id() {
135
let message: Message = serde_json::from_str(
136
r#"{"id":"1","from":{"application":{"id":"bot-guid","displayName":"Wiki Bot"}}}"#,
137
)
138
.unwrap();
139
let sender = message.from.as_ref().unwrap();
140
assert_eq!(sender.application_id(), Some("bot-guid"));
141
assert_eq!(sender.user_id(), None);
142
}
@@ -129,3 +129,14 @@ fn a_tag_mention_exposes_its_target_id_and_name() {129
assert_eq!(mentioned.display_name(), Some("Tip of the day"));129
assert_eq!(mentioned.display_name(), Some("Tip of the day"));130
assert_eq!(mentioned.user_id(), None);130
assert_eq!(mentioned.user_id(), None);131
}131
}132
133
#[test]134
fn an_application_sender_exposes_its_id_but_no_user_id() {135
let message: Message = serde_json::from_str(136
r#"{"id":"1","from":{"application":{"id":"bot-guid","displayName":"Wiki Bot"}}}"#,137
)138
.unwrap();139
let sender = message.from.as_ref().unwrap();140
assert_eq!(sender.application_id(), Some("bot-guid"));141
assert_eq!(sender.user_id(), None);142
}@@ -1,12 +1,7 @@
1
1
(async ({requests, resource, scope, marginMs, concurrency, maxBytes, forceRefresh}) => {
2
const base = resource.replace(/\/+$/, '');
3
const wanted = (base + '/' + scope).toLowerCase();
4
2
const fresh = (expires) => expires > Date.now() + marginMs;
5
3
const normalize = (value) => value.toLowerCase().replace(/\/\/+(?=[^/]*$)/, '/');
6
const short = scope.toLowerCase();
7
4
const covers = (value, name) => value === name || value === name + '.all';
8
const grants = (scopes) => scopes.some(s => covers(normalize(s), wanted)
9
|| (base === 'https://graph.microsoft.com' && covers(s.toLowerCase(), short)));
10
5
const entries = [];
11
6
let activeHome = null;
12
7
for (let index = 0; index < localStorage.length; index++) {
@@ -19,50 +14,66 @@
19
14
}
20
15
const ownAccount = (entry) => !activeHome || entry.homeAccountId === activeHome;
21
16
const homeTenant = (entry) => (entry.homeAccountId || '').split('.')[1];
22
let token = null, expiresOn = 0;
23
for (const entry of forceRefresh ? [] : entries) {
24
if (entry.credentialType !== 'AccessToken' || (entry.tokenType && entry.tokenType !== 'Bearer')) continue;
25
if (!ownAccount(entry) || (entry.realm && entry.realm !== homeTenant(entry))) continue;
26
const expires = Number(entry.expiresOn) * 1000;
27
if (!grants((entry.target || '').split(' ')) || !fresh(expires) || expires <= expiresOn) continue;
28
token = entry.secret; expiresOn = expires;
29
}
30
17
const cache = (window.__rustyTeamsTokens = window.__rustyTeamsTokens || {});
31
const cached = cache[base];
32
if (!token && !forceRefresh && cached && fresh(cached.expires)) {
33
if (grants(cached.scopes)) token = cached.token;
34
else return {noToken: true, refreshError: `the app is not granted ${scope}`};
35
}
36
const refreshTokens = entries
37
.filter(entry => entry.credentialType === 'RefreshToken' && ownAccount(entry))
38
.filter(entry => !entry.expiresOn || Number(entry.expiresOn) * 1000 > Date.now())
39
.sort((first, second) => Number(second.lastUpdatedAt || 0) - Number(first.lastUpdatedAt || 0));
40
let refreshError = null;
41
for (const refreshToken of token ? [] : refreshTokens) {
42
const form = new URLSearchParams({
43
client_id: refreshToken.clientId, grant_type: 'refresh_token', refresh_token: refreshToken.secret,
44
scope: base + '/.default openid profile offline_access',
45
});
46
try {
47
const response = await fetch(`https://login.microsoftonline.com/${homeTenant(refreshToken) || 'organizations'}/oauth2/v2.0/token`,
48
{method: 'POST', body: form});
49
const answer = await response.json();
50
if (!response.ok) { refreshError = answer.error || `HTTP ${response.status}`; continue; }
51
const scopes = (answer.scope || '').split(' ');
52
cache[base] = {token: answer.access_token, scopes, expires: Date.now() + answer.expires_in * 1000};
53
if (grants(scopes)) { token = answer.access_token; break; }
54
refreshError = `the app is not granted ${scope}`;
55
} catch (error) {
56
refreshError = String(error);
18
const acquire = async (resource, scope) => {
19
const base = resource.replace(/\/+$/, '');
20
const wanted = (base + '/' + scope).toLowerCase();
21
const short = scope.toLowerCase();
22
const underResource = (name) => normalize(name).startsWith(base.toLowerCase() + '/');
23
const grants = (scopes) => scopes.some(s => (scope === '.default' ? underResource(s) : covers(normalize(s), wanted))
24
|| (base === 'https://graph.microsoft.com' && covers(s.toLowerCase(), short)));
25
let token = null, expiresOn = 0;
26
for (const entry of forceRefresh ? [] : entries) {
27
if (entry.credentialType !== 'AccessToken' || (entry.tokenType && entry.tokenType !== 'Bearer')) continue;
28
if (!ownAccount(entry) || (entry.realm && entry.realm !== homeTenant(entry))) continue;
29
const expires = Number(entry.expiresOn) * 1000;
30
if (!grants((entry.target || '').split(' ')) || !fresh(expires) || expires <= expiresOn) continue;
31
token = entry.secret; expiresOn = expires;
57
32
}
58
}
33
const cached = cache[base];
34
if (!token && !forceRefresh && cached && fresh(cached.expires)) {
35
if (grants(cached.scopes)) token = cached.token;
36
else return {token: null, refreshError: `the app is not granted ${scope}`};
37
}
38
const refreshTokens = entries
39
.filter(entry => entry.credentialType === 'RefreshToken' && ownAccount(entry))
40
.filter(entry => !entry.expiresOn || Number(entry.expiresOn) * 1000 > Date.now())
41
.sort((first, second) => Number(second.lastUpdatedAt || 0) - Number(first.lastUpdatedAt || 0));
42
let refreshError = null;
43
for (const refreshToken of token ? [] : refreshTokens) {
44
const form = new URLSearchParams({
45
client_id: refreshToken.clientId, grant_type: 'refresh_token', refresh_token: refreshToken.secret,
46
scope: base + '/.default openid profile offline_access',
47
});
48
try {
49
const response = await fetch(`https://login.microsoftonline.com/${homeTenant(refreshToken) || 'organizations'}/oauth2/v2.0/token`,
50
{method: 'POST', body: form});
51
const answer = await response.json();
52
if (!response.ok) { refreshError = answer.error || `HTTP ${response.status}`; continue; }
53
const scopes = (answer.scope || '').split(' ');
54
cache[base] = {token: answer.access_token, scopes, expires: Date.now() + answer.expires_in * 1000};
55
if (grants(scopes)) { token = answer.access_token; break; }
56
refreshError = `the app is not granted ${scope}`;
57
} catch (error) {
58
refreshError = String(error);
59
}
60
}
61
return {token, refreshError};
62
};
63
const {token, refreshError} = await acquire(resource, scope);
59
64
if (!token) return {noToken: true, refreshError};
60
65
const run = async (request) => {
61
66
try {
67
let requestBody = request.body;
68
for (const extra of request.bodyTokens || []) {
69
const granted = await acquire(extra.resource, extra.scope);
70
if (!granted.token) return {status: 0, body: `no token for ${extra.resource}`};
71
requestBody = requestBody.split(extra.placeholder).join(granted.token);
72
}
62
73
const response = await fetch(request.url, {
63
74
method: request.method,
64
75
headers: request.anonymous ? request.headers : {Authorization: 'Bearer ' + token, ...request.headers},
65
body: request.bodyBase64 ? Uint8Array.from(atob(request.bodyBase64), (character) => character.charCodeAt(0)) : request.body,
76
body: request.bodyBase64 ? Uint8Array.from(atob(request.bodyBase64), (character) => character.charCodeAt(0)) : requestBody,
66
77
});
67
78
if (request.binary && response.ok) {
68
79
const bytes = new Uint8Array(await response.arrayBuffer());
@@ -1,12 +1,7 @@1
(async ({requests, resource, scope, marginMs, concurrency, maxBytes, forceRefresh}) => {1
(async ({requests, resource, scope, marginMs, concurrency, maxBytes, forceRefresh}) => {2
const base = resource.replace(/\/+$/, '');3
const wanted = (base + '/' + scope).toLowerCase();4
const fresh = (expires) => expires > Date.now() + marginMs;2
const fresh = (expires) => expires > Date.now() + marginMs;5
const normalize = (value) => value.toLowerCase().replace(/\/\/+(?=[^/]*$)/, '/');3
const normalize = (value) => value.toLowerCase().replace(/\/\/+(?=[^/]*$)/, '/');6
const short = scope.toLowerCase();7
const covers = (value, name) => value === name || value === name + '.all';4
const covers = (value, name) => value === name || value === name + '.all';8
const grants = (scopes) => scopes.some(s => covers(normalize(s), wanted)9
|| (base === 'https://graph.microsoft.com' && covers(s.toLowerCase(), short)));10
const entries = [];5
const entries = [];11
let activeHome = null;6
let activeHome = null;12
for (let index = 0; index < localStorage.length; index++) {7
for (let index = 0; index < localStorage.length; index++) {@@ -19,50 +14,66 @@19
}14
}20
const ownAccount = (entry) => !activeHome || entry.homeAccountId === activeHome;15
const ownAccount = (entry) => !activeHome || entry.homeAccountId === activeHome;21
const homeTenant = (entry) => (entry.homeAccountId || '').split('.')[1];16
const homeTenant = (entry) => (entry.homeAccountId || '').split('.')[1];22
let token = null, expiresOn = 0;23
for (const entry of forceRefresh ? [] : entries) {24
if (entry.credentialType !== 'AccessToken' || (entry.tokenType && entry.tokenType !== 'Bearer')) continue;25
if (!ownAccount(entry) || (entry.realm && entry.realm !== homeTenant(entry))) continue;26
const expires = Number(entry.expiresOn) * 1000;27
if (!grants((entry.target || '').split(' ')) || !fresh(expires) || expires <= expiresOn) continue;28
token = entry.secret; expiresOn = expires;29
}30
const cache = (window.__rustyTeamsTokens = window.__rustyTeamsTokens || {});17
const cache = (window.__rustyTeamsTokens = window.__rustyTeamsTokens || {});31
const cached = cache[base];18
const acquire = async (resource, scope) => {32
if (!token && !forceRefresh && cached && fresh(cached.expires)) {19
const base = resource.replace(/\/+$/, '');33
if (grants(cached.scopes)) token = cached.token;20
const wanted = (base + '/' + scope).toLowerCase();34
else return {noToken: true, refreshError: `the app is not granted ${scope}`};21
const short = scope.toLowerCase();35
}22
const underResource = (name) => normalize(name).startsWith(base.toLowerCase() + '/');36
const refreshTokens = entries23
const grants = (scopes) => scopes.some(s => (scope === '.default' ? underResource(s) : covers(normalize(s), wanted))37
.filter(entry => entry.credentialType === 'RefreshToken' && ownAccount(entry))24
|| (base === 'https://graph.microsoft.com' && covers(s.toLowerCase(), short)));38
.filter(entry => !entry.expiresOn || Number(entry.expiresOn) * 1000 > Date.now())25
let token = null, expiresOn = 0;39
.sort((first, second) => Number(second.lastUpdatedAt || 0) - Number(first.lastUpdatedAt || 0));26
for (const entry of forceRefresh ? [] : entries) {40
let refreshError = null;27
if (entry.credentialType !== 'AccessToken' || (entry.tokenType && entry.tokenType !== 'Bearer')) continue;41
for (const refreshToken of token ? [] : refreshTokens) {28
if (!ownAccount(entry) || (entry.realm && entry.realm !== homeTenant(entry))) continue;42
const form = new URLSearchParams({29
const expires = Number(entry.expiresOn) * 1000;43
client_id: refreshToken.clientId, grant_type: 'refresh_token', refresh_token: refreshToken.secret,30
if (!grants((entry.target || '').split(' ')) || !fresh(expires) || expires <= expiresOn) continue;44
scope: base + '/.default openid profile offline_access',31
token = entry.secret; expiresOn = expires;45
});46
try {47
const response = await fetch(`https://login.microsoftonline.com/${homeTenant(refreshToken) || 'organizations'}/oauth2/v2.0/token`,48
{method: 'POST', body: form});49
const answer = await response.json();50
if (!response.ok) { refreshError = answer.error || `HTTP ${response.status}`; continue; }51
const scopes = (answer.scope || '').split(' ');52
cache[base] = {token: answer.access_token, scopes, expires: Date.now() + answer.expires_in * 1000};53
if (grants(scopes)) { token = answer.access_token; break; }54
refreshError = `the app is not granted ${scope}`;55
} catch (error) {56
refreshError = String(error);57
}32
}58
}33
const cached = cache[base];34
if (!token && !forceRefresh && cached && fresh(cached.expires)) {35
if (grants(cached.scopes)) token = cached.token;36
else return {token: null, refreshError: `the app is not granted ${scope}`};37
}38
const refreshTokens = entries39
.filter(entry => entry.credentialType === 'RefreshToken' && ownAccount(entry))40
.filter(entry => !entry.expiresOn || Number(entry.expiresOn) * 1000 > Date.now())41
.sort((first, second) => Number(second.lastUpdatedAt || 0) - Number(first.lastUpdatedAt || 0));42
let refreshError = null;43
for (const refreshToken of token ? [] : refreshTokens) {44
const form = new URLSearchParams({45
client_id: refreshToken.clientId, grant_type: 'refresh_token', refresh_token: refreshToken.secret,46
scope: base + '/.default openid profile offline_access',47
});48
try {49
const response = await fetch(`https://login.microsoftonline.com/${homeTenant(refreshToken) || 'organizations'}/oauth2/v2.0/token`,50
{method: 'POST', body: form});51
const answer = await response.json();52
if (!response.ok) { refreshError = answer.error || `HTTP ${response.status}`; continue; }53
const scopes = (answer.scope || '').split(' ');54
cache[base] = {token: answer.access_token, scopes, expires: Date.now() + answer.expires_in * 1000};55
if (grants(scopes)) { token = answer.access_token; break; }56
refreshError = `the app is not granted ${scope}`;57
} catch (error) {58
refreshError = String(error);59
}60
}61
return {token, refreshError};62
};63
const {token, refreshError} = await acquire(resource, scope);59
if (!token) return {noToken: true, refreshError};64
if (!token) return {noToken: true, refreshError};60
const run = async (request) => {65
const run = async (request) => {61
try {66
try {67
let requestBody = request.body;68
for (const extra of request.bodyTokens || []) {69
const granted = await acquire(extra.resource, extra.scope);70
if (!granted.token) return {status: 0, body: `no token for ${extra.resource}`};71
requestBody = requestBody.split(extra.placeholder).join(granted.token);72
}62
const response = await fetch(request.url, {73
const response = await fetch(request.url, {63
method: request.method,74
method: request.method,64
headers: request.anonymous ? request.headers : {Authorization: 'Bearer ' + token, ...request.headers},75
headers: request.anonymous ? request.headers : {Authorization: 'Bearer ' + token, ...request.headers},65
body: request.bodyBase64 ? Uint8Array.from(atob(request.bodyBase64), (character) => character.charCodeAt(0)) : request.body,76
body: request.bodyBase64 ? Uint8Array.from(atob(request.bodyBase64), (character) => character.charCodeAt(0)) : requestBody,66
});77
});67
if (request.binary && response.ok) {78
if (request.binary && response.ok) {68
const bytes = new Uint8Array(await response.arrayBuffer());79
const bytes = new Uint8Array(await response.arrayBuffer());@@ -11,7 +11,8 @@ mod transport;
11
11
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
pub use request::{ApiResponse, Method, Request};
15
pub use scope::{GRAPH, IC3, OUTLOOK, PRESENCE, Scope};
14
pub use page_script::token_acquirer_script;
15
pub use request::{ApiResponse, BodyToken, Method, Request};
16
pub use scope::{GRAPH, IC3, OUTLOOK, PRESENCE, SPACES, Scope};
16
17
pub use session::{DEFAULT_ENDPOINT, Session, SessionConfig};
17
18
pub use transport::{BoxFuture, CdpTransport, Diagnosis, OpenedTab, Transport};
@@ -11,7 +11,8 @@ mod transport;11
pub use app::{App, Target, find_app_tab, has_login_tab, is_login_url};11
pub use app::{App, Target, find_app_tab, has_login_tab, is_login_url};12
pub use error::{Error, Result};12
pub use error::{Error, Result};13
pub use events::{TabChannel, TabCommand, TabControl, TabEvent, TabEvents};13
pub use events::{TabChannel, TabCommand, TabControl, TabEvent, TabEvents};14
pub use request::{ApiResponse, Method, Request};14
pub use page_script::token_acquirer_script;15
pub use scope::{GRAPH, IC3, OUTLOOK, PRESENCE, Scope};15
pub use request::{ApiResponse, BodyToken, Method, Request};16
pub use scope::{GRAPH, IC3, OUTLOOK, PRESENCE, SPACES, Scope};16
pub use session::{DEFAULT_ENDPOINT, Session, SessionConfig};17
pub use session::{DEFAULT_ENDPOINT, Session, SessionConfig};17
pub use transport::{BoxFuture, CdpTransport, Diagnosis, OpenedTab, Transport};18
pub use transport::{BoxFuture, CdpTransport, Diagnosis, OpenedTab, Transport};@@ -8,11 +8,24 @@ use crate::scope::Scope;
8
8
use crate::session::{FETCH_SCRIPT, NOT_GRANTED_PREFIX, Session};
9
9
10
10
const TOKEN_MARKER: &str = "if (!token) return {noToken: true, refreshError};";
11
const ACQUIRE_CALL: &str = "const {token, refreshError} = await acquire(resource, scope);";
12
13
/// A JS function expression: `(factory)({marginMs, forceRefresh})` resolves to `acquire(resource, scope)`, which answers `{token, refreshError}`.
14
pub fn token_acquirer_script() -> String {
15
let call_at = FETCH_SCRIPT
16
.find(ACQUIRE_CALL)
17
.expect("fetch.js contains the acquire call");
18
format!("{}return acquire;}})", &FETCH_SCRIPT[..call_at])
19
}
11
20
12
21
impl Session {
13
22
/// Opens a dedicated CDP connection to the app tab. Events of the tab arrive on the stream.
14
23
pub async fn subscribe(&self, app: App) -> Result<(TabControl, TabEvents)> {
15
let (control, events) = self.transport.open(app, true).await?.ok_or(Error::NoAppTab)?;
24
let (control, events) = self
25
.transport
26
.open(app, true)
27
.await?
28
.ok_or(Error::NoAppTab)?;
16
29
Ok((control, events.expect("opened with events")))
17
30
}
18
31
@@ -52,7 +65,9 @@ impl Session {
52
65
.map_err(|error| Error::Cdp(format!("unexpected page answer: {error}")))?;
53
66
let reason = outcome.refresh_error.unwrap_or_default();
54
67
if reason.starts_with(NOT_GRANTED_PREFIX) {
55
return Err(Error::LoginRequired(format!("{app} app is not granted {scope}")));
68
return Err(Error::LoginRequired(format!(
69
"{app} app is not granted {scope}"
70
)));
56
71
}
57
72
let detail = if reason.is_empty() {
58
73
String::new()
@@ -67,3 +82,16 @@ impl Session {
67
82
Ok(outcome)
68
83
}
69
84
}
85
86
#[cfg(test)]
87
mod tests {
88
use super::*;
89
90
#[test]
91
fn acquirer_script_returns_the_acquire_function_before_any_request_runs() {
92
let script = token_acquirer_script();
93
assert!(script.starts_with("(async ({"));
94
assert!(script.ends_with("return acquire;})"));
95
assert!(!script.contains("const run = "));
96
}
97
}
@@ -8,11 +8,24 @@ use crate::scope::Scope;8
use crate::session::{FETCH_SCRIPT, NOT_GRANTED_PREFIX, Session};8
use crate::session::{FETCH_SCRIPT, NOT_GRANTED_PREFIX, Session};9
9
10
const TOKEN_MARKER: &str = "if (!token) return {noToken: true, refreshError};";10
const TOKEN_MARKER: &str = "if (!token) return {noToken: true, refreshError};";11
const ACQUIRE_CALL: &str = "const {token, refreshError} = await acquire(resource, scope);";12
13
/// A JS function expression: `(factory)({marginMs, forceRefresh})` resolves to `acquire(resource, scope)`, which answers `{token, refreshError}`.14
pub fn token_acquirer_script() -> String {15
let call_at = FETCH_SCRIPT16
.find(ACQUIRE_CALL)17
.expect("fetch.js contains the acquire call");18
format!("{}return acquire;}})", &FETCH_SCRIPT[..call_at])19
}11
20
12
impl Session {21
impl Session {13
/// Opens a dedicated CDP connection to the app tab. Events of the tab arrive on the stream.22
/// Opens a dedicated CDP connection to the app tab. Events of the tab arrive on the stream.14
pub async fn subscribe(&self, app: App) -> Result<(TabControl, TabEvents)> {23
pub async fn subscribe(&self, app: App) -> Result<(TabControl, TabEvents)> {15
let (control, events) = self.transport.open(app, true).await?.ok_or(Error::NoAppTab)?;24
let (control, events) = self25
.transport26
.open(app, true)27
.await?28
.ok_or(Error::NoAppTab)?;16
Ok((control, events.expect("opened with events")))29
Ok((control, events.expect("opened with events")))17
}30
}18
31
@@ -52,7 +65,9 @@ impl Session {52
.map_err(|error| Error::Cdp(format!("unexpected page answer: {error}")))?;65
.map_err(|error| Error::Cdp(format!("unexpected page answer: {error}")))?;53
let reason = outcome.refresh_error.unwrap_or_default();66
let reason = outcome.refresh_error.unwrap_or_default();54
if reason.starts_with(NOT_GRANTED_PREFIX) {67
if reason.starts_with(NOT_GRANTED_PREFIX) {55
return Err(Error::LoginRequired(format!("{app} app is not granted {scope}")));68
return Err(Error::LoginRequired(format!(69
"{app} app is not granted {scope}"70
)));56
}71
}57
let detail = if reason.is_empty() {72
let detail = if reason.is_empty() {58
String::new()73
String::new()@@ -67,3 +82,16 @@ impl Session {67
Ok(outcome)82
Ok(outcome)68
}83
}69
}84
}85
86
#[cfg(test)]87
mod tests {88
use super::*;89
90
#[test]91
fn acquirer_script_returns_the_acquire_function_before_any_request_runs() {92
let script = token_acquirer_script();93
assert!(script.starts_with("(async ({"));94
assert!(script.ends_with("return acquire;})"));95
assert!(!script.contains("const run = "));96
}97
}@@ -22,6 +22,13 @@ impl Method {
22
22
}
23
23
}
24
24
25
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
26
pub struct BodyToken {
27
pub resource: String,
28
pub scope: String,
29
pub placeholder: String,
30
}
31
25
32
#[derive(Debug, Clone)]
26
33
pub struct Request {
27
34
pub method: Method,
@@ -31,6 +38,7 @@ pub struct Request {
31
38
pub binary: bool,
32
39
pub anonymous: bool,
33
40
pub body_base64: Option<String>,
41
pub body_tokens: Vec<BodyToken>,
34
42
}
35
43
36
44
impl Request {
@@ -51,9 +59,20 @@ impl Request {
51
59
binary: false,
52
60
anonymous: false,
53
61
body_base64: None,
62
body_tokens: Vec::new(),
54
63
}
55
64
}
56
65
66
/// Replaces `placeholder` in the body with a token for `resource` inside the page, so the token never leaves it.
67
pub fn with_body_token(mut self, resource: &str, scope: &str, placeholder: &str) -> Self {
68
self.body_tokens.push(BodyToken {
69
resource: resource.to_owned(),
70
scope: scope.to_owned(),
71
placeholder: placeholder.to_owned(),
72
});
73
self
74
}
75
57
76
/// Sent without an Authorization header, for pre-authenticated URLs such as upload sessions.
58
77
pub fn anonymous_bytes(method: Method, url: impl Into<String>, headers: Vec<(String, String)>, body_base64: String) -> Self {
59
78
Request {
@@ -90,6 +109,7 @@ impl Request {
90
109
binary: false,
91
110
anonymous: false,
92
111
body_base64: None,
112
body_tokens: Vec::new(),
93
113
}
94
114
}
95
115
}
@@ -117,6 +137,8 @@ pub(crate) struct WireRequest<'a> {
117
137
pub body_base64: Option<&'a str>,
118
138
pub binary: bool,
119
139
pub anonymous: bool,
140
#[serde(rename = "bodyTokens")]
141
pub body_tokens: &'a [BodyToken],
120
142
}
121
143
122
144
impl<'a> From<&'a Request> for WireRequest<'a> {
@@ -137,6 +159,7 @@ impl<'a> From<&'a Request> for WireRequest<'a> {
137
159
body_base64: request.body_base64.as_deref(),
138
160
binary: request.binary,
139
161
anonymous: request.anonymous,
162
body_tokens: &request.body_tokens,
140
163
}
141
164
}
142
165
}
@@ -225,6 +248,23 @@ mod tests {
225
248
assert_eq!(wire["headers"]["Range"], "bytes=0-9");
226
249
}
227
250
251
#[test]
252
fn body_tokens_travel_as_placeholders() {
253
let request = Request::with_body(Method::Post, "u", json!({"token": "@@t@@"}))
254
.with_body_token(
255
"https://api.spaces.skype.com",
256
"user_impersonation",
257
"@@t@@",
258
);
259
let wire = serde_json::to_value(WireRequest::from(&request)).unwrap();
260
assert_eq!(
261
wire["bodyTokens"][0]["resource"],
262
"https://api.spaces.skype.com"
263
);
264
assert_eq!(wire["bodyTokens"][0]["placeholder"], "@@t@@");
265
assert_eq!(wire["body"], r#"{"token":"@@t@@"}"#);
266
}
267
228
268
#[test]
229
269
fn get_has_no_body() {
230
270
let request = Request::get("u");
@@ -22,6 +22,13 @@ impl Method {22
}22
}23
}23
}24
24
25
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]26
pub struct BodyToken {27
pub resource: String,28
pub scope: String,29
pub placeholder: String,30
}31
25
#[derive(Debug, Clone)]32
#[derive(Debug, Clone)]26
pub struct Request {33
pub struct Request {27
pub method: Method,34
pub method: Method,@@ -31,6 +38,7 @@ pub struct Request {31
pub binary: bool,38
pub binary: bool,32
pub anonymous: bool,39
pub anonymous: bool,33
pub body_base64: Option<String>,40
pub body_base64: Option<String>,41
pub body_tokens: Vec<BodyToken>,34
}42
}35
43
36
impl Request {44
impl Request {@@ -51,9 +59,20 @@ impl Request {51
binary: false,59
binary: false,52
anonymous: false,60
anonymous: false,53
body_base64: None,61
body_base64: None,62
body_tokens: Vec::new(),54
}63
}55
}64
}56
65
66
/// Replaces `placeholder` in the body with a token for `resource` inside the page, so the token never leaves it.67
pub fn with_body_token(mut self, resource: &str, scope: &str, placeholder: &str) -> Self {68
self.body_tokens.push(BodyToken {69
resource: resource.to_owned(),70
scope: scope.to_owned(),71
placeholder: placeholder.to_owned(),72
});73
self74
}75
57
/// Sent without an Authorization header, for pre-authenticated URLs such as upload sessions.76
/// Sent without an Authorization header, for pre-authenticated URLs such as upload sessions.58
pub fn anonymous_bytes(method: Method, url: impl Into<String>, headers: Vec<(String, String)>, body_base64: String) -> Self {77
pub fn anonymous_bytes(method: Method, url: impl Into<String>, headers: Vec<(String, String)>, body_base64: String) -> Self {59
Request {78
Request {@@ -90,6 +109,7 @@ impl Request {90
binary: false,109
binary: false,91
anonymous: false,110
anonymous: false,92
body_base64: None,111
body_base64: None,112
body_tokens: Vec::new(),93
}113
}94
}114
}95
}115
}@@ -117,6 +137,8 @@ pub(crate) struct WireRequest<'a> {117
pub body_base64: Option<&'a str>,137
pub body_base64: Option<&'a str>,118
pub binary: bool,138
pub binary: bool,119
pub anonymous: bool,139
pub anonymous: bool,140
#[serde(rename = "bodyTokens")]141
pub body_tokens: &'a [BodyToken],120
}142
}121
143
122
impl<'a> From<&'a Request> for WireRequest<'a> {144
impl<'a> From<&'a Request> for WireRequest<'a> {@@ -137,6 +159,7 @@ impl<'a> From<&'a Request> for WireRequest<'a> {137
body_base64: request.body_base64.as_deref(),159
body_base64: request.body_base64.as_deref(),138
binary: request.binary,160
binary: request.binary,139
anonymous: request.anonymous,161
anonymous: request.anonymous,162
body_tokens: &request.body_tokens,140
}163
}141
}164
}142
}165
}@@ -225,6 +248,23 @@ mod tests {225
assert_eq!(wire["headers"]["Range"], "bytes=0-9");248
assert_eq!(wire["headers"]["Range"], "bytes=0-9");226
}249
}227
250
251
#[test]252
fn body_tokens_travel_as_placeholders() {253
let request = Request::with_body(Method::Post, "u", json!({"token": "@@t@@"}))254
.with_body_token(255
"https://api.spaces.skype.com",256
"user_impersonation",257
"@@t@@",258
);259
let wire = serde_json::to_value(WireRequest::from(&request)).unwrap();260
assert_eq!(261
wire["bodyTokens"][0]["resource"],262
"https://api.spaces.skype.com"263
);264
assert_eq!(wire["bodyTokens"][0]["placeholder"], "@@t@@");265
assert_eq!(wire["body"], r#"{"token":"@@t@@"}"#);266
}267
228
#[test]268
#[test]229
fn get_has_no_body() {269
fn get_has_no_body() {230
let request = Request::get("u");270
let request = Request::get("u");@@ -6,6 +6,7 @@ pub const GRAPH: &str = "https://graph.microsoft.com";
6
6
pub const IC3: &str = "https://ic3.teams.office.com";
7
7
pub const PRESENCE: &str = "https://presence.teams.microsoft.com";
8
8
pub const OUTLOOK: &str = "https://outlook.office.com";
9
pub const SPACES: &str = "https://api.spaces.skype.com";
9
10
10
11
#[derive(Debug, Clone, PartialEq, Eq)]
11
12
pub struct Scope {
@@ -6,6 +6,7 @@ pub const GRAPH: &str = "https://graph.microsoft.com";6
pub const IC3: &str = "https://ic3.teams.office.com";6
pub const IC3: &str = "https://ic3.teams.office.com";7
pub const PRESENCE: &str = "https://presence.teams.microsoft.com";7
pub const PRESENCE: &str = "https://presence.teams.microsoft.com";8
pub const OUTLOOK: &str = "https://outlook.office.com";8
pub const OUTLOOK: &str = "https://outlook.office.com";9
pub const SPACES: &str = "https://api.spaces.skype.com";9
10
10
#[derive(Debug, Clone, PartialEq, Eq)]11
#[derive(Debug, Clone, PartialEq, Eq)]11
pub struct Scope {12
pub struct Scope {@@ -10,7 +10,7 @@ use crate::store::Store;
10
10
use crate::time::{from_millis, optional_from_millis, optional_to_millis, to_millis};
11
11
12
12
const MESSAGE_COLUMNS: &str = "conversation_id, message_id, reply_to_id, sender_id, sender_name, created_at, \
13
edited_at, deleted, body_html, attachments_json, reactions_json, mentions_json";
13
edited_at, deleted, body_html, attachments_json, reactions_json, mentions_json, sender_application_id";
14
14
15
15
impl Store {
16
16
pub fn upsert_messages(&self, messages: &[MessageRecord]) -> Result<()> {
@@ -19,13 +19,14 @@ impl Store {
19
19
{
20
20
let mut upsert = transaction.prepare_cached(&format!(
21
21
"INSERT INTO messages ({MESSAGE_COLUMNS})
22
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12)
22
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13)
23
23
ON CONFLICT (conversation_id, message_id) DO UPDATE SET
24
24
reply_to_id = excluded.reply_to_id, sender_id = excluded.sender_id,
25
25
sender_name = excluded.sender_name, created_at = excluded.created_at,
26
26
edited_at = excluded.edited_at, deleted = excluded.deleted, body_html = excluded.body_html,
27
27
attachments_json = excluded.attachments_json, reactions_json = excluded.reactions_json,
28
mentions_json = excluded.mentions_json"
28
mentions_json = excluded.mentions_json,
29
sender_application_id = excluded.sender_application_id"
29
30
))?;
30
31
for message in messages {
31
32
upsert.execute(params![
@@ -41,6 +42,7 @@ impl Store {
41
42
message.attachments_json,
42
43
message.reactions_json,
43
44
message.mentions_json,
45
message.sender_application_id,
44
46
])?;
45
47
index_message(&transaction, message)?;
46
48
}
@@ -163,5 +165,6 @@ fn message_from_row(row: &Row<'_>) -> rusqlite::Result<MessageRecord> {
163
165
attachments_json: row.get(9)?,
164
166
reactions_json: row.get(10)?,
165
167
mentions_json: row.get(11)?,
168
sender_application_id: row.get(12)?,
166
169
})
167
170
}
@@ -10,7 +10,7 @@ use crate::store::Store;10
use crate::time::{from_millis, optional_from_millis, optional_to_millis, to_millis};10
use crate::time::{from_millis, optional_from_millis, optional_to_millis, to_millis};11
11
12
const MESSAGE_COLUMNS: &str = "conversation_id, message_id, reply_to_id, sender_id, sender_name, created_at, \12
const MESSAGE_COLUMNS: &str = "conversation_id, message_id, reply_to_id, sender_id, sender_name, created_at, \13
edited_at, deleted, body_html, attachments_json, reactions_json, mentions_json";13
edited_at, deleted, body_html, attachments_json, reactions_json, mentions_json, sender_application_id";14
14
15
impl Store {15
impl Store {16
pub fn upsert_messages(&self, messages: &[MessageRecord]) -> Result<()> {16
pub fn upsert_messages(&self, messages: &[MessageRecord]) -> Result<()> {@@ -19,13 +19,14 @@ impl Store {19
{19
{20
let mut upsert = transaction.prepare_cached(&format!(20
let mut upsert = transaction.prepare_cached(&format!(21
"INSERT INTO messages ({MESSAGE_COLUMNS})21
"INSERT INTO messages ({MESSAGE_COLUMNS})22
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12)22
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13)23
ON CONFLICT (conversation_id, message_id) DO UPDATE SET23
ON CONFLICT (conversation_id, message_id) DO UPDATE SET24
reply_to_id = excluded.reply_to_id, sender_id = excluded.sender_id,24
reply_to_id = excluded.reply_to_id, sender_id = excluded.sender_id,25
sender_name = excluded.sender_name, created_at = excluded.created_at,25
sender_name = excluded.sender_name, created_at = excluded.created_at,26
edited_at = excluded.edited_at, deleted = excluded.deleted, body_html = excluded.body_html,26
edited_at = excluded.edited_at, deleted = excluded.deleted, body_html = excluded.body_html,27
attachments_json = excluded.attachments_json, reactions_json = excluded.reactions_json,27
attachments_json = excluded.attachments_json, reactions_json = excluded.reactions_json,28
mentions_json = excluded.mentions_json"28
mentions_json = excluded.mentions_json,29
sender_application_id = excluded.sender_application_id"29
))?;30
))?;30
for message in messages {31
for message in messages {31
upsert.execute(params![32
upsert.execute(params![@@ -41,6 +42,7 @@ impl Store {41
message.attachments_json,42
message.attachments_json,42
message.reactions_json,43
message.reactions_json,43
message.mentions_json,44
message.mentions_json,45
message.sender_application_id,44
])?;46
])?;45
index_message(&transaction, message)?;47
index_message(&transaction, message)?;46
}48
}@@ -163,5 +165,6 @@ fn message_from_row(row: &Row<'_>) -> rusqlite::Result<MessageRecord> {163
attachments_json: row.get(9)?,165
attachments_json: row.get(9)?,164
reactions_json: row.get(10)?,166
reactions_json: row.get(10)?,165
mentions_json: row.get(11)?,167
mentions_json: row.get(11)?,168
sender_application_id: row.get(12)?,166
})169
})167
}170
}@@ -33,6 +33,10 @@ const MIGRATIONS: &[Migration] = &[
33
33
script: include_str!("migrations/0006_presence.sql"),
34
34
after: None,
35
35
},
36
Migration {
37
script: include_str!("migrations/0007_sender_application.sql"),
38
after: None,
39
},
36
40
];
37
41
38
42
pub fn latest_version() -> i64 {
@@ -33,6 +33,10 @@ const MIGRATIONS: &[Migration] = &[33
script: include_str!("migrations/0006_presence.sql"),33
script: include_str!("migrations/0006_presence.sql"),34
after: None,34
after: None,35
},35
},36
Migration {37
script: include_str!("migrations/0007_sender_application.sql"),38
after: None,39
},36
];40
];37
41
38
pub fn latest_version() -> i64 {42
pub fn latest_version() -> i64 {@@ -0,0 +1 @@
1
ALTER TABLE messages ADD COLUMN sender_application_id TEXT;
@@ -0,0 +1 @@1
ALTER TABLE messages ADD COLUMN sender_application_id TEXT;@@ -68,6 +68,7 @@ pub struct MessageRecord {
68
68
pub attachments_json: String,
69
69
pub reactions_json: String,
70
70
pub mentions_json: String,
71
pub sender_application_id: Option<String>,
71
72
}
72
73
73
74
#[derive(Debug, Clone, PartialEq)]
@@ -68,6 +68,7 @@ pub struct MessageRecord {68
pub attachments_json: String,68
pub attachments_json: String,69
pub reactions_json: String,69
pub reactions_json: String,70
pub mentions_json: String,70
pub mentions_json: String,71
pub sender_application_id: Option<String>,71
}72
}72
73
73
#[derive(Debug, Clone, PartialEq)]74
#[derive(Debug, Clone, PartialEq)]@@ -46,9 +46,22 @@ fn message(conversation_id: &str, message_id: &str, minute: u32) -> MessageRecor
46
46
attachments_json: "[]".to_owned(),
47
47
reactions_json: "[]".to_owned(),
48
48
mentions_json: "[]".to_owned(),
49
sender_application_id: None,
49
50
}
50
51
}
51
52
53
#[test]
54
fn sender_application_round_trips() {
55
let store = Store::open_in_memory().unwrap();
56
let bot_message = MessageRecord {
57
sender_application_id: Some("bot-guid".to_owned()),
58
..message("c1", "m1", 1)
59
};
60
store.upsert_messages(std::slice::from_ref(&bot_message)).unwrap();
61
let found = store.messages_by_id("c1", &["m1".to_owned()]).unwrap();
62
assert_eq!(found["m1"], bot_message);
63
}
64
52
65
fn ids(messages: &[MessageRecord]) -> Vec<&str> {
53
66
messages
54
67
.iter()
@@ -345,11 +358,11 @@ fn file_database_uses_wal_persists_and_migrates_once() {
345
358
let path = directory.path().join("nested").join("cache.sqlite3");
346
359
{
347
360
let store = Store::open(&path).unwrap();
348
assert_eq!(store.schema_version().unwrap(), 6);
361
assert_eq!(store.schema_version().unwrap(), 7);
349
362
store.upsert_messages(&[message("c", "m1", 1)]).unwrap();
350
363
}
351
364
let reopened = Store::open(&path).unwrap();
352
assert_eq!(reopened.schema_version().unwrap(), 6);
365
assert_eq!(reopened.schema_version().unwrap(), 7);
353
366
assert_eq!(reopened.message_count("c").unwrap(), 1);
354
367
drop(reopened);
355
368
let mode: String = rusqlite_open(&path)
@@ -381,7 +394,7 @@ fn old_schema_is_upgraded_in_place() {
381
394
connection.execute_batch("DROP TABLE messages; DROP TABLE sync_state; DROP TABLE chats; DROP TABLE chat_members; DROP TABLE channels; DROP TABLE teams; DROP TABLE meta; DROP TABLE avatars; DROP TABLE folder_items; DROP TABLE folders; DROP TABLE pinned_channels; DROP TABLE images; DROP TABLE search_keys; DROP TABLE message_search; DROP TABLE title_search; DROP TABLE team_layout; DROP TABLE channel_layout; DROP TABLE presence; PRAGMA user_version = 0").unwrap();
382
395
drop(connection);
383
396
let store = Store::open(&path).unwrap();
384
assert_eq!(store.schema_version().unwrap(), 6);
397
assert_eq!(store.schema_version().unwrap(), 7);
385
398
store.upsert_messages(&[message("c", "m1", 1)]).unwrap();
386
399
}
387
400
@@ -447,7 +460,7 @@ fn migration_to_v2_keeps_existing_sync_state() {
447
460
let store = Store::open(&path).unwrap();
448
461
let state = store.sync_state("c").unwrap().unwrap();
449
462
assert_eq!(state.delta_link, None);
450
assert_eq!(store.schema_version().unwrap(), 6);
463
assert_eq!(store.schema_version().unwrap(), 7);
451
464
}
452
465
453
466
#[test]
@@ -678,6 +691,7 @@ fn migration_indexes_rows_that_predate_search() {
678
691
DROP TRIGGER channels_title_insert; DROP TRIGGER channels_title_update; DROP TRIGGER channels_title_delete;
679
692
DROP TABLE images; DROP TABLE search_keys; DROP TABLE message_search; DROP TABLE title_search;
680
693
DROP TABLE team_layout; DROP TABLE channel_layout; DROP TABLE presence;
694
ALTER TABLE messages DROP COLUMN sender_application_id;
681
695
PRAGMA user_version = 3;",
682
696
)
683
697
.unwrap();
@@ -46,9 +46,22 @@ fn message(conversation_id: &str, message_id: &str, minute: u32) -> MessageRecor46
attachments_json: "[]".to_owned(),46
attachments_json: "[]".to_owned(),47
reactions_json: "[]".to_owned(),47
reactions_json: "[]".to_owned(),48
mentions_json: "[]".to_owned(),48
mentions_json: "[]".to_owned(),49
sender_application_id: None,49
}50
}50
}51
}51
52
53
#[test]54
fn sender_application_round_trips() {55
let store = Store::open_in_memory().unwrap();56
let bot_message = MessageRecord {57
sender_application_id: Some("bot-guid".to_owned()),58
..message("c1", "m1", 1)59
};60
store.upsert_messages(std::slice::from_ref(&bot_message)).unwrap();61
let found = store.messages_by_id("c1", &["m1".to_owned()]).unwrap();62
assert_eq!(found["m1"], bot_message);63
}64
52
fn ids(messages: &[MessageRecord]) -> Vec<&str> {65
fn ids(messages: &[MessageRecord]) -> Vec<&str> {53
messages66
messages54
.iter()67
.iter()@@ -345,11 +358,11 @@ fn file_database_uses_wal_persists_and_migrates_once() {345
let path = directory.path().join("nested").join("cache.sqlite3");358
let path = directory.path().join("nested").join("cache.sqlite3");346
{359
{347
let store = Store::open(&path).unwrap();360
let store = Store::open(&path).unwrap();348
assert_eq!(store.schema_version().unwrap(), 6);361
assert_eq!(store.schema_version().unwrap(), 7);349
store.upsert_messages(&[message("c", "m1", 1)]).unwrap();362
store.upsert_messages(&[message("c", "m1", 1)]).unwrap();350
}363
}351
let reopened = Store::open(&path).unwrap();364
let reopened = Store::open(&path).unwrap();352
assert_eq!(reopened.schema_version().unwrap(), 6);365
assert_eq!(reopened.schema_version().unwrap(), 7);353
assert_eq!(reopened.message_count("c").unwrap(), 1);366
assert_eq!(reopened.message_count("c").unwrap(), 1);354
drop(reopened);367
drop(reopened);355
let mode: String = rusqlite_open(&path)368
let mode: String = rusqlite_open(&path)@@ -381,7 +394,7 @@ fn old_schema_is_upgraded_in_place() {381
connection.execute_batch("DROP TABLE messages; DROP TABLE sync_state; DROP TABLE chats; DROP TABLE chat_members; DROP TABLE channels; DROP TABLE teams; DROP TABLE meta; DROP TABLE avatars; DROP TABLE folder_items; DROP TABLE folders; DROP TABLE pinned_channels; DROP TABLE images; DROP TABLE search_keys; DROP TABLE message_search; DROP TABLE title_search; DROP TABLE team_layout; DROP TABLE channel_layout; DROP TABLE presence; PRAGMA user_version = 0").unwrap();394
connection.execute_batch("DROP TABLE messages; DROP TABLE sync_state; DROP TABLE chats; DROP TABLE chat_members; DROP TABLE channels; DROP TABLE teams; DROP TABLE meta; DROP TABLE avatars; DROP TABLE folder_items; DROP TABLE folders; DROP TABLE pinned_channels; DROP TABLE images; DROP TABLE search_keys; DROP TABLE message_search; DROP TABLE title_search; DROP TABLE team_layout; DROP TABLE channel_layout; DROP TABLE presence; PRAGMA user_version = 0").unwrap();382
drop(connection);395
drop(connection);383
let store = Store::open(&path).unwrap();396
let store = Store::open(&path).unwrap();384
assert_eq!(store.schema_version().unwrap(), 6);397
assert_eq!(store.schema_version().unwrap(), 7);385
store.upsert_messages(&[message("c", "m1", 1)]).unwrap();398
store.upsert_messages(&[message("c", "m1", 1)]).unwrap();386
}399
}387
400
@@ -447,7 +460,7 @@ fn migration_to_v2_keeps_existing_sync_state() {447
let store = Store::open(&path).unwrap();460
let store = Store::open(&path).unwrap();448
let state = store.sync_state("c").unwrap().unwrap();461
let state = store.sync_state("c").unwrap().unwrap();449
assert_eq!(state.delta_link, None);462
assert_eq!(state.delta_link, None);450
assert_eq!(store.schema_version().unwrap(), 6);463
assert_eq!(store.schema_version().unwrap(), 7);451
}464
}452
465
453
#[test]466
#[test]@@ -678,6 +691,7 @@ fn migration_indexes_rows_that_predate_search() {678
DROP TRIGGER channels_title_insert; DROP TRIGGER channels_title_update; DROP TRIGGER channels_title_delete;691
DROP TRIGGER channels_title_insert; DROP TRIGGER channels_title_update; DROP TRIGGER channels_title_delete;679
DROP TABLE images; DROP TABLE search_keys; DROP TABLE message_search; DROP TABLE title_search;692
DROP TABLE images; DROP TABLE search_keys; DROP TABLE message_search; DROP TABLE title_search;680
DROP TABLE team_layout; DROP TABLE channel_layout; DROP TABLE presence;693
DROP TABLE team_layout; DROP TABLE channel_layout; DROP TABLE presence;694
ALTER TABLE messages DROP COLUMN sender_application_id;681
PRAGMA user_version = 3;",695
PRAGMA user_version = 3;",682
)696
)683
.unwrap();697
.unwrap();@@ -18,6 +18,8 @@ windows = { version = "0.62", features = [
18
18
"Win32_System_Com",
19
19
"Win32_System_LibraryLoader",
20
20
"Win32_System_Threading",
21
"Win32_UI_HiDpi",
22
"Win32_UI_Shell",
21
23
"Win32_UI_WindowsAndMessaging",
22
24
] }
23
25
windows-core = "0.62"
@@ -18,6 +18,8 @@ windows = { version = "0.62", features = [18
"Win32_System_Com",18
"Win32_System_Com",19
"Win32_System_LibraryLoader",19
"Win32_System_LibraryLoader",20
"Win32_System_Threading",20
"Win32_System_Threading",21
"Win32_UI_HiDpi",22
"Win32_UI_Shell",21
"Win32_UI_WindowsAndMessaging",23
"Win32_UI_WindowsAndMessaging",22
] }24
] }23
windows-core = "0.62"25
windows-core = "0.62"@@ -0,0 +1,61 @@
1
use std::sync::{Arc, mpsc};
2
3
use crate::transport::UiRequest;
4
5
#[derive(Debug, Clone)]
6
pub struct DialogSpec {
7
pub title: String,
8
pub width: u32,
9
pub height: u32,
10
pub background: u32,
11
pub owner: Option<isize>,
12
pub page_url: String,
13
pub page_html: String,
14
}
15
16
#[derive(Debug, Clone, PartialEq, Eq)]
17
pub enum DialogEvent {
18
Message(String),
19
Closed,
20
}
21
22
#[derive(Debug)]
23
pub(crate) enum DialogCommand {
24
Post(String),
25
Resize {
26
width: Option<u32>,
27
height: Option<u32>,
28
},
29
Close,
30
}
31
32
#[derive(Clone)]
33
pub struct DialogHandle {
34
pub(crate) id: u64,
35
pub(crate) requests: mpsc::Sender<UiRequest>,
36
pub(crate) waker: Arc<dyn Fn() + Send + Sync>,
37
}
38
39
impl DialogHandle {
40
pub fn post(&self, json: String) {
41
self.send(DialogCommand::Post(json));
42
}
43
44
pub fn resize(&self, width: Option<u32>, height: Option<u32>) {
45
self.send(DialogCommand::Resize { width, height });
46
}
47
48
pub fn close(&self) {
49
self.send(DialogCommand::Close);
50
}
51
52
fn send(&self, command: DialogCommand) {
53
let request = UiRequest::Dialog {
54
id: self.id,
55
command,
56
};
57
if self.requests.send(request).is_ok() {
58
(self.waker)();
59
}
60
}
61
}
@@ -0,0 +1,61 @@1
use std::sync::{Arc, mpsc};2
3
use crate::transport::UiRequest;4
5
#[derive(Debug, Clone)]6
pub struct DialogSpec {7
pub title: String,8
pub width: u32,9
pub height: u32,10
pub background: u32,11
pub owner: Option<isize>,12
pub page_url: String,13
pub page_html: String,14
}15
16
#[derive(Debug, Clone, PartialEq, Eq)]17
pub enum DialogEvent {18
Message(String),19
Closed,20
}21
22
#[derive(Debug)]23
pub(crate) enum DialogCommand {24
Post(String),25
Resize {26
width: Option<u32>,27
height: Option<u32>,28
},29
Close,30
}31
32
#[derive(Clone)]33
pub struct DialogHandle {34
pub(crate) id: u64,35
pub(crate) requests: mpsc::Sender<UiRequest>,36
pub(crate) waker: Arc<dyn Fn() + Send + Sync>,37
}38
39
impl DialogHandle {40
pub fn post(&self, json: String) {41
self.send(DialogCommand::Post(json));42
}43
44
pub fn resize(&self, width: Option<u32>, height: Option<u32>) {45
self.send(DialogCommand::Resize { width, height });46
}47
48
pub fn close(&self) {49
self.send(DialogCommand::Close);50
}51
52
fn send(&self, command: DialogCommand) {53
let request = UiRequest::Dialog {54
id: self.id,55
command,56
};57
if self.requests.send(request).is_ok() {58
(self.waker)();59
}60
}61
}@@ -12,8 +12,8 @@ use webview2_com::Microsoft::Web::WebView2::Win32::*;
12
12
use webview2_com::{
13
13
CallDevToolsProtocolMethodCompletedHandler, CoreWebView2EnvironmentOptions,
14
14
CreateCoreWebView2ControllerCompletedHandler, CreateCoreWebView2EnvironmentCompletedHandler,
15
DevToolsProtocolEventReceivedEventHandler, NavigationCompletedEventHandler, ProcessFailedEventHandler,
16
SourceChangedEventHandler, take_pwstr,
15
DevToolsProtocolEventReceivedEventHandler, NavigationCompletedEventHandler,
16
ProcessFailedEventHandler, SourceChangedEventHandler, take_pwstr,
17
17
};
18
18
use windows::Win32::Foundation::{HINSTANCE, HWND, LPARAM, LRESULT, RECT, WPARAM};
19
19
use windows::Win32::System::Com::{COINIT_APARTMENTTHREADED, CoInitializeEx};
@@ -22,6 +22,7 @@ use windows::Win32::UI::WindowsAndMessaging::*;
22
22
use windows::core::{HSTRING, Interface, PCWSTR, PWSTR, w};
23
23
24
24
use crate::fanout::Subscribers;
25
use crate::host_dialog::{self, Dialog};
25
26
use crate::transport::{HostState, UiRequest, WebViewTransport};
26
27
use crate::{BROWSER_ARGUMENTS, FORWARDED_EVENTS};
27
28
@@ -47,10 +48,12 @@ struct View {
47
48
webview: ICoreWebView2,
48
49
}
49
50
50
struct Shared {
51
pub(crate) struct Shared {
51
52
config: HostConfig,
52
53
windows: HashMap<App, HWND>,
53
54
views: RefCell<HashMap<App, View>>,
55
pub(crate) environment: RefCell<Option<ICoreWebView2Environment>>,
56
pub(crate) dialogs: RefCell<HashMap<u64, Dialog>>,
54
57
subscribers: RefCell<Subscribers>,
55
58
state: watch::Sender<HostState>,
56
59
requests: mpsc::Receiver<UiRequest>,
@@ -62,7 +65,7 @@ thread_local! {
62
65
static SHARED: RefCell<Option<Rc<Shared>>> = const { RefCell::new(None) };
63
66
}
64
67
65
fn shared() -> Option<Rc<Shared>> {
68
pub(crate) fn shared() -> Option<Rc<Shared>> {
66
69
SHARED.with(|slot| slot.borrow().clone())
67
70
}
68
71
@@ -76,7 +79,8 @@ pub fn start(config: HostConfig) -> Arc<WebViewTransport> {
76
79
.name("webview2".into())
77
80
.spawn(move || run(config, requests, state_sender, window_sender));
78
81
if let Err(error) = spawned {
79
failure_state.send_modify(|state| state.failure = Some(format!("no webview thread: {error}")));
82
failure_state
83
.send_modify(|state| state.failure = Some(format!("no webview thread: {error}")));
80
84
}
81
85
let window = window_receiver.recv().ok();
82
86
let waker = Arc::new(move || {
@@ -108,6 +112,8 @@ fn run(
108
112
config,
109
113
windows,
110
114
views: RefCell::new(HashMap::new()),
115
environment: RefCell::new(None),
116
dialogs: RefCell::new(HashMap::new()),
111
117
subscribers: RefCell::new(Subscribers::default()),
112
118
state,
113
119
requests,
@@ -173,14 +179,18 @@ fn load(shared: &Rc<Shared>) {
173
179
174
180
fn create_views(shared: &Rc<Shared>) -> std::result::Result<(), String> {
175
181
let environment = create_environment(&shared.config.user_data_folder)?;
182
*shared.environment.borrow_mut() = Some(environment.clone());
176
183
for app in App::ALL {
177
let view = create_view(shared, &environment, app).map_err(|error| format!("{app} webview: {error}"))?;
184
let view = create_view(shared, &environment, app)
185
.map_err(|error| format!("{app} webview: {error}"))?;
178
186
shared.views.borrow_mut().insert(app, view);
179
187
}
180
188
Ok(())
181
189
}
182
190
183
fn create_environment(user_data_folder: &std::path::Path) -> std::result::Result<ICoreWebView2Environment, String> {
191
fn create_environment(
192
user_data_folder: &std::path::Path,
193
) -> std::result::Result<ICoreWebView2Environment, String> {
184
194
let options = CoreWebView2EnvironmentOptions::default();
185
195
unsafe {
186
196
options.set_additional_browser_arguments(BROWSER_ARGUMENTS.to_owned());
@@ -208,7 +218,11 @@ fn create_environment(user_data_folder: &std::path::Path) -> std::result::Result
208
218
.ok_or_else(|| "WebView2 runtime returned no environment".to_owned())
209
219
}
210
220
211
fn create_view(shared: &Rc<Shared>, environment: &ICoreWebView2Environment, app: App) -> windows::core::Result<View> {
221
fn create_view(
222
shared: &Rc<Shared>,
223
environment: &ICoreWebView2Environment,
224
app: App,
225
) -> windows::core::Result<View> {
212
226
let window = shared.windows[&app];
213
227
let (sender, receiver) = mpsc::channel();
214
228
let creator = environment.clone();
@@ -228,11 +242,10 @@ fn create_view(shared: &Rc<Shared>, environment: &ICoreWebView2Environment, app:
228
242
webview2_com::Error::WindowsError(error) => error,
229
243
other => windows::core::Error::new(windows::core::HRESULT(-1), other.to_string()),
230
244
})?;
231
let controller = receiver
232
.recv()
233
.ok()
234
.flatten()
235
.ok_or_else(|| windows::core::Error::new(windows::core::HRESULT(-1), "no controller"))?;
245
let controller =
246
receiver.recv().ok().flatten().ok_or_else(|| {
247
windows::core::Error::new(windows::core::HRESULT(-1), "no controller")
248
})?;
236
249
let webview = unsafe { controller.CoreWebView2() }?;
237
250
fit(window, &controller);
238
251
unsafe {
@@ -244,7 +257,10 @@ fn create_view(shared: &Rc<Shared>, environment: &ICoreWebView2Environment, app:
244
257
watch_failures(&webview, app)?;
245
258
forward_events(&webview, app)?;
246
259
unsafe { webview.Navigate(&HSTRING::from(app.start_url())) }?;
247
Ok(View { controller, webview })
260
Ok(View {
261
controller,
262
webview,
263
})
248
264
}
249
265
250
266
fn watch_source(webview: &ICoreWebView2, app: App) -> windows::core::Result<()> {
@@ -320,7 +336,9 @@ fn watch_failures(webview: &ICoreWebView2, app: App) -> windows::core::Result<()
320
336
unsafe { arguments.ProcessFailedKind(&mut kind) }?;
321
337
if kind == COREWEBVIEW2_PROCESS_FAILED_KIND_BROWSER_PROCESS_EXITED {
322
338
if !shared.restarting.replace(true) {
323
unsafe { PostMessageW(Some(shared.windows[&app]), WM_RESTART, WPARAM(0), LPARAM(0)) }?;
339
unsafe {
340
PostMessageW(Some(shared.windows[&app]), WM_RESTART, WPARAM(0), LPARAM(0))
341
}?;
324
342
}
325
343
} else if kind == COREWEBVIEW2_PROCESS_FAILED_KIND_RENDER_PROCESS_EXITED
326
344
|| kind == COREWEBVIEW2_PROCESS_FAILED_KIND_RENDER_PROCESS_UNRESPONSIVE
@@ -336,19 +354,20 @@ fn forward_events(webview: &ICoreWebView2, app: App) -> windows::core::Result<()
336
354
for name in FORWARDED_EVENTS {
337
355
let receiver = unsafe { webview.GetDevToolsProtocolEventReceiver(&HSTRING::from(name)) }?;
338
356
let mut token = 0;
339
let handler = DevToolsProtocolEventReceivedEventHandler::create(Box::new(move |_, arguments| {
340
let (Some(arguments), Some(shared)) = (arguments, shared()) else {
341
return Ok(());
342
};
343
let mut parameters = PWSTR::null();
344
unsafe { arguments.ParameterObjectAsJson(&mut parameters) }?;
345
let event = TabEvent {
346
method: name.to_owned(),
347
params: serde_json::from_str(&take_pwstr(parameters)).unwrap_or(Value::Null),
348
};
349
shared.subscribers.borrow_mut().publish(app, &event);
350
Ok(())
351
}));
357
let handler =
358
DevToolsProtocolEventReceivedEventHandler::create(Box::new(move |_, arguments| {
359
let (Some(arguments), Some(shared)) = (arguments, shared()) else {
360
return Ok(());
361
};
362
let mut parameters = PWSTR::null();
363
unsafe { arguments.ParameterObjectAsJson(&mut parameters) }?;
364
let event = TabEvent {
365
method: name.to_owned(),
366
params: serde_json::from_str(&take_pwstr(parameters)).unwrap_or(Value::Null),
367
};
368
shared.subscribers.borrow_mut().publish(app, &event);
369
Ok(())
370
}));
352
371
unsafe { receiver.add_DevToolsProtocolEventReceived(&handler, &mut token) }?;
353
372
}
354
373
Ok(())
@@ -380,11 +399,21 @@ fn on_source_changed(shared: &Shared, app: App, url: String) {
380
399
}
381
400
382
401
fn webview_of(shared: &Shared, app: App) -> Option<ICoreWebView2> {
383
shared.views.borrow().get(&app).map(|view| view.webview.clone())
402
shared
403
.views
404
.borrow()
405
.get(&app)
406
.map(|view| view.webview.clone())
384
407
}
385
408
386
409
fn current_url(shared: &Shared, app: App) -> String {
387
shared.state.borrow().urls.get(&app).cloned().unwrap_or_default()
410
shared
411
.state
412
.borrow()
413
.urls
414
.get(&app)
415
.cloned()
416
.unwrap_or_default()
388
417
}
389
418
390
419
fn drain(shared: &Rc<Shared>) {
@@ -398,6 +427,10 @@ fn drain(shared: &Rc<Shared>) {
398
427
restart(shared);
399
428
}
400
429
}
430
UiRequest::OpenDialog { id, spec, events } => {
431
host_dialog::open(shared, id, spec, events)
432
}
433
UiRequest::Dialog { id, command } => host_dialog::run(shared, id, command),
401
434
}
402
435
}
403
436
}
@@ -410,13 +443,15 @@ fn call(shared: &Shared, app: App, command: TabCommand) {
410
443
let parameters = HSTRING::from(command.params.to_string());
411
444
let pending = Rc::new(RefCell::new(Some(command)));
412
445
let answered = pending.clone();
413
let handler = CallDevToolsProtocolMethodCompletedHandler::create(Box::new(move |code, json| {
414
if let Some(command) = answered.borrow_mut().take() {
415
command.respond(answer(code, &json));
416
}
417
Ok(())
418
}));
419
if let Err(error) = unsafe { webview.CallDevToolsProtocolMethod(&method, ¶meters, &handler) }
446
let handler =
447
CallDevToolsProtocolMethodCompletedHandler::create(Box::new(move |code, json| {
448
if let Some(command) = answered.borrow_mut().take() {
449
command.respond(answer(code, &json));
450
}
451
Ok(())
452
}));
453
if let Err(error) =
454
unsafe { webview.CallDevToolsProtocolMethod(&method, ¶meters, &handler) }
420
455
&& let Some(command) = pending.borrow_mut().take()
421
456
{
422
457
let reason = format!("{}: {error}", command.method);
@@ -484,7 +519,13 @@ fn show(shared: &Shared, app: App) {
484
519
fn restart(shared: &Rc<Shared>) {
485
520
shared.state.send_modify(|state| state.ready = false);
486
521
shared.subscribers.borrow_mut().clear();
487
let views: Vec<View> = shared.views.borrow_mut().drain().map(|(_, view)| view).collect();
522
host_dialog::close_all(shared);
523
let views: Vec<View> = shared
524
.views
525
.borrow_mut()
526
.drain()
527
.map(|(_, view)| view)
528
.collect();
488
529
for view in views {
489
530
unsafe {
490
531
let _ = view.controller.Close();
@@ -494,7 +535,7 @@ fn restart(shared: &Rc<Shared>) {
494
535
shared.restarting.set(false);
495
536
}
496
537
497
fn fit(window: HWND, controller: &ICoreWebView2Controller) {
538
pub(crate) fn fit(window: HWND, controller: &ICoreWebView2Controller) {
498
539
let mut bounds = RECT::default();
499
540
unsafe {
500
541
if GetClientRect(window, &mut bounds).is_ok() {
@@ -510,7 +551,12 @@ fn app_of(shared: &Shared, window: HWND) -> Option<App> {
510
551
.find_map(|(&app, &candidate)| (candidate == window).then_some(app))
511
552
}
512
553
513
extern "system" fn window_procedure(window: HWND, message: u32, wparam: WPARAM, lparam: LPARAM) -> LRESULT {
554
extern "system" fn window_procedure(
555
window: HWND,
556
message: u32,
557
wparam: WPARAM,
558
lparam: LPARAM,
559
) -> LRESULT {
514
560
let Some(shared) = shared() else {
515
561
return unsafe { DefWindowProcW(window, message, wparam, lparam) };
516
562
};
@@ -12,8 +12,8 @@ use webview2_com::Microsoft::Web::WebView2::Win32::*;12
use webview2_com::{12
use webview2_com::{13
CallDevToolsProtocolMethodCompletedHandler, CoreWebView2EnvironmentOptions,13
CallDevToolsProtocolMethodCompletedHandler, CoreWebView2EnvironmentOptions,14
CreateCoreWebView2ControllerCompletedHandler, CreateCoreWebView2EnvironmentCompletedHandler,14
CreateCoreWebView2ControllerCompletedHandler, CreateCoreWebView2EnvironmentCompletedHandler,15
DevToolsProtocolEventReceivedEventHandler, NavigationCompletedEventHandler, ProcessFailedEventHandler,15
DevToolsProtocolEventReceivedEventHandler, NavigationCompletedEventHandler,16
SourceChangedEventHandler, take_pwstr,16
ProcessFailedEventHandler, SourceChangedEventHandler, take_pwstr,17
};17
};18
use windows::Win32::Foundation::{HINSTANCE, HWND, LPARAM, LRESULT, RECT, WPARAM};18
use windows::Win32::Foundation::{HINSTANCE, HWND, LPARAM, LRESULT, RECT, WPARAM};19
use windows::Win32::System::Com::{COINIT_APARTMENTTHREADED, CoInitializeEx};19
use windows::Win32::System::Com::{COINIT_APARTMENTTHREADED, CoInitializeEx};@@ -22,6 +22,7 @@ use windows::Win32::UI::WindowsAndMessaging::*;22
use windows::core::{HSTRING, Interface, PCWSTR, PWSTR, w};22
use windows::core::{HSTRING, Interface, PCWSTR, PWSTR, w};23
23
24
use crate::fanout::Subscribers;24
use crate::fanout::Subscribers;25
use crate::host_dialog::{self, Dialog};25
use crate::transport::{HostState, UiRequest, WebViewTransport};26
use crate::transport::{HostState, UiRequest, WebViewTransport};26
use crate::{BROWSER_ARGUMENTS, FORWARDED_EVENTS};27
use crate::{BROWSER_ARGUMENTS, FORWARDED_EVENTS};27
28
@@ -47,10 +48,12 @@ struct View {47
webview: ICoreWebView2,48
webview: ICoreWebView2,48
}49
}49
50
50
struct Shared {51
pub(crate) struct Shared {51
config: HostConfig,52
config: HostConfig,52
windows: HashMap<App, HWND>,53
windows: HashMap<App, HWND>,53
views: RefCell<HashMap<App, View>>,54
views: RefCell<HashMap<App, View>>,55
pub(crate) environment: RefCell<Option<ICoreWebView2Environment>>,56
pub(crate) dialogs: RefCell<HashMap<u64, Dialog>>,54
subscribers: RefCell<Subscribers>,57
subscribers: RefCell<Subscribers>,55
state: watch::Sender<HostState>,58
state: watch::Sender<HostState>,56
requests: mpsc::Receiver<UiRequest>,59
requests: mpsc::Receiver<UiRequest>,@@ -62,7 +65,7 @@ thread_local! {62
static SHARED: RefCell<Option<Rc<Shared>>> = const { RefCell::new(None) };65
static SHARED: RefCell<Option<Rc<Shared>>> = const { RefCell::new(None) };63
}66
}64
67
65
fn shared() -> Option<Rc<Shared>> {68
pub(crate) fn shared() -> Option<Rc<Shared>> {66
SHARED.with(|slot| slot.borrow().clone())69
SHARED.with(|slot| slot.borrow().clone())67
}70
}68
71
@@ -76,7 +79,8 @@ pub fn start(config: HostConfig) -> Arc<WebViewTransport> {76
.name("webview2".into())79
.name("webview2".into())77
.spawn(move || run(config, requests, state_sender, window_sender));80
.spawn(move || run(config, requests, state_sender, window_sender));78
if let Err(error) = spawned {81
if let Err(error) = spawned {79
failure_state.send_modify(|state| state.failure = Some(format!("no webview thread: {error}")));82
failure_state83
.send_modify(|state| state.failure = Some(format!("no webview thread: {error}")));80
}84
}81
let window = window_receiver.recv().ok();85
let window = window_receiver.recv().ok();82
let waker = Arc::new(move || {86
let waker = Arc::new(move || {@@ -108,6 +112,8 @@ fn run(108
config,112
config,109
windows,113
windows,110
views: RefCell::new(HashMap::new()),114
views: RefCell::new(HashMap::new()),115
environment: RefCell::new(None),116
dialogs: RefCell::new(HashMap::new()),111
subscribers: RefCell::new(Subscribers::default()),117
subscribers: RefCell::new(Subscribers::default()),112
state,118
state,113
requests,119
requests,@@ -173,14 +179,18 @@ fn load(shared: &Rc<Shared>) {173
179
174
fn create_views(shared: &Rc<Shared>) -> std::result::Result<(), String> {180
fn create_views(shared: &Rc<Shared>) -> std::result::Result<(), String> {175
let environment = create_environment(&shared.config.user_data_folder)?;181
let environment = create_environment(&shared.config.user_data_folder)?;182
*shared.environment.borrow_mut() = Some(environment.clone());176
for app in App::ALL {183
for app in App::ALL {177
let view = create_view(shared, &environment, app).map_err(|error| format!("{app} webview: {error}"))?;184
let view = create_view(shared, &environment, app)185
.map_err(|error| format!("{app} webview: {error}"))?;178
shared.views.borrow_mut().insert(app, view);186
shared.views.borrow_mut().insert(app, view);179
}187
}180
Ok(())188
Ok(())181
}189
}182
190
183
fn create_environment(user_data_folder: &std::path::Path) -> std::result::Result<ICoreWebView2Environment, String> {191
fn create_environment(192
user_data_folder: &std::path::Path,193
) -> std::result::Result<ICoreWebView2Environment, String> {184
let options = CoreWebView2EnvironmentOptions::default();194
let options = CoreWebView2EnvironmentOptions::default();185
unsafe {195
unsafe {186
options.set_additional_browser_arguments(BROWSER_ARGUMENTS.to_owned());196
options.set_additional_browser_arguments(BROWSER_ARGUMENTS.to_owned());@@ -208,7 +218,11 @@ fn create_environment(user_data_folder: &std::path::Path) -> std::result::Result208
.ok_or_else(|| "WebView2 runtime returned no environment".to_owned())218
.ok_or_else(|| "WebView2 runtime returned no environment".to_owned())209
}219
}210
220
211
fn create_view(shared: &Rc<Shared>, environment: &ICoreWebView2Environment, app: App) -> windows::core::Result<View> {221
fn create_view(222
shared: &Rc<Shared>,223
environment: &ICoreWebView2Environment,224
app: App,225
) -> windows::core::Result<View> {212
let window = shared.windows[&app];226
let window = shared.windows[&app];213
let (sender, receiver) = mpsc::channel();227
let (sender, receiver) = mpsc::channel();214
let creator = environment.clone();228
let creator = environment.clone();@@ -228,11 +242,10 @@ fn create_view(shared: &Rc<Shared>, environment: &ICoreWebView2Environment, app:228
webview2_com::Error::WindowsError(error) => error,242
webview2_com::Error::WindowsError(error) => error,229
other => windows::core::Error::new(windows::core::HRESULT(-1), other.to_string()),243
other => windows::core::Error::new(windows::core::HRESULT(-1), other.to_string()),230
})?;244
})?;231
let controller = receiver245
let controller =232
.recv()246
receiver.recv().ok().flatten().ok_or_else(|| {233
.ok()247
windows::core::Error::new(windows::core::HRESULT(-1), "no controller")234
.flatten()248
})?;235
.ok_or_else(|| windows::core::Error::new(windows::core::HRESULT(-1), "no controller"))?;236
let webview = unsafe { controller.CoreWebView2() }?;249
let webview = unsafe { controller.CoreWebView2() }?;237
fit(window, &controller);250
fit(window, &controller);238
unsafe {251
unsafe {@@ -244,7 +257,10 @@ fn create_view(shared: &Rc<Shared>, environment: &ICoreWebView2Environment, app:244
watch_failures(&webview, app)?;257
watch_failures(&webview, app)?;245
forward_events(&webview, app)?;258
forward_events(&webview, app)?;246
unsafe { webview.Navigate(&HSTRING::from(app.start_url())) }?;259
unsafe { webview.Navigate(&HSTRING::from(app.start_url())) }?;247
Ok(View { controller, webview })260
Ok(View {261
controller,262
webview,263
})248
}264
}249
265
250
fn watch_source(webview: &ICoreWebView2, app: App) -> windows::core::Result<()> {266
fn watch_source(webview: &ICoreWebView2, app: App) -> windows::core::Result<()> {@@ -320,7 +336,9 @@ fn watch_failures(webview: &ICoreWebView2, app: App) -> windows::core::Result<()320
unsafe { arguments.ProcessFailedKind(&mut kind) }?;336
unsafe { arguments.ProcessFailedKind(&mut kind) }?;321
if kind == COREWEBVIEW2_PROCESS_FAILED_KIND_BROWSER_PROCESS_EXITED {337
if kind == COREWEBVIEW2_PROCESS_FAILED_KIND_BROWSER_PROCESS_EXITED {322
if !shared.restarting.replace(true) {338
if !shared.restarting.replace(true) {323
unsafe { PostMessageW(Some(shared.windows[&app]), WM_RESTART, WPARAM(0), LPARAM(0)) }?;339
unsafe {340
PostMessageW(Some(shared.windows[&app]), WM_RESTART, WPARAM(0), LPARAM(0))341
}?;324
}342
}325
} else if kind == COREWEBVIEW2_PROCESS_FAILED_KIND_RENDER_PROCESS_EXITED343
} else if kind == COREWEBVIEW2_PROCESS_FAILED_KIND_RENDER_PROCESS_EXITED326
|| kind == COREWEBVIEW2_PROCESS_FAILED_KIND_RENDER_PROCESS_UNRESPONSIVE344
|| kind == COREWEBVIEW2_PROCESS_FAILED_KIND_RENDER_PROCESS_UNRESPONSIVE@@ -336,19 +354,20 @@ fn forward_events(webview: &ICoreWebView2, app: App) -> windows::core::Result<()336
for name in FORWARDED_EVENTS {354
for name in FORWARDED_EVENTS {337
let receiver = unsafe { webview.GetDevToolsProtocolEventReceiver(&HSTRING::from(name)) }?;355
let receiver = unsafe { webview.GetDevToolsProtocolEventReceiver(&HSTRING::from(name)) }?;338
let mut token = 0;356
let mut token = 0;339
let handler = DevToolsProtocolEventReceivedEventHandler::create(Box::new(move |_, arguments| {357
let handler =340
let (Some(arguments), Some(shared)) = (arguments, shared()) else {358
DevToolsProtocolEventReceivedEventHandler::create(Box::new(move |_, arguments| {341
return Ok(());359
let (Some(arguments), Some(shared)) = (arguments, shared()) else {342
};360
return Ok(());343
let mut parameters = PWSTR::null();361
};344
unsafe { arguments.ParameterObjectAsJson(&mut parameters) }?;362
let mut parameters = PWSTR::null();345
let event = TabEvent {363
unsafe { arguments.ParameterObjectAsJson(&mut parameters) }?;346
method: name.to_owned(),364
let event = TabEvent {347
params: serde_json::from_str(&take_pwstr(parameters)).unwrap_or(Value::Null),365
method: name.to_owned(),348
};366
params: serde_json::from_str(&take_pwstr(parameters)).unwrap_or(Value::Null),349
shared.subscribers.borrow_mut().publish(app, &event);367
};350
Ok(())368
shared.subscribers.borrow_mut().publish(app, &event);351
}));369
Ok(())370
}));352
unsafe { receiver.add_DevToolsProtocolEventReceived(&handler, &mut token) }?;371
unsafe { receiver.add_DevToolsProtocolEventReceived(&handler, &mut token) }?;353
}372
}354
Ok(())373
Ok(())@@ -380,11 +399,21 @@ fn on_source_changed(shared: &Shared, app: App, url: String) {380
}399
}381
400
382
fn webview_of(shared: &Shared, app: App) -> Option<ICoreWebView2> {401
fn webview_of(shared: &Shared, app: App) -> Option<ICoreWebView2> {383
shared.views.borrow().get(&app).map(|view| view.webview.clone())402
shared403
.views404
.borrow()405
.get(&app)406
.map(|view| view.webview.clone())384
}407
}385
408
386
fn current_url(shared: &Shared, app: App) -> String {409
fn current_url(shared: &Shared, app: App) -> String {387
shared.state.borrow().urls.get(&app).cloned().unwrap_or_default()410
shared411
.state412
.borrow()413
.urls414
.get(&app)415
.cloned()416
.unwrap_or_default()388
}417
}389
418
390
fn drain(shared: &Rc<Shared>) {419
fn drain(shared: &Rc<Shared>) {@@ -398,6 +427,10 @@ fn drain(shared: &Rc<Shared>) {398
restart(shared);427
restart(shared);399
}428
}400
}429
}430
UiRequest::OpenDialog { id, spec, events } => {431
host_dialog::open(shared, id, spec, events)432
}433
UiRequest::Dialog { id, command } => host_dialog::run(shared, id, command),401
}434
}402
}435
}403
}436
}@@ -410,13 +443,15 @@ fn call(shared: &Shared, app: App, command: TabCommand) {410
let parameters = HSTRING::from(command.params.to_string());443
let parameters = HSTRING::from(command.params.to_string());411
let pending = Rc::new(RefCell::new(Some(command)));444
let pending = Rc::new(RefCell::new(Some(command)));412
let answered = pending.clone();445
let answered = pending.clone();413
let handler = CallDevToolsProtocolMethodCompletedHandler::create(Box::new(move |code, json| {446
let handler =414
if let Some(command) = answered.borrow_mut().take() {447
CallDevToolsProtocolMethodCompletedHandler::create(Box::new(move |code, json| {415
command.respond(answer(code, &json));448
if let Some(command) = answered.borrow_mut().take() {416
}449
command.respond(answer(code, &json));417
Ok(())450
}418
}));451
Ok(())419
if let Err(error) = unsafe { webview.CallDevToolsProtocolMethod(&method, ¶meters, &handler) }452
}));453
if let Err(error) =454
unsafe { webview.CallDevToolsProtocolMethod(&method, ¶meters, &handler) }420
&& let Some(command) = pending.borrow_mut().take()455
&& let Some(command) = pending.borrow_mut().take()421
{456
{422
let reason = format!("{}: {error}", command.method);457
let reason = format!("{}: {error}", command.method);@@ -484,7 +519,13 @@ fn show(shared: &Shared, app: App) {484
fn restart(shared: &Rc<Shared>) {519
fn restart(shared: &Rc<Shared>) {485
shared.state.send_modify(|state| state.ready = false);520
shared.state.send_modify(|state| state.ready = false);486
shared.subscribers.borrow_mut().clear();521
shared.subscribers.borrow_mut().clear();487
let views: Vec<View> = shared.views.borrow_mut().drain().map(|(_, view)| view).collect();522
host_dialog::close_all(shared);523
let views: Vec<View> = shared524
.views525
.borrow_mut()526
.drain()527
.map(|(_, view)| view)528
.collect();488
for view in views {529
for view in views {489
unsafe {530
unsafe {490
let _ = view.controller.Close();531
let _ = view.controller.Close();@@ -494,7 +535,7 @@ fn restart(shared: &Rc<Shared>) {494
shared.restarting.set(false);535
shared.restarting.set(false);495
}536
}496
537
497
fn fit(window: HWND, controller: &ICoreWebView2Controller) {538
pub(crate) fn fit(window: HWND, controller: &ICoreWebView2Controller) {498
let mut bounds = RECT::default();539
let mut bounds = RECT::default();499
unsafe {540
unsafe {500
if GetClientRect(window, &mut bounds).is_ok() {541
if GetClientRect(window, &mut bounds).is_ok() {@@ -510,7 +551,12 @@ fn app_of(shared: &Shared, window: HWND) -> Option<App> {510
.find_map(|(&app, &candidate)| (candidate == window).then_some(app))551
.find_map(|(&app, &candidate)| (candidate == window).then_some(app))511
}552
}512
553
513
extern "system" fn window_procedure(window: HWND, message: u32, wparam: WPARAM, lparam: LPARAM) -> LRESULT {554
extern "system" fn window_procedure(555
window: HWND,556
message: u32,557
wparam: WPARAM,558
lparam: LPARAM,559
) -> LRESULT {514
let Some(shared) = shared() else {560
let Some(shared) = shared() else {515
return unsafe { DefWindowProcW(window, message, wparam, lparam) };561
return unsafe { DefWindowProcW(window, message, wparam, lparam) };516
};562
};@@ -0,0 +1,464 @@
1
use std::rc::Rc;
2
3
use tokio::sync::mpsc::UnboundedSender;
4
use webview2_com::Microsoft::Web::WebView2::Win32::*;
5
use webview2_com::{
6
AcceleratorKeyPressedEventHandler, CreateCoreWebView2ControllerCompletedHandler,
7
NewWindowRequestedEventHandler, WebMessageReceivedEventHandler,
8
WebResourceRequestedEventHandler, take_pwstr,
9
};
10
use windows::Win32::Foundation::{COLORREF, HINSTANCE, HWND, LPARAM, LRESULT, RECT, WPARAM};
11
use windows::Win32::Graphics::Gdi::{
12
CreateSolidBrush, GetMonitorInfoW, MONITOR_DEFAULTTONEAREST, MONITOR_DEFAULTTOPRIMARY,
13
MONITOR_FROM_FLAGS, MONITORINFO, MonitorFromWindow,
14
};
15
use windows::Win32::System::LibraryLoader::GetModuleHandleW;
16
use windows::Win32::UI::HiDpi::{AdjustWindowRectExForDpi, GetDpiForWindow};
17
use windows::Win32::UI::Shell::SHCreateMemStream;
18
use windows::Win32::UI::WindowsAndMessaging::*;
19
use windows::core::{HSTRING, Interface, PWSTR, w};
20
21
use crate::dialog::{DialogCommand, DialogEvent, DialogSpec};
22
use crate::host::{Shared, fit, shared as running_host};
23
24
const DIALOG_CLASS: windows::core::PCWSTR = w!("RustyTeamsDialog");
25
const DIALOG_STYLE: WINDOW_STYLE = WINDOW_STYLE(WS_CAPTION.0 | WS_SYSMENU.0);
26
const BASE_DPI: u32 = 96;
27
const VIRTUAL_KEY_ESCAPE: u32 = 0x1B;
28
const PAGE_HEADERS: windows::core::PCWSTR =
29
w!("Content-Type: text/html; charset=utf-8\r\nCache-Control: no-store");
30
const NEW_WINDOW_KIND: &str = "newWindow";
31
32
struct DialogView {
33
controller: ICoreWebView2Controller,
34
webview: ICoreWebView2,
35
}
36
37
pub(crate) struct Dialog {
38
window: HWND,
39
view: Option<DialogView>,
40
events: UnboundedSender<DialogEvent>,
41
}
42
43
struct HostPage {
44
url: String,
45
html: String,
46
}
47
48
pub(crate) fn open(
49
shared: &Rc<Shared>,
50
id: u64,
51
spec: DialogSpec,
52
events: UnboundedSender<DialogEvent>,
53
) {
54
let Some(environment) = shared.environment.borrow().clone() else {
55
let _ = events.send(DialogEvent::Closed);
56
return;
57
};
58
let Ok(window) = create_window(&spec) else {
59
let _ = events.send(DialogEvent::Closed);
60
return;
61
};
62
shared.dialogs.borrow_mut().insert(
63
id,
64
Dialog {
65
window,
66
view: None,
67
events,
68
},
69
);
70
unsafe {
71
let _ = ShowWindow(window, SW_SHOW);
72
let _ = SetForegroundWindow(window);
73
}
74
let page = HostPage {
75
url: spec.page_url,
76
html: spec.page_html,
77
};
78
let creator = environment.clone();
79
let handler =
80
CreateCoreWebView2ControllerCompletedHandler::create(Box::new(move |code, controller| {
81
let Some(shared) = running_host() else {
82
return Ok(());
83
};
84
let attached = code
85
.and_then(|()| {
86
controller.ok_or_else(|| windows::core::Error::from(windows::core::HRESULT(-1)))
87
})
88
.and_then(|controller| {
89
attach(&shared, id, &environment, controller, page, spec.background)
90
});
91
if attached.is_err() {
92
close(&shared, id);
93
}
94
Ok(())
95
}));
96
if unsafe { creator.CreateCoreWebView2Controller(window, &handler) }.is_err() {
97
close(shared, id);
98
}
99
}
100
101
pub(crate) fn run(shared: &Rc<Shared>, id: u64, command: DialogCommand) {
102
match command {
103
DialogCommand::Post(json) => {
104
let webview = shared
105
.dialogs
106
.borrow()
107
.get(&id)
108
.and_then(|dialog| dialog.view.as_ref().map(|view| view.webview.clone()));
109
if let Some(webview) = webview {
110
unsafe {
111
let _ = webview.PostWebMessageAsJson(&HSTRING::from(json));
112
}
113
}
114
}
115
DialogCommand::Resize { width, height } => resize(shared, id, width, height),
116
DialogCommand::Close => close(shared, id),
117
}
118
}
119
120
pub(crate) fn close(shared: &Rc<Shared>, id: u64) {
121
let Some(dialog) = shared.dialogs.borrow_mut().remove(&id) else {
122
return;
123
};
124
unsafe {
125
if let Some(view) = &dialog.view {
126
let _ = view.controller.Close();
127
}
128
let _ = DestroyWindow(dialog.window);
129
}
130
let _ = dialog.events.send(DialogEvent::Closed);
131
}
132
133
pub(crate) fn close_all(shared: &Rc<Shared>) {
134
let ids: Vec<u64> = shared.dialogs.borrow().keys().copied().collect();
135
for id in ids {
136
close(shared, id);
137
}
138
}
139
140
fn id_of(shared: &Shared, window: HWND) -> Option<u64> {
141
shared
142
.dialogs
143
.borrow()
144
.iter()
145
.find_map(|(&id, dialog)| (dialog.window == window).then_some(id))
146
}
147
148
fn emit(id: u64, event: DialogEvent) {
149
if let Some(shared) = running_host()
150
&& let Some(dialog) = shared.dialogs.borrow().get(&id)
151
{
152
let _ = dialog.events.send(event);
153
}
154
}
155
156
fn work_area(window: HWND, flags: MONITOR_FROM_FLAGS) -> RECT {
157
let mut info = MONITORINFO {
158
cbSize: std::mem::size_of::<MONITORINFO>() as u32,
159
..Default::default()
160
};
161
unsafe {
162
let monitor = MonitorFromWindow(window, flags);
163
let _ = GetMonitorInfoW(monitor, &mut info);
164
}
165
info.rcWork
166
}
167
168
fn outer_size(client_width: i32, client_height: i32, dpi: u32, work: RECT) -> (i32, i32) {
169
let mut frame = RECT {
170
left: 0,
171
top: 0,
172
right: client_width,
173
bottom: client_height,
174
};
175
unsafe {
176
let _ = AdjustWindowRectExForDpi(
177
&mut frame,
178
DIALOG_STYLE,
179
false,
180
WINDOW_EX_STYLE::default(),
181
dpi,
182
);
183
}
184
(
185
(frame.right - frame.left).min(work.right - work.left),
186
(frame.bottom - frame.top).min(work.bottom - work.top),
187
)
188
}
189
190
fn scaled(logical: u32, dpi: u32) -> i32 {
191
(logical as u64 * dpi as u64 / BASE_DPI as u64) as i32
192
}
193
194
fn create_window(spec: &DialogSpec) -> windows::core::Result<HWND> {
195
let instance = HINSTANCE(unsafe { GetModuleHandleW(None) }?.0);
196
let blue_green_red =
197
(spec.background & 0xff) << 16 | (spec.background & 0xff00) | (spec.background >> 16);
198
let class = WNDCLASSW {
199
lpfnWndProc: Some(dialog_procedure),
200
hInstance: instance,
201
lpszClassName: DIALOG_CLASS,
202
hbrBackground: unsafe { CreateSolidBrush(COLORREF(blue_green_red)) },
203
..Default::default()
204
};
205
unsafe { RegisterClassW(&class) };
206
let owner = spec.owner.map(|raw| HWND(raw as *mut _));
207
let (dpi, work, owner_bounds) = match owner {
208
Some(owner) => {
209
let mut bounds = RECT::default();
210
unsafe {
211
let _ = GetWindowRect(owner, &mut bounds);
212
}
213
let dpi = unsafe { GetDpiForWindow(owner) }.max(BASE_DPI);
214
(
215
dpi,
216
work_area(owner, MONITOR_DEFAULTTONEAREST),
217
Some(bounds),
218
)
219
}
220
None => (
221
BASE_DPI,
222
work_area(HWND::default(), MONITOR_DEFAULTTOPRIMARY),
223
None,
224
),
225
};
226
let (width, height) = outer_size(scaled(spec.width, dpi), scaled(spec.height, dpi), dpi, work);
227
let anchor = owner_bounds.unwrap_or(work);
228
let left = (anchor.left + (anchor.right - anchor.left - width) / 2)
229
.clamp(work.left, (work.right - width).max(work.left));
230
let top = (anchor.top + (anchor.bottom - anchor.top - height) / 2)
231
.clamp(work.top, (work.bottom - height).max(work.top));
232
unsafe {
233
CreateWindowExW(
234
WINDOW_EX_STYLE::default(),
235
DIALOG_CLASS,
236
&HSTRING::from(spec.title.as_str()),
237
DIALOG_STYLE,
238
left,
239
top,
240
width,
241
height,
242
owner,
243
None,
244
Some(instance),
245
None,
246
)
247
}
248
}
249
250
fn resize(shared: &Rc<Shared>, id: u64, width: Option<u32>, height: Option<u32>) {
251
let Some(window) = shared.dialogs.borrow().get(&id).map(|dialog| dialog.window) else {
252
return;
253
};
254
let dpi = unsafe { GetDpiForWindow(window) }.max(BASE_DPI);
255
let mut client = RECT::default();
256
unsafe {
257
let _ = GetClientRect(window, &mut client);
258
}
259
let client_width = width.map_or(client.right - client.left, |width| scaled(width, dpi));
260
let client_height = height.map_or(client.bottom - client.top, |height| scaled(height, dpi));
261
let (outer_width, outer_height) = outer_size(
262
client_width,
263
client_height,
264
dpi,
265
work_area(window, MONITOR_DEFAULTTONEAREST),
266
);
267
unsafe {
268
let _ = SetWindowPos(
269
window,
270
None,
271
0,
272
0,
273
outer_width,
274
outer_height,
275
SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE,
276
);
277
}
278
}
279
280
fn attach(
281
shared: &Rc<Shared>,
282
id: u64,
283
environment: &ICoreWebView2Environment,
284
controller: ICoreWebView2Controller,
285
page: HostPage,
286
background: u32,
287
) -> windows::core::Result<()> {
288
let Some(window) = shared.dialogs.borrow().get(&id).map(|dialog| dialog.window) else {
289
unsafe { controller.Close() }?;
290
return Ok(());
291
};
292
let webview = unsafe { controller.CoreWebView2() }?;
293
fit(window, &controller);
294
unsafe {
295
controller
296
.cast::<ICoreWebView2Controller2>()?
297
.SetDefaultBackgroundColor(COREWEBVIEW2_COLOR {
298
A: 255,
299
R: (background >> 16) as u8,
300
G: (background >> 8) as u8,
301
B: background as u8,
302
})?;
303
webview.Settings()?.SetIsStatusBarEnabled(false)?;
304
}
305
serve_host_page(&webview, environment, &page)?;
306
forward_messages(&webview, id, &page.url)?;
307
forward_new_windows(&webview, id)?;
308
close_on_escape(&controller, window)?;
309
unsafe {
310
controller.SetIsVisible(true)?;
311
webview.Navigate(&HSTRING::from(page.url.as_str()))?;
312
}
313
if let Some(dialog) = shared.dialogs.borrow_mut().get_mut(&id) {
314
dialog.view = Some(DialogView {
315
controller,
316
webview,
317
});
318
}
319
Ok(())
320
}
321
322
fn serve_host_page(
323
webview: &ICoreWebView2,
324
environment: &ICoreWebView2Environment,
325
page: &HostPage,
326
) -> windows::core::Result<()> {
327
let filter = HSTRING::from(page.url.as_str());
328
unsafe {
329
match webview.cast::<ICoreWebView2_22>() {
330
Ok(webview) => webview.AddWebResourceRequestedFilterWithRequestSourceKinds(
331
&filter,
332
COREWEBVIEW2_WEB_RESOURCE_CONTEXT_DOCUMENT,
333
COREWEBVIEW2_WEB_RESOURCE_REQUEST_SOURCE_KINDS_ALL,
334
)?,
335
Err(_) => webview.AddWebResourceRequestedFilter(
336
&filter,
337
COREWEBVIEW2_WEB_RESOURCE_CONTEXT_DOCUMENT,
338
)?,
339
}
340
}
341
let environment = environment.clone();
342
let (url, html) = (page.url.clone(), page.html.clone());
343
let handler = WebResourceRequestedEventHandler::create(Box::new(move |_, arguments| {
344
let Some(arguments) = arguments else {
345
return Ok(());
346
};
347
let request = unsafe { arguments.Request() }?;
348
let mut requested = PWSTR::null();
349
unsafe { request.Uri(&mut requested) }?;
350
if take_pwstr(requested) != url {
351
return Ok(());
352
}
353
let stream = unsafe { SHCreateMemStream(Some(html.as_bytes())) }
354
.ok_or_else(|| windows::core::Error::from(windows::core::HRESULT(-1)))?;
355
let response =
356
unsafe { environment.CreateWebResourceResponse(&stream, 200, w!("OK"), PAGE_HEADERS) }?;
357
unsafe { arguments.SetResponse(&response) }
358
}));
359
let mut token = 0;
360
unsafe { webview.add_WebResourceRequested(&handler, &mut token) }
361
}
362
363
fn forward_messages(webview: &ICoreWebView2, id: u64, page_url: &str) -> windows::core::Result<()> {
364
let page_url = page_url.to_owned();
365
let handler = WebMessageReceivedEventHandler::create(Box::new(move |_, arguments| {
366
let Some(arguments) = arguments else {
367
return Ok(());
368
};
369
let mut source = PWSTR::null();
370
unsafe { arguments.Source(&mut source) }?;
371
if take_pwstr(source) != page_url {
372
return Ok(());
373
}
374
let mut message = PWSTR::null();
375
if unsafe { arguments.TryGetWebMessageAsString(&mut message) }.is_ok() {
376
emit(id, DialogEvent::Message(take_pwstr(message)));
377
}
378
Ok(())
379
}));
380
let mut token = 0;
381
unsafe { webview.add_WebMessageReceived(&handler, &mut token) }
382
}
383
384
fn forward_new_windows(webview: &ICoreWebView2, id: u64) -> windows::core::Result<()> {
385
let handler = NewWindowRequestedEventHandler::create(Box::new(move |_, arguments| {
386
let Some(arguments) = arguments else {
387
return Ok(());
388
};
389
let mut target = PWSTR::null();
390
unsafe {
391
arguments.Uri(&mut target)?;
392
arguments.SetHandled(true)?;
393
}
394
let message = serde_json::json!({"kind": NEW_WINDOW_KIND, "url": take_pwstr(target)});
395
emit(id, DialogEvent::Message(message.to_string()));
396
Ok(())
397
}));
398
let mut token = 0;
399
unsafe { webview.add_NewWindowRequested(&handler, &mut token) }
400
}
401
402
fn close_on_escape(
403
controller: &ICoreWebView2Controller,
404
window: HWND,
405
) -> windows::core::Result<()> {
406
let handler = AcceleratorKeyPressedEventHandler::create(Box::new(move |_, arguments| {
407
let Some(arguments) = arguments else {
408
return Ok(());
409
};
410
let mut kind = COREWEBVIEW2_KEY_EVENT_KIND::default();
411
let mut key = 0;
412
unsafe {
413
arguments.KeyEventKind(&mut kind)?;
414
arguments.VirtualKey(&mut key)?;
415
}
416
if kind == COREWEBVIEW2_KEY_EVENT_KIND_KEY_DOWN && key == VIRTUAL_KEY_ESCAPE {
417
unsafe {
418
arguments.SetHandled(true)?;
419
PostMessageW(Some(window), WM_CLOSE, WPARAM(0), LPARAM(0))?;
420
}
421
}
422
Ok(())
423
}));
424
let mut token = 0;
425
unsafe { controller.add_AcceleratorKeyPressed(&handler, &mut token) }
426
}
427
428
extern "system" fn dialog_procedure(
429
window: HWND,
430
message: u32,
431
wparam: WPARAM,
432
lparam: LPARAM,
433
) -> LRESULT {
434
let Some(shared) = running_host() else {
435
return unsafe { DefWindowProcW(window, message, wparam, lparam) };
436
};
437
match message {
438
WM_SIZE => {
439
let id = id_of(&shared, window);
440
let controller = id.and_then(|id| {
441
shared
442
.dialogs
443
.borrow()
444
.get(&id)
445
.and_then(|dialog| dialog.view.as_ref().map(|view| view.controller.clone()))
446
});
447
if let Some(controller) = controller {
448
fit(window, &controller);
449
}
450
LRESULT(0)
451
}
452
WM_CLOSE | WM_DESTROY => {
453
if let Some(id) = id_of(&shared, window) {
454
close(&shared, id);
455
}
456
if message == WM_CLOSE {
457
LRESULT(0)
458
} else {
459
unsafe { DefWindowProcW(window, message, wparam, lparam) }
460
}
461
}
462
_ => unsafe { DefWindowProcW(window, message, wparam, lparam) },
463
}
464
}
@@ -0,0 +1,464 @@1
use std::rc::Rc;2
3
use tokio::sync::mpsc::UnboundedSender;4
use webview2_com::Microsoft::Web::WebView2::Win32::*;5
use webview2_com::{6
AcceleratorKeyPressedEventHandler, CreateCoreWebView2ControllerCompletedHandler,7
NewWindowRequestedEventHandler, WebMessageReceivedEventHandler,8
WebResourceRequestedEventHandler, take_pwstr,9
};10
use windows::Win32::Foundation::{COLORREF, HINSTANCE, HWND, LPARAM, LRESULT, RECT, WPARAM};11
use windows::Win32::Graphics::Gdi::{12
CreateSolidBrush, GetMonitorInfoW, MONITOR_DEFAULTTONEAREST, MONITOR_DEFAULTTOPRIMARY,13
MONITOR_FROM_FLAGS, MONITORINFO, MonitorFromWindow,14
};15
use windows::Win32::System::LibraryLoader::GetModuleHandleW;16
use windows::Win32::UI::HiDpi::{AdjustWindowRectExForDpi, GetDpiForWindow};17
use windows::Win32::UI::Shell::SHCreateMemStream;18
use windows::Win32::UI::WindowsAndMessaging::*;19
use windows::core::{HSTRING, Interface, PWSTR, w};20
21
use crate::dialog::{DialogCommand, DialogEvent, DialogSpec};22
use crate::host::{Shared, fit, shared as running_host};23
24
const DIALOG_CLASS: windows::core::PCWSTR = w!("RustyTeamsDialog");25
const DIALOG_STYLE: WINDOW_STYLE = WINDOW_STYLE(WS_CAPTION.0 | WS_SYSMENU.0);26
const BASE_DPI: u32 = 96;27
const VIRTUAL_KEY_ESCAPE: u32 = 0x1B;28
const PAGE_HEADERS: windows::core::PCWSTR =29
w!("Content-Type: text/html; charset=utf-8\r\nCache-Control: no-store");30
const NEW_WINDOW_KIND: &str = "newWindow";31
32
struct DialogView {33
controller: ICoreWebView2Controller,34
webview: ICoreWebView2,35
}36
37
pub(crate) struct Dialog {38
window: HWND,39
view: Option<DialogView>,40
events: UnboundedSender<DialogEvent>,41
}42
43
struct HostPage {44
url: String,45
html: String,46
}47
48
pub(crate) fn open(49
shared: &Rc<Shared>,50
id: u64,51
spec: DialogSpec,52
events: UnboundedSender<DialogEvent>,53
) {54
let Some(environment) = shared.environment.borrow().clone() else {55
let _ = events.send(DialogEvent::Closed);56
return;57
};58
let Ok(window) = create_window(&spec) else {59
let _ = events.send(DialogEvent::Closed);60
return;61
};62
shared.dialogs.borrow_mut().insert(63
id,64
Dialog {65
window,66
view: None,67
events,68
},69
);70
unsafe {71
let _ = ShowWindow(window, SW_SHOW);72
let _ = SetForegroundWindow(window);73
}74
let page = HostPage {75
url: spec.page_url,76
html: spec.page_html,77
};78
let creator = environment.clone();79
let handler =80
CreateCoreWebView2ControllerCompletedHandler::create(Box::new(move |code, controller| {81
let Some(shared) = running_host() else {82
return Ok(());83
};84
let attached = code85
.and_then(|()| {86
controller.ok_or_else(|| windows::core::Error::from(windows::core::HRESULT(-1)))87
})88
.and_then(|controller| {89
attach(&shared, id, &environment, controller, page, spec.background)90
});91
if attached.is_err() {92
close(&shared, id);93
}94
Ok(())95
}));96
if unsafe { creator.CreateCoreWebView2Controller(window, &handler) }.is_err() {97
close(shared, id);98
}99
}100
101
pub(crate) fn run(shared: &Rc<Shared>, id: u64, command: DialogCommand) {102
match command {103
DialogCommand::Post(json) => {104
let webview = shared105
.dialogs106
.borrow()107
.get(&id)108
.and_then(|dialog| dialog.view.as_ref().map(|view| view.webview.clone()));109
if let Some(webview) = webview {110
unsafe {111
let _ = webview.PostWebMessageAsJson(&HSTRING::from(json));112
}113
}114
}115
DialogCommand::Resize { width, height } => resize(shared, id, width, height),116
DialogCommand::Close => close(shared, id),117
}118
}119
120
pub(crate) fn close(shared: &Rc<Shared>, id: u64) {121
let Some(dialog) = shared.dialogs.borrow_mut().remove(&id) else {122
return;123
};124
unsafe {125
if let Some(view) = &dialog.view {126
let _ = view.controller.Close();127
}128
let _ = DestroyWindow(dialog.window);129
}130
let _ = dialog.events.send(DialogEvent::Closed);131
}132
133
pub(crate) fn close_all(shared: &Rc<Shared>) {134
let ids: Vec<u64> = shared.dialogs.borrow().keys().copied().collect();135
for id in ids {136
close(shared, id);137
}138
}139
140
fn id_of(shared: &Shared, window: HWND) -> Option<u64> {141
shared142
.dialogs143
.borrow()144
.iter()145
.find_map(|(&id, dialog)| (dialog.window == window).then_some(id))146
}147
148
fn emit(id: u64, event: DialogEvent) {149
if let Some(shared) = running_host()150
&& let Some(dialog) = shared.dialogs.borrow().get(&id)151
{152
let _ = dialog.events.send(event);153
}154
}155
156
fn work_area(window: HWND, flags: MONITOR_FROM_FLAGS) -> RECT {157
let mut info = MONITORINFO {158
cbSize: std::mem::size_of::<MONITORINFO>() as u32,159
..Default::default()160
};161
unsafe {162
let monitor = MonitorFromWindow(window, flags);163
let _ = GetMonitorInfoW(monitor, &mut info);164
}165
info.rcWork166
}167
168
fn outer_size(client_width: i32, client_height: i32, dpi: u32, work: RECT) -> (i32, i32) {169
let mut frame = RECT {170
left: 0,171
top: 0,172
right: client_width,173
bottom: client_height,174
};175
unsafe {176
let _ = AdjustWindowRectExForDpi(177
&mut frame,178
DIALOG_STYLE,179
false,180
WINDOW_EX_STYLE::default(),181
dpi,182
);183
}184
(185
(frame.right - frame.left).min(work.right - work.left),186
(frame.bottom - frame.top).min(work.bottom - work.top),187
)188
}189
190
fn scaled(logical: u32, dpi: u32) -> i32 {191
(logical as u64 * dpi as u64 / BASE_DPI as u64) as i32192
}193
194
fn create_window(spec: &DialogSpec) -> windows::core::Result<HWND> {195
let instance = HINSTANCE(unsafe { GetModuleHandleW(None) }?.0);196
let blue_green_red =197
(spec.background & 0xff) << 16 | (spec.background & 0xff00) | (spec.background >> 16);198
let class = WNDCLASSW {199
lpfnWndProc: Some(dialog_procedure),200
hInstance: instance,201
lpszClassName: DIALOG_CLASS,202
hbrBackground: unsafe { CreateSolidBrush(COLORREF(blue_green_red)) },203
..Default::default()204
};205
unsafe { RegisterClassW(&class) };206
let owner = spec.owner.map(|raw| HWND(raw as *mut _));207
let (dpi, work, owner_bounds) = match owner {208
Some(owner) => {209
let mut bounds = RECT::default();210
unsafe {211
let _ = GetWindowRect(owner, &mut bounds);212
}213
let dpi = unsafe { GetDpiForWindow(owner) }.max(BASE_DPI);214
(215
dpi,216
work_area(owner, MONITOR_DEFAULTTONEAREST),217
Some(bounds),218
)219
}220
None => (221
BASE_DPI,222
work_area(HWND::default(), MONITOR_DEFAULTTOPRIMARY),223
None,224
),225
};226
let (width, height) = outer_size(scaled(spec.width, dpi), scaled(spec.height, dpi), dpi, work);227
let anchor = owner_bounds.unwrap_or(work);228
let left = (anchor.left + (anchor.right - anchor.left - width) / 2)229
.clamp(work.left, (work.right - width).max(work.left));230
let top = (anchor.top + (anchor.bottom - anchor.top - height) / 2)231
.clamp(work.top, (work.bottom - height).max(work.top));232
unsafe {233
CreateWindowExW(234
WINDOW_EX_STYLE::default(),235
DIALOG_CLASS,236
&HSTRING::from(spec.title.as_str()),237
DIALOG_STYLE,238
left,239
top,240
width,241
height,242
owner,243
None,244
Some(instance),245
None,246
)247
}248
}249
250
fn resize(shared: &Rc<Shared>, id: u64, width: Option<u32>, height: Option<u32>) {251
let Some(window) = shared.dialogs.borrow().get(&id).map(|dialog| dialog.window) else {252
return;253
};254
let dpi = unsafe { GetDpiForWindow(window) }.max(BASE_DPI);255
let mut client = RECT::default();256
unsafe {257
let _ = GetClientRect(window, &mut client);258
}259
let client_width = width.map_or(client.right - client.left, |width| scaled(width, dpi));260
let client_height = height.map_or(client.bottom - client.top, |height| scaled(height, dpi));261
let (outer_width, outer_height) = outer_size(262
client_width,263
client_height,264
dpi,265
work_area(window, MONITOR_DEFAULTTONEAREST),266
);267
unsafe {268
let _ = SetWindowPos(269
window,270
None,271
0,272
0,273
outer_width,274
outer_height,275
SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE,276
);277
}278
}279
280
fn attach(281
shared: &Rc<Shared>,282
id: u64,283
environment: &ICoreWebView2Environment,284
controller: ICoreWebView2Controller,285
page: HostPage,286
background: u32,287
) -> windows::core::Result<()> {288
let Some(window) = shared.dialogs.borrow().get(&id).map(|dialog| dialog.window) else {289
unsafe { controller.Close() }?;290
return Ok(());291
};292
let webview = unsafe { controller.CoreWebView2() }?;293
fit(window, &controller);294
unsafe {295
controller296
.cast::<ICoreWebView2Controller2>()?297
.SetDefaultBackgroundColor(COREWEBVIEW2_COLOR {298
A: 255,299
R: (background >> 16) as u8,300
G: (background >> 8) as u8,301
B: background as u8,302
})?;303
webview.Settings()?.SetIsStatusBarEnabled(false)?;304
}305
serve_host_page(&webview, environment, &page)?;306
forward_messages(&webview, id, &page.url)?;307
forward_new_windows(&webview, id)?;308
close_on_escape(&controller, window)?;309
unsafe {310
controller.SetIsVisible(true)?;311
webview.Navigate(&HSTRING::from(page.url.as_str()))?;312
}313
if let Some(dialog) = shared.dialogs.borrow_mut().get_mut(&id) {314
dialog.view = Some(DialogView {315
controller,316
webview,317
});318
}319
Ok(())320
}321
322
fn serve_host_page(323
webview: &ICoreWebView2,324
environment: &ICoreWebView2Environment,325
page: &HostPage,326
) -> windows::core::Result<()> {327
let filter = HSTRING::from(page.url.as_str());328
unsafe {329
match webview.cast::<ICoreWebView2_22>() {330
Ok(webview) => webview.AddWebResourceRequestedFilterWithRequestSourceKinds(331
&filter,332
COREWEBVIEW2_WEB_RESOURCE_CONTEXT_DOCUMENT,333
COREWEBVIEW2_WEB_RESOURCE_REQUEST_SOURCE_KINDS_ALL,334
)?,335
Err(_) => webview.AddWebResourceRequestedFilter(336
&filter,337
COREWEBVIEW2_WEB_RESOURCE_CONTEXT_DOCUMENT,338
)?,339
}340
}341
let environment = environment.clone();342
let (url, html) = (page.url.clone(), page.html.clone());343
let handler = WebResourceRequestedEventHandler::create(Box::new(move |_, arguments| {344
let Some(arguments) = arguments else {345
return Ok(());346
};347
let request = unsafe { arguments.Request() }?;348
let mut requested = PWSTR::null();349
unsafe { request.Uri(&mut requested) }?;350
if take_pwstr(requested) != url {351
return Ok(());352
}353
let stream = unsafe { SHCreateMemStream(Some(html.as_bytes())) }354
.ok_or_else(|| windows::core::Error::from(windows::core::HRESULT(-1)))?;355
let response =356
unsafe { environment.CreateWebResourceResponse(&stream, 200, w!("OK"), PAGE_HEADERS) }?;357
unsafe { arguments.SetResponse(&response) }358
}));359
let mut token = 0;360
unsafe { webview.add_WebResourceRequested(&handler, &mut token) }361
}362
363
fn forward_messages(webview: &ICoreWebView2, id: u64, page_url: &str) -> windows::core::Result<()> {364
let page_url = page_url.to_owned();365
let handler = WebMessageReceivedEventHandler::create(Box::new(move |_, arguments| {366
let Some(arguments) = arguments else {367
return Ok(());368
};369
let mut source = PWSTR::null();370
unsafe { arguments.Source(&mut source) }?;371
if take_pwstr(source) != page_url {372
return Ok(());373
}374
let mut message = PWSTR::null();375
if unsafe { arguments.TryGetWebMessageAsString(&mut message) }.is_ok() {376
emit(id, DialogEvent::Message(take_pwstr(message)));377
}378
Ok(())379
}));380
let mut token = 0;381
unsafe { webview.add_WebMessageReceived(&handler, &mut token) }382
}383
384
fn forward_new_windows(webview: &ICoreWebView2, id: u64) -> windows::core::Result<()> {385
let handler = NewWindowRequestedEventHandler::create(Box::new(move |_, arguments| {386
let Some(arguments) = arguments else {387
return Ok(());388
};389
let mut target = PWSTR::null();390
unsafe {391
arguments.Uri(&mut target)?;392
arguments.SetHandled(true)?;393
}394
let message = serde_json::json!({"kind": NEW_WINDOW_KIND, "url": take_pwstr(target)});395
emit(id, DialogEvent::Message(message.to_string()));396
Ok(())397
}));398
let mut token = 0;399
unsafe { webview.add_NewWindowRequested(&handler, &mut token) }400
}401
402
fn close_on_escape(403
controller: &ICoreWebView2Controller,404
window: HWND,405
) -> windows::core::Result<()> {406
let handler = AcceleratorKeyPressedEventHandler::create(Box::new(move |_, arguments| {407
let Some(arguments) = arguments else {408
return Ok(());409
};410
let mut kind = COREWEBVIEW2_KEY_EVENT_KIND::default();411
let mut key = 0;412
unsafe {413
arguments.KeyEventKind(&mut kind)?;414
arguments.VirtualKey(&mut key)?;415
}416
if kind == COREWEBVIEW2_KEY_EVENT_KIND_KEY_DOWN && key == VIRTUAL_KEY_ESCAPE {417
unsafe {418
arguments.SetHandled(true)?;419
PostMessageW(Some(window), WM_CLOSE, WPARAM(0), LPARAM(0))?;420
}421
}422
Ok(())423
}));424
let mut token = 0;425
unsafe { controller.add_AcceleratorKeyPressed(&handler, &mut token) }426
}427
428
extern "system" fn dialog_procedure(429
window: HWND,430
message: u32,431
wparam: WPARAM,432
lparam: LPARAM,433
) -> LRESULT {434
let Some(shared) = running_host() else {435
return unsafe { DefWindowProcW(window, message, wparam, lparam) };436
};437
match message {438
WM_SIZE => {439
let id = id_of(&shared, window);440
let controller = id.and_then(|id| {441
shared442
.dialogs443
.borrow()444
.get(&id)445
.and_then(|dialog| dialog.view.as_ref().map(|view| view.controller.clone()))446
});447
if let Some(controller) = controller {448
fit(window, &controller);449
}450
LRESULT(0)451
}452
WM_CLOSE | WM_DESTROY => {453
if let Some(id) = id_of(&shared, window) {454
close(&shared, id);455
}456
if message == WM_CLOSE {457
LRESULT(0)458
} else {459
unsafe { DefWindowProcW(window, message, wparam, lparam) }460
}461
}462
_ => unsafe { DefWindowProcW(window, message, wparam, lparam) },463
}464
}@@ -1,9 +1,12 @@
1
1
#![cfg(windows)]
2
2
3
mod dialog;
3
4
mod fanout;
4
5
mod host;
6
mod host_dialog;
5
7
mod transport;
6
8
9
pub use dialog::{DialogEvent, DialogHandle, DialogSpec};
7
10
pub use host::{HostConfig, start};
8
11
pub use transport::{HostState, WebViewTransport};
9
12
@@ -1,9 +1,12 @@1
#![cfg(windows)]1
#![cfg(windows)]2
2
3
mod dialog;3
mod fanout;4
mod fanout;4
mod host;5
mod host;6
mod host_dialog;5
mod transport;7
mod transport;6
8
9
pub use dialog::{DialogEvent, DialogHandle, DialogSpec};7
pub use host::{HostConfig, start};10
pub use host::{HostConfig, start};8
pub use transport::{HostState, WebViewTransport};11
pub use transport::{HostState, WebViewTransport};9
12
@@ -1,18 +1,44 @@
1
1
use std::collections::HashMap;
2
use std::sync::atomic::{AtomicU64, Ordering};
2
3
use std::sync::{Arc, mpsc};
3
4
use std::time::Duration;
4
5
5
use session::{App, BoxFuture, Diagnosis, Error, OpenedTab, Result, TabChannel, TabCommand, TabEvent, Transport, is_login_url};
6
use tokio::sync::{mpsc::UnboundedSender, watch};
6
use session::{
7
App, BoxFuture, Diagnosis, Error, OpenedTab, Result, TabChannel, TabCommand, TabEvent,
8
Transport, is_login_url,
9
};
10
use tokio::sync::{
11
mpsc::{UnboundedReceiver, UnboundedSender, unbounded_channel},
12
watch,
13
};
14
15
use crate::dialog::{DialogCommand, DialogEvent, DialogHandle, DialogSpec};
7
16
8
17
const ENDPOINT_NAME: &str = "WebView2";
9
18
const READY_WAIT: Duration = Duration::from_secs(30);
10
19
11
20
pub(crate) enum UiRequest {
12
Call { app: App, command: TabCommand },
13
Subscribe { app: App, sink: UnboundedSender<TabEvent> },
14
Wake { app: App },
21
Call {
22
app: App,
23
command: TabCommand,
24
},
25
Subscribe {
26
app: App,
27
sink: UnboundedSender<TabEvent>,
28
},
29
Wake {
30
app: App,
31
},
15
32
Retry,
33
OpenDialog {
34
id: u64,
35
spec: DialogSpec,
36
events: UnboundedSender<DialogEvent>,
37
},
38
Dialog {
39
id: u64,
40
command: DialogCommand,
41
},
16
42
}
17
43
18
44
#[derive(Debug, Clone, Default)]
@@ -27,6 +53,7 @@ pub struct WebViewTransport {
27
53
waker: Arc<dyn Fn() + Send + Sync>,
28
54
state: watch::Receiver<HostState>,
29
55
ready_wait: Duration,
56
next_dialog: AtomicU64,
30
57
}
31
58
32
59
impl WebViewTransport {
@@ -40,9 +67,22 @@ impl WebViewTransport {
40
67
waker,
41
68
state,
42
69
ready_wait: READY_WAIT,
70
next_dialog: AtomicU64::new(1),
43
71
}
44
72
}
45
73
74
pub fn open_dialog(&self, spec: DialogSpec) -> (DialogHandle, UnboundedReceiver<DialogEvent>) {
75
let id = self.next_dialog.fetch_add(1, Ordering::Relaxed);
76
let (events, receiver) = unbounded_channel();
77
let handle = DialogHandle {
78
id,
79
requests: self.requests.clone(),
80
waker: self.waker.clone(),
81
};
82
let _ = self.send(UiRequest::OpenDialog { id, spec, events });
83
(handle, receiver)
84
}
85
46
86
fn send(&self, request: UiRequest) -> Result<()> {
47
87
self.requests
48
88
.send(request)
@@ -144,7 +184,10 @@ mod tests {
144
184
HostState {
145
185
ready: true,
146
186
failure: None,
147
urls: urls.iter().map(|&(app, url)| (app, url.to_owned())).collect(),
187
urls: urls
188
.iter()
189
.map(|&(app, url)| (app, url.to_owned()))
190
.collect(),
148
191
}
149
192
}
150
193
@@ -174,14 +217,25 @@ mod tests {
174
217
#[tokio::test]
175
218
async fn open_before_ready_has_no_tab() {
176
219
let ui = fake_ui();
177
assert!(ui.transport.open(App::Teams, false).await.unwrap().is_none());
220
assert!(
221
ui.transport
222
.open(App::Teams, false)
223
.await
224
.unwrap()
225
.is_none()
226
);
178
227
}
179
228
180
229
#[tokio::test]
181
230
async fn calls_reach_the_ui_thread_and_answers_come_back() {
182
231
let ui = fake_ui();
183
232
ui.state.send_replace(ready(&[]));
184
let (control, events) = ui.transport.open(App::Outlook, false).await.unwrap().unwrap();
233
let (control, events) = ui
234
.transport
235
.open(App::Outlook, false)
236
.await
237
.unwrap()
238
.unwrap();
185
239
assert!(events.is_none());
186
240
let requests = ui.requests;
187
241
let answer = tokio::task::spawn_blocking(move || match requests.recv().unwrap() {
@@ -219,7 +273,10 @@ mod tests {
219
273
async fn diagnose_sees_a_login_page() {
220
274
let ui = fake_ui();
221
275
ui.state.send_replace(ready(&[
222
(App::Teams, "https://login.microsoftonline.com/common/oauth2/v2.0/authorize"),
276
(
277
App::Teams,
278
"https://login.microsoftonline.com/common/oauth2/v2.0/authorize",
279
),
223
280
(App::Outlook, "https://outlook.cloud.microsoft/mail/"),
224
281
]));
225
282
let diagnosis = ui.transport.diagnose().await.unwrap();
@@ -1,18 +1,44 @@1
use std::collections::HashMap;1
use std::collections::HashMap;2
use std::sync::atomic::{AtomicU64, Ordering};2
use std::sync::{Arc, mpsc};3
use std::sync::{Arc, mpsc};3
use std::time::Duration;4
use std::time::Duration;4
5
5
use session::{App, BoxFuture, Diagnosis, Error, OpenedTab, Result, TabChannel, TabCommand, TabEvent, Transport, is_login_url};6
use session::{6
use tokio::sync::{mpsc::UnboundedSender, watch};7
App, BoxFuture, Diagnosis, Error, OpenedTab, Result, TabChannel, TabCommand, TabEvent,8
Transport, is_login_url,9
};10
use tokio::sync::{11
mpsc::{UnboundedReceiver, UnboundedSender, unbounded_channel},12
watch,13
};14
15
use crate::dialog::{DialogCommand, DialogEvent, DialogHandle, DialogSpec};7
16
8
const ENDPOINT_NAME: &str = "WebView2";17
const ENDPOINT_NAME: &str = "WebView2";9
const READY_WAIT: Duration = Duration::from_secs(30);18
const READY_WAIT: Duration = Duration::from_secs(30);10
19
11
pub(crate) enum UiRequest {20
pub(crate) enum UiRequest {12
Call { app: App, command: TabCommand },21
Call {13
Subscribe { app: App, sink: UnboundedSender<TabEvent> },22
app: App,14
Wake { app: App },23
command: TabCommand,24
},25
Subscribe {26
app: App,27
sink: UnboundedSender<TabEvent>,28
},29
Wake {30
app: App,31
},15
Retry,32
Retry,33
OpenDialog {34
id: u64,35
spec: DialogSpec,36
events: UnboundedSender<DialogEvent>,37
},38
Dialog {39
id: u64,40
command: DialogCommand,41
},16
}42
}17
43
18
#[derive(Debug, Clone, Default)]44
#[derive(Debug, Clone, Default)]@@ -27,6 +53,7 @@ pub struct WebViewTransport {27
waker: Arc<dyn Fn() + Send + Sync>,53
waker: Arc<dyn Fn() + Send + Sync>,28
state: watch::Receiver<HostState>,54
state: watch::Receiver<HostState>,29
ready_wait: Duration,55
ready_wait: Duration,56
next_dialog: AtomicU64,30
}57
}31
58
32
impl WebViewTransport {59
impl WebViewTransport {@@ -40,9 +67,22 @@ impl WebViewTransport {40
waker,67
waker,41
state,68
state,42
ready_wait: READY_WAIT,69
ready_wait: READY_WAIT,70
next_dialog: AtomicU64::new(1),43
}71
}44
}72
}45
73
74
pub fn open_dialog(&self, spec: DialogSpec) -> (DialogHandle, UnboundedReceiver<DialogEvent>) {75
let id = self.next_dialog.fetch_add(1, Ordering::Relaxed);76
let (events, receiver) = unbounded_channel();77
let handle = DialogHandle {78
id,79
requests: self.requests.clone(),80
waker: self.waker.clone(),81
};82
let _ = self.send(UiRequest::OpenDialog { id, spec, events });83
(handle, receiver)84
}85
46
fn send(&self, request: UiRequest) -> Result<()> {86
fn send(&self, request: UiRequest) -> Result<()> {47
self.requests87
self.requests48
.send(request)88
.send(request)@@ -144,7 +184,10 @@ mod tests {144
HostState {184
HostState {145
ready: true,185
ready: true,146
failure: None,186
failure: None,147
urls: urls.iter().map(|&(app, url)| (app, url.to_owned())).collect(),187
urls: urls188
.iter()189
.map(|&(app, url)| (app, url.to_owned()))190
.collect(),148
}191
}149
}192
}150
193
@@ -174,14 +217,25 @@ mod tests {174
#[tokio::test]217
#[tokio::test]175
async fn open_before_ready_has_no_tab() {218
async fn open_before_ready_has_no_tab() {176
let ui = fake_ui();219
let ui = fake_ui();177
assert!(ui.transport.open(App::Teams, false).await.unwrap().is_none());220
assert!(221
ui.transport222
.open(App::Teams, false)223
.await224
.unwrap()225
.is_none()226
);178
}227
}179
228
180
#[tokio::test]229
#[tokio::test]181
async fn calls_reach_the_ui_thread_and_answers_come_back() {230
async fn calls_reach_the_ui_thread_and_answers_come_back() {182
let ui = fake_ui();231
let ui = fake_ui();183
ui.state.send_replace(ready(&[]));232
ui.state.send_replace(ready(&[]));184
let (control, events) = ui.transport.open(App::Outlook, false).await.unwrap().unwrap();233
let (control, events) = ui234
.transport235
.open(App::Outlook, false)236
.await237
.unwrap()238
.unwrap();185
assert!(events.is_none());239
assert!(events.is_none());186
let requests = ui.requests;240
let requests = ui.requests;187
let answer = tokio::task::spawn_blocking(move || match requests.recv().unwrap() {241
let answer = tokio::task::spawn_blocking(move || match requests.recv().unwrap() {@@ -219,7 +273,10 @@ mod tests {219
async fn diagnose_sees_a_login_page() {273
async fn diagnose_sees_a_login_page() {220
let ui = fake_ui();274
let ui = fake_ui();221
ui.state.send_replace(ready(&[275
ui.state.send_replace(ready(&[222
(App::Teams, "https://login.microsoftonline.com/common/oauth2/v2.0/authorize"),276
(277
App::Teams,278
"https://login.microsoftonline.com/common/oauth2/v2.0/authorize",279
),223
(App::Outlook, "https://outlook.cloud.microsoft/mail/"),280
(App::Outlook, "https://outlook.cloud.microsoft/mail/"),224
]));281
]));225
let diagnosis = ui.transport.diagnose().await.unwrap();282
let diagnosis = ui.transport.diagnose().await.unwrap();