BlueGit

ict rusty-teams

Files

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

card_actions.rs

chore: cargo fmt the workspace
metis Daniel Däschle · pushed by metis · 2 weeks ago
a6592765 History
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 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 fn replace_card(&mut self, scope: &CardScope, json: &str, cx: &mut Context<Self>) -> bool {
231 let Some(card) = AdaptiveCard::parse(json) else {
232 return false;
233 };
234 self.cards.clear_card(&scope.card_key());
235 if scope.surface == Surface::Dialog {
236 if let Some(dialog) = self.task_dialog.as_mut() {
237 dialog.card = card;
238 }
239 self.announce_cards(scope, cx);
240 return true;
241 }
242 let Some(record) = self
243 .store
244 .messages_by_id(
245 &scope.conversation_id,
246 std::slice::from_ref(&scope.message_id),
247 )
248 .ok()
249 .and_then(|mut records| records.remove(&scope.message_id))
250 else {
251 return false;
252 };
253 let mut cards = adaptive_cards(&record);
254 match cards.get_mut(scope.card_index) {
255 Some(slot) => *slot = card,
256 None => cards.push(card),
257 }
258 self.cards.set_override(
259 &scope.conversation_id,
260 &scope.message_id,
261 CardOverride {
262 basis: record.attachments_json,
263 cards,
264 },
265 );
266 self.announce_cards(scope, cx);
267 true
268 }
269
270 fn open_task_dialog(
271 &mut self,
272 scope: &CardScope,
273 dialog: TaskDialog,
274 app: Option<(ChatApp, String)>,
275 cx: &mut Context<Self>,
276 ) {
277 let app_name = app.as_ref().map(|(app, _)| app.name.clone());
278 let title = dialog.title.clone().or(app_name).unwrap_or_default();
279 let in_dialog = scope.surface == Surface::Dialog;
280 match dialog.kind {
281 TaskDialogKind::Card(json) => {
282 let Some(card) = AdaptiveCard::parse(&json) else {
283 return;
284 };
285 self.cards.clear_card(&CardScope::dialog_key());
286 self.task_dialog = Some(TaskDialogState {
287 title,
288 card,
289 scope: CardScope {
290 card_index: 0,
291 surface: Surface::Dialog,
292 ..scope.clone()
293 },
294 width: dialog.width,
295 height: dialog.height,
296 });
297 cx.emit(AppEvent::TaskDialog);
298 cx.notify();
299 }
300 TaskDialogKind::Url { url, fallback_url } => {
301 let (app_id, bot_id, web_application_resource) = match app {
302 Some((app, bot_id)) => (app.app_id, bot_id, app.web_application_resource),
303 None => (String::new(), String::new(), None),
304 };
305 open_url_dialog(
306 UrlDialog {
307 title,
308 url,
309 fallback_url,
310 width: dialog.width,
311 height: dialog.height,
312 app_id,
313 bot_id,
314 scope: scope.clone(),
315 web_application_resource,
316 },
317 self.engine.clone(),
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 set_card_slot(
370 &mut self,
371 scope: &CardScope,
372 slot_key: &str,
373 value: usize,
374 cx: &mut Context<Self>,
375 ) {
376 self.cards.set_slot(slot_key, value);
377 self.announce_cards(scope, cx);
378 }
379
380 pub fn bot_identity(&self, conversation_id: &str, application_id: &str) -> Option<BotIdentity> {
381 let apps = self.bot_apps.get(conversation_id)?;
382 let matched = apps
383 .iter()
384 .find(|app| app.has_bot(application_id) || app.app_id == application_id);
385 let mut with_bots = apps.iter().filter(|app| !app.bot_ids.is_empty());
386 let app = match (matched, with_bots.next(), with_bots.next()) {
387 (Some(app), _, _) | (None, Some(app), None) => app,
388 _ => return None,
389 };
390 Some(BotIdentity {
391 name: app.name.clone(),
392 icon_url: app.small_image_url.clone(),
393 })
394 }
395
396 pub fn request_chat_apps(&mut self, conversation_id: &str, cx: &mut Context<Self>) {
397 if self.bot_apps.contains_key(conversation_id)
398 || self.bot_apps_pending.contains(conversation_id)
399 {
400 return;
401 }
402 let Some(engine) = self.engine.clone() else {
403 return;
404 };
405 self.bot_apps_pending.insert(conversation_id.to_owned());
406 let conversation_id = conversation_id.to_owned();
407 let receiver = {
408 let conversation_id = conversation_id.clone();
409 runtime::spawn(async move { engine.chat_apps(&conversation_id).await })
410 };
411 cx.spawn(async move |this, cx| {
412 let apps = receiver.await.ok().and_then(Result::ok).unwrap_or_default();
413 this.update(cx, |state, cx| {
414 state.bot_apps_pending.remove(&conversation_id);
415 state.bot_apps.insert(conversation_id, apps);
416 state.apply_bot_titles();
417 cx.emit(AppEvent::Sidebar);
418 cx.emit(AppEvent::Directory);
419 cx.notify();
420 })
421 .ok();
422 })
423 .detach();
424 }
425
426 pub fn apply_bot_titles(&mut self) {
427 let me = self.directory.me.clone();
428 for chat in self.sidebar.chats.iter_mut() {
429 let Some(apps) = self.bot_apps.get(&chat.id) else {
430 continue;
431 };
432 if !is_one_on_one(chat) || !others(chat, me.as_ref()).is_empty() {
433 continue;
434 }
435 let mut with_bots = apps.iter().filter(|app| !app.bot_ids.is_empty());
436 if let (Some(app), None) = (with_bots.next(), with_bots.next()) {
437 chat.title = app.name.clone();
438 }
439 }
440 }
441}
442
443#[cfg(test)]
444mod tests {
445 use std::sync::Arc;
446
447 use gpui_kit::{AppContext as _, TestAppContext};
448 use store::Store;
449 use teams_core::{CardActionOutcome, TaskDialog, TaskDialogKind};
450
451 use super::CardAnswer;
452 use crate::app_state::{AppState, Mode};
453 use crate::card_state::CardScope;
454 use crate::task_dialog::UrlDialogNext;
455
456 fn finish(cx: &mut TestAppContext, answer: CardAnswer) -> (UrlDialogNext, Option<String>) {
457 let store = Arc::new(Store::open_in_memory().unwrap());
458 let app = cx.update(|cx| cx.new(|_| AppState::new(store, Mode::default())));
459 let scope = CardScope::message("19:chat@thread.v2", "m1", 0);
460 cx.update(|cx| {
461 app.update(cx, |state, cx| {
462 let next = state.finish_url_dialog_submit(&scope, answer, cx);
463 (next, state.cards.note(&scope.card_key()).map(str::to_owned))
464 })
465 })
466 }
467
468 fn dialog(kind: TaskDialogKind) -> CardActionOutcome {
469 CardActionOutcome::Dialog(TaskDialog {
470 title: None,
471 width: 640,
472 height: 300,
473 kind,
474 })
475 }
476
477 #[gpui_kit::test]
478 fn a_sent_submit_closes_the_url_dialog(cx: &mut TestAppContext) {
479 let (next, note) = finish(cx, Ok((CardActionOutcome::Sent, None)));
480 assert_eq!(next, UrlDialogNext::Close);
481 assert_eq!(note, None);
482 }
483
484 #[gpui_kit::test]
485 fn a_message_answer_is_shown_on_the_card_and_closes_the_dialog(cx: &mut TestAppContext) {
486 let (next, note) = finish(cx, Ok((CardActionOutcome::Message("Saved".into()), None)));
487 assert_eq!(next, UrlDialogNext::Close);
488 assert_eq!(note.as_deref(), Some("Saved"));
489 }
490
491 #[gpui_kit::test]
492 fn a_failed_submit_is_shown_on_the_card(cx: &mut TestAppContext) {
493 let (next, note) = finish(cx, Err("Not connected".into()));
494 assert_eq!(next, UrlDialogNext::Close);
495 assert_eq!(note.as_deref(), Some("Not connected"));
496 }
497
498 #[gpui_kit::test]
499 fn a_continued_url_task_navigates_the_open_dialog(cx: &mut TestAppContext) {
500 let kind = TaskDialogKind::Url {
501 url: "https://bot.example/next".into(),
502 fallback_url: "https://bot.example/next".into(),
503 };
504 let (next, _) = finish(cx, Ok((dialog(kind), None)));
505 assert_eq!(
506 next,
507 UrlDialogNext::Navigate {
508 url: "https://bot.example/next".into(),
509 width: 640,
510 height: 300
511 }
512 );
513 }
514}