BlueGit

ict rusty-teams

Files

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

card_actions.rs

card_actions.rs 17.4 KiB Download Raw
1use gpui_kit::*;
2use serde_json::Value;
3use teams_core::{
4 AdaptiveCard, CardAction, CardActionOutcome, CardInput, ChatApp, TaskDialog, TaskDialogKind,
5 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 inputs: Vec<CardInput>,
37 cx: &mut Context<Self>,
38 ) {
39 if self.cards.is_busy(&action_key) {
40 return;
41 }
42 let Some(task) = self.card_task(&scope, action, &inputs, cx) else {
43 return;
44 };
45 self.cards.set_phase(&action_key, ActionPhase::Busy);
46 self.cards.clear_note(&scope.card_key());
47 self.announce_cards(&scope, cx);
48 let answer = self.card_answer(&scope, task);
49 cx.spawn(async move |this, cx| {
50 let answer = match answer {
51 Some(receiver) => receiver.await.unwrap_or_else(|_| Err(CANCELLED.to_owned())),
52 None => Err(NOT_CONNECTED.to_owned()),
53 };
54 this.update(cx, |state, cx| {
55 state.finish_card_task(scope, action_key, answer, cx)
56 })
57 .ok();
58 })
59 .detach();
60 }
61
62 fn card_answer(
63 &self,
64 scope: &CardScope,
65 task: CardTask,
66 ) -> Option<oneshot::Receiver<CardAnswer>> {
67 if self.mode.demo {
68 return Some(runtime::spawn(crate::demo::card_answer(task)));
69 }
70 if self.mode.read_only {
71 return Some(runtime::spawn(async { Err(READ_ONLY.to_owned()) }));
72 }
73 let engine = self.engine.clone()?;
74 let (conversation_id, message_id) =
75 (scope.conversation_id.clone(), scope.message_id.clone());
76 Some(runtime::spawn(async move {
77 let outcome = match task {
78 CardTask::Action(action) => {
79 engine
80 .card_action(&conversation_id, &message_id, &action)
81 .await
82 }
83 CardTask::Submit(data) => {
84 engine
85 .task_submit(&conversation_id, &message_id, data)
86 .await
87 }
88 }
89 .map_err(|error| short_reason(&error.to_string()))?;
90 let app = engine.card_app(&conversation_id, &message_id).await.ok();
91 Ok((outcome, app))
92 }))
93 }
94
95 fn finish_card_task(
96 &mut self,
97 scope: CardScope,
98 action_key: String,
99 answer: CardAnswer,
100 cx: &mut Context<Self>,
101 ) {
102 let (outcome, app) = match answer {
103 Ok(answer) => answer,
104 Err(reason) => {
105 self.fail_card_action(&scope, &action_key, reason, cx);
106 return;
107 }
108 };
109 let in_dialog = scope.surface == Surface::Dialog;
110 match outcome {
111 CardActionOutcome::Sent => {
112 self.mark_done(&scope, &action_key, cx);
113 if in_dialog {
114 self.close_task_dialog(cx);
115 }
116 }
117 CardActionOutcome::ReplaceCard(json) => {
118 if self.replace_card(&scope, &json, cx) {
119 self.mark_done(&scope, &action_key, cx);
120 } else {
121 self.fail_card_action(&scope, &action_key, "Unreadable card".into(), cx);
122 }
123 }
124 CardActionOutcome::Message(text) => {
125 self.mark_done(&scope, &action_key, cx);
126 self.note_card(&scope, text, cx);
127 if in_dialog {
128 self.close_task_dialog_later(cx);
129 }
130 }
131 CardActionOutcome::Dialog(dialog) => {
132 self.mark_done(&scope, &action_key, cx);
133 self.open_task_dialog(&scope, dialog, app, cx);
134 }
135 CardActionOutcome::Failed(reason) => {
136 self.fail_card_action(&scope, &action_key, reason, cx)
137 }
138 }
139 }
140
141 #[cfg_attr(not(windows), allow(dead_code))]
142 pub fn submit_url_dialog(
143 &mut self,
144 scope: CardScope,
145 result: Value,
146 cx: &mut Context<Self>,
147 ) -> Task<UrlDialogNext> {
148 let answer = self.card_answer(&scope, CardTask::Submit(result));
149 cx.spawn(async move |this, cx| {
150 let answer = match answer {
151 Some(receiver) => receiver.await.unwrap_or_else(|_| Err(CANCELLED.to_owned())),
152 None => Err(NOT_CONNECTED.to_owned()),
153 };
154 this.update(cx, |state, cx| {
155 state.finish_url_dialog_submit(&scope, answer, cx)
156 })
157 .unwrap_or(UrlDialogNext::Close)
158 })
159 }
160
161 #[cfg_attr(not(windows), allow(dead_code))]
162 fn finish_url_dialog_submit(
163 &mut self,
164 scope: &CardScope,
165 answer: CardAnswer,
166 cx: &mut Context<Self>,
167 ) -> UrlDialogNext {
168 let (outcome, app) = match answer {
169 Ok(answer) => answer,
170 Err(reason) => (CardActionOutcome::Failed(reason), None),
171 };
172 match outcome {
173 CardActionOutcome::Sent => {}
174 CardActionOutcome::ReplaceCard(json) => {
175 self.replace_card(scope, &json, cx);
176 }
177 CardActionOutcome::Message(text) => self.note_card(scope, text, cx),
178 CardActionOutcome::Failed(reason) => self.note_card(scope, short_reason(&reason), cx),
179 CardActionOutcome::Dialog(dialog) => {
180 if let TaskDialogKind::Url { url, .. } = &dialog.kind {
181 return UrlDialogNext::Navigate {
182 url: url.clone(),
183 width: dialog.width,
184 height: dialog.height,
185 };
186 }
187 self.open_task_dialog(scope, dialog, app, cx);
188 }
189 }
190 UrlDialogNext::Close
191 }
192
193 fn note_card(&mut self, scope: &CardScope, text: String, cx: &mut Context<Self>) {
194 self.cards.set_note(&scope.card_key(), text);
195 self.announce_cards(scope, cx);
196 }
197
198 fn fail_card_action(
199 &mut self,
200 scope: &CardScope,
201 action_key: &str,
202 reason: String,
203 cx: &mut Context<Self>,
204 ) {
205 self.cards
206 .set_phase(action_key, ActionPhase::Failed(short_reason(&reason)));
207 self.announce_cards(scope, cx);
208 }
209
210 fn mark_done(&mut self, scope: &CardScope, action_key: &str, cx: &mut Context<Self>) {
211 self.cards.set_phase(action_key, ActionPhase::Done);
212 self.announce_cards(scope, cx);
213 let (scope, action_key) = (scope.clone(), action_key.to_owned());
214 cx.spawn(async move |this, cx| {
215 cx.background_executor().timer(DONE_HOLD).await;
216 this.update(cx, |state, cx| {
217 state.cards.clear_done(&action_key);
218 state.announce_cards(&scope, cx);
219 })
220 .ok();
221 })
222 .detach();
223 }
224
225 pub(crate) fn announce_cards(&mut self, scope: &CardScope, cx: &mut Context<Self>) {
226 cx.emit(AppEvent::Cards(scope.conversation_id.clone()));
227 cx.notify();
228 }
229
230 pub(crate) fn replace_card(
231 &mut self,
232 scope: &CardScope,
233 json: &str,
234 cx: &mut Context<Self>,
235 ) -> bool {
236 let Some(card) = AdaptiveCard::parse(json) else {
237 return false;
238 };
239 self.cards.clear_card(&scope.card_key());
240 if scope.surface == Surface::Dialog {
241 if let Some(dialog) = self.task_dialog.as_mut() {
242 dialog.card = card;
243 }
244 self.announce_cards(scope, cx);
245 return true;
246 }
247 let Some(record) = self
248 .store
249 .messages_by_id(
250 &scope.conversation_id,
251 std::slice::from_ref(&scope.message_id),
252 )
253 .ok()
254 .and_then(|mut records| records.remove(&scope.message_id))
255 else {
256 return false;
257 };
258 let mut cards = adaptive_cards(&record);
259 match cards.get_mut(scope.card_index) {
260 Some(slot) => *slot = card,
261 None => cards.push(card),
262 }
263 self.cards.set_override(
264 &scope.conversation_id,
265 &scope.message_id,
266 CardOverride {
267 basis: record.attachments_json,
268 cards,
269 },
270 );
271 self.announce_cards(scope, cx);
272 true
273 }
274
275 fn open_task_dialog(
276 &mut self,
277 scope: &CardScope,
278 dialog: TaskDialog,
279 app: Option<(ChatApp, String)>,
280 cx: &mut Context<Self>,
281 ) {
282 let app_name = app.as_ref().map(|(app, _)| app.name.clone());
283 let title = dialog.title.clone().or(app_name).unwrap_or_default();
284 let in_dialog = scope.surface == Surface::Dialog;
285 match dialog.kind {
286 TaskDialogKind::Card(json) => {
287 let Some(card) = AdaptiveCard::parse(&json) else {
288 return;
289 };
290 self.cards.clear_card(&CardScope::dialog_key());
291 self.task_dialog = Some(TaskDialogState {
292 title,
293 card,
294 scope: CardScope {
295 card_index: 0,
296 surface: Surface::Dialog,
297 ..scope.clone()
298 },
299 width: dialog.width,
300 height: dialog.height,
301 });
302 cx.emit(AppEvent::TaskDialog);
303 cx.notify();
304 }
305 TaskDialogKind::Url { url, fallback_url } => {
306 let (app_id, bot_id, web_application_resource) = match app {
307 Some((app, bot_id)) => (app.app_id, bot_id, app.web_application_resource),
308 None => (String::new(), String::new(), None),
309 };
310 open_url_dialog(
311 UrlDialog {
312 title,
313 url,
314 fallback_url,
315 width: dialog.width,
316 height: dialog.height,
317 app_id,
318 bot_id,
319 scope: scope.clone(),
320 web_application_resource,
321 },
322 self.engine.clone(),
323 cx,
324 );
325 if in_dialog {
326 self.close_task_dialog(cx);
327 }
328 }
329 }
330 }
331
332 pub fn close_task_dialog(&mut self, cx: &mut Context<Self>) {
333 if self.task_dialog.take().is_some() {
334 self.cards.clear_card(&CardScope::dialog_key());
335 cx.emit(AppEvent::TaskDialog);
336 cx.notify();
337 }
338 }
339
340 fn close_task_dialog_later(&mut self, cx: &mut Context<Self>) {
341 cx.spawn(async move |this, cx| {
342 cx.background_executor().timer(DIALOG_MESSAGE_HOLD).await;
343 this.update(cx, |state, cx| state.close_task_dialog(cx))
344 .ok();
345 })
346 .detach();
347 }
348
349 pub fn toggle_card_elements(
350 &mut self,
351 scope: &CardScope,
352 root_key: &str,
353 elements: Vec<(String, bool, Option<bool>)>,
354 cx: &mut Context<Self>,
355 ) {
356 for (element_id, initial, forced) in elements {
357 self.cards
358 .toggle_visibility(&format!("{root_key}/{element_id}"), initial, forced);
359 }
360 self.announce_cards(scope, cx);
361 }
362
363 pub fn toggle_show_card(
364 &mut self,
365 scope: &CardScope,
366 actions_key: &str,
367 index: usize,
368 cx: &mut Context<Self>,
369 ) {
370 self.cards.toggle_open_card(actions_key, index);
371 self.announce_cards(scope, cx);
372 }
373
374 pub fn set_card_slot(
375 &mut self,
376 scope: &CardScope,
377 slot_key: &str,
378 value: usize,
379 cx: &mut Context<Self>,
380 ) {
381 self.cards.set_slot(slot_key, value);
382 self.announce_cards(scope, cx);
383 }
384
385 pub fn bot_identity(&self, conversation_id: &str, application_id: &str) -> Option<BotIdentity> {
386 let apps = self.bot_apps.get(conversation_id)?;
387 let matched = apps
388 .iter()
389 .find(|app| app.has_bot(application_id) || app.app_id == application_id);
390 let mut with_bots = apps.iter().filter(|app| !app.bot_ids.is_empty());
391 let app = match (matched, with_bots.next(), with_bots.next()) {
392 (Some(app), _, _) | (None, Some(app), None) => app,
393 _ => return None,
394 };
395 Some(BotIdentity {
396 name: app.name.clone(),
397 icon_url: app.small_image_url.clone(),
398 })
399 }
400
401 pub fn request_chat_apps(&mut self, conversation_id: &str, cx: &mut Context<Self>) {
402 if self.bot_apps.contains_key(conversation_id)
403 || self.bot_apps_pending.contains(conversation_id)
404 {
405 return;
406 }
407 let Some(engine) = self.engine.clone() else {
408 return;
409 };
410 self.bot_apps_pending.insert(conversation_id.to_owned());
411 let conversation_id = conversation_id.to_owned();
412 let receiver = {
413 let conversation_id = conversation_id.clone();
414 runtime::spawn(async move { engine.chat_apps(&conversation_id).await })
415 };
416 cx.spawn(async move |this, cx| {
417 let apps = receiver.await.ok().and_then(Result::ok).unwrap_or_default();
418 this.update(cx, |state, cx| {
419 state.bot_apps_pending.remove(&conversation_id);
420 state.bot_apps.insert(conversation_id, apps);
421 state.apply_bot_titles();
422 cx.emit(AppEvent::Sidebar);
423 cx.emit(AppEvent::Directory);
424 cx.notify();
425 })
426 .ok();
427 })
428 .detach();
429 }
430
431 pub fn apply_bot_titles(&mut self) {
432 let me = self.directory.me.clone();
433 for chat in self.sidebar.chats.iter_mut() {
434 let Some(apps) = self.bot_apps.get(&chat.id) else {
435 continue;
436 };
437 if !is_one_on_one(chat) || !others(chat, me.as_ref()).is_empty() {
438 continue;
439 }
440 let mut with_bots = apps.iter().filter(|app| !app.bot_ids.is_empty());
441 if let (Some(app), None) = (with_bots.next(), with_bots.next()) {
442 chat.title = app.name.clone();
443 }
444 }
445 }
446}
447
448#[cfg(test)]
449mod tests {
450 use std::sync::Arc;
451
452 use gpui_kit::{AppContext as _, TestAppContext};
453 use store::Store;
454 use teams_core::{CardActionOutcome, TaskDialog, TaskDialogKind};
455
456 use super::CardAnswer;
457 use crate::app_state::{AppState, Mode};
458 use crate::card_state::CardScope;
459 use crate::task_dialog::UrlDialogNext;
460
461 fn finish(cx: &mut TestAppContext, answer: CardAnswer) -> (UrlDialogNext, Option<String>) {
462 let store = Arc::new(Store::open_in_memory().unwrap());
463 let app = cx.update(|cx| cx.new(|_| AppState::new(store, Mode::default())));
464 let scope = CardScope::message("19:chat@thread.v2", "m1", 0);
465 cx.update(|cx| {
466 app.update(cx, |state, cx| {
467 let next = state.finish_url_dialog_submit(&scope, answer, cx);
468 (next, state.cards.note(&scope.card_key()).map(str::to_owned))
469 })
470 })
471 }
472
473 fn dialog(kind: TaskDialogKind) -> CardActionOutcome {
474 CardActionOutcome::Dialog(TaskDialog {
475 title: None,
476 width: 640,
477 height: 300,
478 kind,
479 })
480 }
481
482 #[gpui_kit::test]
483 fn a_sent_submit_closes_the_url_dialog(cx: &mut TestAppContext) {
484 let (next, note) = finish(cx, Ok((CardActionOutcome::Sent, None)));
485 assert_eq!(next, UrlDialogNext::Close);
486 assert_eq!(note, None);
487 }
488
489 #[gpui_kit::test]
490 fn a_message_answer_is_shown_on_the_card_and_closes_the_dialog(cx: &mut TestAppContext) {
491 let (next, note) = finish(cx, Ok((CardActionOutcome::Message("Saved".into()), None)));
492 assert_eq!(next, UrlDialogNext::Close);
493 assert_eq!(note.as_deref(), Some("Saved"));
494 }
495
496 #[gpui_kit::test]
497 fn a_failed_submit_is_shown_on_the_card(cx: &mut TestAppContext) {
498 let (next, note) = finish(cx, Err("Not connected".into()));
499 assert_eq!(next, UrlDialogNext::Close);
500 assert_eq!(note.as_deref(), Some("Not connected"));
501 }
502
503 #[gpui_kit::test]
504 fn a_continued_url_task_navigates_the_open_dialog(cx: &mut TestAppContext) {
505 let kind = TaskDialogKind::Url {
506 url: "https://bot.example/next".into(),
507 fallback_url: "https://bot.example/next".into(),
508 };
509 let (next, _) = finish(cx, Ok((dialog(kind), None)));
510 assert_eq!(
511 next,
512 UrlDialogNext::Navigate {
513 url: "https://bot.example/next".into(),
514 width: 640,
515 height: 300
516 }
517 );
518 }
519}