BlueGit

ict rusty-teams

Files

rusty-teams / crates / app / src / card_actions.rs

card_actions.rs

card_actions.rs 17.2 KiB Download Raw
1use gpui_kit::*;
2use serde_json::Value;
3use teams_core::{
4 AdaptiveCard, CardAction, CardActionKind, CardActionOutcome, ChatApp, TaskDialog,
5 TaskDialogKind, adaptive_cards,
6};
7use tokio::sync::oneshot;
8
9use crate::app_state::{AppEvent, AppState};
10use crate::card_state::{
11 ActionPhase, BotIdentity, CardOverride, CardScope, DONE_HOLD, Surface, TaskDialogState,
12 short_reason,
13};
14use crate::data::{is_one_on_one, others};
15use crate::runtime;
16use crate::task_dialog::{UrlDialog, UrlDialogNext, open_url_dialog};
17
18const NOT_CONNECTED: &str = "Not connected";
19const READ_ONLY: &str = "Read-only mode";
20const CANCELLED: &str = "Cancelled";
21const DIALOG_MESSAGE_HOLD: std::time::Duration = std::time::Duration::from_millis(2200);
22
23pub enum CardTask {
24 Action(CardAction),
25 Submit(Value),
26}
27
28pub type CardAnswer = Result<(CardActionOutcome, Option<(ChatApp, String)>), String>;
29
30impl 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 self.engine.clone(),
319 cx,
320 );
321 if in_dialog {
322 self.close_task_dialog(cx);
323 }
324 }
325 }
326 }
327
328 pub fn close_task_dialog(&mut self, cx: &mut Context<Self>) {
329 if self.task_dialog.take().is_some() {
330 self.cards.clear_card(&CardScope::dialog_key());
331 cx.emit(AppEvent::TaskDialog);
332 cx.notify();
333 }
334 }
335
336 fn close_task_dialog_later(&mut self, cx: &mut Context<Self>) {
337 cx.spawn(async move |this, cx| {
338 cx.background_executor().timer(DIALOG_MESSAGE_HOLD).await;
339 this.update(cx, |state, cx| state.close_task_dialog(cx))
340 .ok();
341 })
342 .detach();
343 }
344
345 pub fn toggle_card_elements(
346 &mut self,
347 scope: &CardScope,
348 root_key: &str,
349 elements: Vec<(String, bool, Option<bool>)>,
350 cx: &mut Context<Self>,
351 ) {
352 for (element_id, initial, forced) in elements {
353 self.cards
354 .toggle_visibility(&format!("{root_key}/{element_id}"), initial, forced);
355 }
356 self.announce_cards(scope, cx);
357 }
358
359 pub fn toggle_show_card(
360 &mut self,
361 scope: &CardScope,
362 actions_key: &str,
363 index: usize,
364 cx: &mut Context<Self>,
365 ) {
366 self.cards.toggle_open_card(actions_key, index);
367 self.announce_cards(scope, cx);
368 }
369
370 pub fn bot_identity(&self, conversation_id: &str, application_id: &str) -> Option<BotIdentity> {
371 let apps = self.bot_apps.get(conversation_id)?;
372 let matched = apps
373 .iter()
374 .find(|app| app.has_bot(application_id) || app.app_id == application_id);
375 let mut with_bots = apps.iter().filter(|app| !app.bot_ids.is_empty());
376 let app = match (matched, with_bots.next(), with_bots.next()) {
377 (Some(app), _, _) | (None, Some(app), None) => app,
378 _ => return None,
379 };
380 Some(BotIdentity {
381 name: app.name.clone(),
382 icon_url: app.small_image_url.clone(),
383 })
384 }
385
386 pub fn request_chat_apps(&mut self, conversation_id: &str, cx: &mut Context<Self>) {
387 if self.bot_apps.contains_key(conversation_id)
388 || self.bot_apps_pending.contains(conversation_id)
389 {
390 return;
391 }
392 let Some(engine) = self.engine.clone() else {
393 return;
394 };
395 self.bot_apps_pending.insert(conversation_id.to_owned());
396 let conversation_id = conversation_id.to_owned();
397 let receiver = {
398 let conversation_id = conversation_id.clone();
399 runtime::spawn(async move { engine.chat_apps(&conversation_id).await })
400 };
401 cx.spawn(async move |this, cx| {
402 let apps = receiver.await.ok().and_then(Result::ok).unwrap_or_default();
403 this.update(cx, |state, cx| {
404 state.bot_apps_pending.remove(&conversation_id);
405 state.bot_apps.insert(conversation_id, apps);
406 state.apply_bot_titles();
407 cx.emit(AppEvent::Sidebar);
408 cx.emit(AppEvent::Directory);
409 cx.notify();
410 })
411 .ok();
412 })
413 .detach();
414 }
415
416 pub fn apply_bot_titles(&mut self) {
417 let me = self.directory.me.clone();
418 for chat in self.sidebar.chats.iter_mut() {
419 let Some(apps) = self.bot_apps.get(&chat.id) else {
420 continue;
421 };
422 if !is_one_on_one(chat) || !others(chat, me.as_ref()).is_empty() {
423 continue;
424 }
425 let mut with_bots = apps.iter().filter(|app| !app.bot_ids.is_empty());
426 if let (Some(app), None) = (with_bots.next(), with_bots.next()) {
427 chat.title = app.name.clone();
428 }
429 }
430 }
431}
432
433#[cfg(test)]
434mod tests {
435 use std::sync::Arc;
436
437 use gpui_kit::{AppContext as _, TestAppContext};
438 use store::Store;
439 use teams_core::{CardActionOutcome, TaskDialog, TaskDialogKind};
440
441 use super::CardAnswer;
442 use crate::app_state::{AppState, Mode};
443 use crate::card_state::CardScope;
444 use crate::task_dialog::UrlDialogNext;
445
446 fn finish(cx: &mut TestAppContext, answer: CardAnswer) -> (UrlDialogNext, Option<String>) {
447 let store = Arc::new(Store::open_in_memory().unwrap());
448 let app = cx.update(|cx| cx.new(|_| AppState::new(store, Mode::default())));
449 let scope = CardScope::message("19:chat@thread.v2", "m1", 0);
450 cx.update(|cx| {
451 app.update(cx, |state, cx| {
452 let next = state.finish_url_dialog_submit(&scope, answer, cx);
453 (next, state.cards.note(&scope.card_key()).map(str::to_owned))
454 })
455 })
456 }
457
458 fn dialog(kind: TaskDialogKind) -> CardActionOutcome {
459 CardActionOutcome::Dialog(TaskDialog {
460 title: None,
461 width: 640,
462 height: 300,
463 kind,
464 })
465 }
466
467 #[gpui_kit::test]
468 fn a_sent_submit_closes_the_url_dialog(cx: &mut TestAppContext) {
469 let (next, note) = finish(cx, Ok((CardActionOutcome::Sent, None)));
470 assert_eq!(next, UrlDialogNext::Close);
471 assert_eq!(note, None);
472 }
473
474 #[gpui_kit::test]
475 fn a_message_answer_is_shown_on_the_card_and_closes_the_dialog(cx: &mut TestAppContext) {
476 let (next, note) = finish(cx, Ok((CardActionOutcome::Message("Saved".into()), None)));
477 assert_eq!(next, UrlDialogNext::Close);
478 assert_eq!(note.as_deref(), Some("Saved"));
479 }
480
481 #[gpui_kit::test]
482 fn a_failed_submit_is_shown_on_the_card(cx: &mut TestAppContext) {
483 let (next, note) = finish(cx, Err("Not connected".into()));
484 assert_eq!(next, UrlDialogNext::Close);
485 assert_eq!(note.as_deref(), Some("Not connected"));
486 }
487
488 #[gpui_kit::test]
489 fn a_continued_url_task_navigates_the_open_dialog(cx: &mut TestAppContext) {
490 let kind = TaskDialogKind::Url {
491 url: "https://bot.example/next".into(),
492 fallback_url: "https://bot.example/next".into(),
493 };
494 let (next, _) = finish(cx, Ok((dialog(kind), None)));
495 assert_eq!(
496 next,
497 UrlDialogNext::Navigate {
498 url: "https://bot.example/next".into(),
499 width: 640,
500 height: 300
501 }
502 );
503 }
504}