BlueGit

ict rusty-teams

Files

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

demo.rs

demo.rs 82.9 KiB Download Raw
1use std::collections::HashMap;
2use std::path::PathBuf;
3use std::sync::OnceLock;
4use std::time::Instant;
5
6use chrono::{DateTime, Duration, Local, TimeZone, Utc};
7use gpui_kit::{App, Entity};
8use store::{
9 ChannelLayoutRecord, ChannelMentions, ChannelNotificationLevel, ChannelNotifications,
10 ChannelRecord, ChannelTabRecord, ChatRecord, MemberRecord, MessageImportance, MessageRecord,
11 Store, TeamLayoutRecord, TeamRecord,
12};
13use teams_core::{
14 Activity, CallEvent, CallPhase, CallType, CardActionOutcome, ChatApp, Gif, Language,
15 LanguageSettings, LinkPreview, MentionCandidate, NOTES_CHAT_ID, PersonCandidate, PersonSource,
16 PinnedMessage, SavedMessage, TaskDialog, TaskDialogKind, Translation, TranslationBehavior,
17 TranslationStatus,
18};
19
20use crate::activity::{Actor, Entry, Kind};
21use crate::app_state::{AppState, Selection};
22use crate::card_actions::{CardAnswer, CardTask};
23use crate::data::{AvatarState, FolderInfo, FolderKind, Person, PresenceKind};
24use crate::demo_gifs;
25use crate::message_actions::ForwardSource;
26
27static SEARCHABLE_GIFS: OnceLock<Vec<Gif>> = OnceLock::new();
28
29pub const DEMO_USER_ID: &str = "demo-me";
30const DEMO_USER_NAME: &str = "Dana Demo";
31const DEMO_USER_EMAIL: &str = "dana.demo@example.com";
32const DEMO_TIME_ZONE: &str = "W. Europe Standard Time";
33const PHOTO_SIZE: usize = 48;
34const DEMO_PHOTO_SIDE: usize = 240;
35const STAGING_IMAGE_KEY: &str = "demo://staging-dashboard";
36const PENDING_IMAGE_KEY: &str = "demo://pending-screenshot";
37const STAGING_SIZE: (usize, usize) = (960, 540);
38const LINK_IMAGE_KEY: &str =
39 "https://de-prod.asyncgw.teams.microsoft.com/urlp/v1/url/image/Thumbnail?url=demo";
40const LINK_IMAGE_SIZE: (u32, u32) = (320, 180);
41const PRIORITY_CHAT: &str = "demo-chat-priya";
42const BOT_CHAT: &str = "demo-chat-wiki-bot";
43const BOT_NAME: &str = "Wiki Bot";
44const ECHO_CHAT: &str = "demo-chat-echo";
45const ECHO_BOT_ID: &str = "28:demo-echo";
46const BOT_APP_NAME: &str = "Wiki Cloud";
47const BOT_ID: &str = "00000000-0000-0000-0000-00000000b07a";
48const CARD_ANSWER_DELAY: std::time::Duration = std::time::Duration::from_millis(700);
49const CARD_PERSON_URL: &str = "https://avatars.githubusercontent.com/u/9919?s=64";
50const CARD_PAGE_URL: &str = "https://avatars.githubusercontent.com/u/9919?s=64";
51const NEW_CHAT_PREFIX: &str = "demo-chat-new-";
52const PEOPLE_DIRECTORY: [(&str, &str, &str, &str); 5] = [
53 (
54 MARA_ID,
55 "Mara Lindqvist",
56 "Product Owner",
57 "mara.lindqvist@example.com",
58 ),
59 (
60 JONAS_ID,
61 "Jonas Ortega",
62 "Backend Engineer",
63 "jonas.ortega@example.com",
64 ),
65 (
66 PRIYA_ID,
67 "Priya Nair",
68 "Engineering Manager",
69 "priya.nair@example.com",
70 ),
71 (
72 LEA_ID,
73 "Lea Schneider",
74 "Customer Success",
75 "lea.schneider@example.com",
76 ),
77 (
78 TOBIAS_ID,
79 "Tobias Klein",
80 "Support Engineer",
81 "tobias.klein@example.com",
82 ),
83];
84
85struct Palette {
86 background: [u8; 3],
87 skin: [u8; 3],
88 hair: [u8; 3],
89 shirt: [u8; 3],
90}
91
92const MARA: Palette = Palette {
93 background: [0x3f, 0x5f, 0x7a],
94 skin: [0xe0, 0xb2, 0x93],
95 hair: [0xd9, 0xa4, 0x41],
96 shirt: [0x1e, 0x29, 0x3b],
97};
98const PRIYA: Palette = Palette {
99 background: [0x4b, 0x3b, 0x5c],
100 skin: [0x9a, 0x6a, 0x4a],
101 hair: [0x1c, 0x19, 0x17],
102 shirt: [0xbe, 0x12, 0x3c],
103};
104const TOBIAS: Palette = Palette {
105 background: [0x3b, 0x4a, 0x3f],
106 skin: [0xf1, 0xc7, 0xa5],
107 hair: [0x57, 0x53, 0x4e],
108 shirt: [0x0f, 0x76, 0x6e],
109};
110
111pub const MARA_ID: &str = "demo-mara";
112pub const JONAS_ID: &str = "demo-jonas";
113pub const PRIYA_ID: &str = "demo-priya";
114pub const LEA_ID: &str = "demo-lea";
115pub const TOBIAS_ID: &str = "demo-tobias";
116
117const DEMO_TEAMS: [(&str, &str, [&str; 3]); 4] = [
118 (
119 "demo-team-1",
120 "Platform",
121 ["General", "Incidents", "Releases"],
122 ),
123 ("demo-team-2", "Product", ["General", "Roadmap", "Feedback"]),
124 (
125 "demo-team-3",
126 "Operations",
127 ["General", "On call", "Runbooks"],
128 ),
129 (
130 "demo-team-4",
131 "Archive 2025",
132 ["General", "Trade fair", "Office move"],
133 ),
134];
135const DEMO_TEAM_ORDER: [&str; 4] = ["demo-team-2", "demo-team-1", "demo-team-3", "demo-team-4"];
136const DEMO_HIDDEN_TEAM: &str = "demo-team-4";
137const DEMO_HIDDEN_CHANNEL: &str = "demo-channel-3-3";
138const DEMO_CHANNEL_MENTIONS: [(&str, ChannelMentions); 4] = [
139 ("demo-channel-1-2", mentions(2, 0, 0)),
140 ("demo-channel-2-1", mentions(0, 1, 0)),
141 (DEMO_HIDDEN_CHANNEL, mentions(1, 0, 0)),
142 ("demo-channel-4-2", mentions(1, 0, 1)),
143];
144const PINNED_CHANNEL: &str = "demo-channel-1-1";
145const PINNED_POST: &str = "t3";
146
147const fn mentions(personal: u32, channel: u32, team: u32) -> ChannelMentions {
148 ChannelMentions {
149 personal,
150 channel,
151 team,
152 }
153}
154const DEMO_CHANNEL_NOTIFICATIONS: [(&str, ChannelNotificationLevel, bool); 4] = [
155 (
156 "demo-channel-1-1",
157 ChannelNotificationLevel::BannerAndFeed,
158 false,
159 ),
160 (
161 "demo-channel-1-2",
162 ChannelNotificationLevel::BannerAndFeed,
163 true,
164 ),
165 ("demo-channel-1-3", ChannelNotificationLevel::Off, false),
166 ("demo-channel-2-2", ChannelNotificationLevel::Off, false),
167];
168
169const UNREAD_CHAT: &str = "demo-chat-atlas";
170const RELEASE_CHAT: &str = "demo-chat-release";
171const PINNED_MESSAGE: &str = "m5b";
172const FRENCH_MESSAGE: &str = "m10";
173const SPANISH_MESSAGE: &str = "m11";
174const SAVED_MESSAGES: [&str; 2] = ["m4", "m5c"];
175const FORWARD_ITEMTYPE: &str = "http://schema.skype.com/Forward";
176const FAVORITES_ID: &str = "demo-folder-favorites";
177const CUSTOMERS_FOLDER: &str = "demo-folder-customers";
178const ATLAS_FOLDER: &str = "demo-folder-atlas";
179const TODO_FOLDER: &str = "demo-folder-todo";
180const MUTED_CHATS: [&str; 6] = [
181 "demo-chat-muted-lunch",
182 "demo-chat-muted-offsite",
183 "demo-chat-muted-kudos",
184 "demo-chat-muted-bikes",
185 "demo-chat-muted-book",
186 "demo-chat-muted-games",
187];
188
189fn member(user_id: &str, name: &str) -> MemberRecord {
190 MemberRecord {
191 user_id: Some(user_id.to_owned()),
192 display_name: name.to_owned(),
193 }
194}
195
196fn people(extra: &[(&str, &str)]) -> Vec<MemberRecord> {
197 std::iter::once(member(DEMO_USER_ID, DEMO_USER_NAME))
198 .chain(extra.iter().map(|(id, name)| member(id, name)))
199 .collect()
200}
201
202pub fn at(days_ago: i64, hour: u32, minute: u32) -> DateTime<Utc> {
203 let day = Local::now().date_naive() - Duration::days(days_ago);
204 let local = day.and_hms_opt(hour, minute, 0).expect("valid time");
205 Local
206 .from_local_datetime(&local)
207 .earliest()
208 .map_or_else(Utc::now, |time| time.with_timezone(&Utc))
209}
210
211struct DemoChat {
212 id: &'static str,
213 kind: &'static str,
214 title: &'static str,
215 members: Vec<MemberRecord>,
216 time: DateTime<Utc>,
217 unread: bool,
218 preview: Option<(&'static str, &'static str, &'static str)>,
219 deleted: bool,
220}
221
222fn demo_chats() -> Vec<DemoChat> {
223 let group = |extra: &[(&str, &str)]| people(extra);
224 vec![
225 DemoChat {
226 id: BOT_CHAT,
227 kind: "oneOnOne",
228 title: BOT_NAME,
229 members: people(&[]),
230 time: at(0, 13, 45),
231 unread: true,
232 preview: Some(("", BOT_NAME, "Mara Lindqvist edited your page")),
233 deleted: false,
234 },
235 DemoChat {
236 id: "demo-chat-mara",
237 kind: "oneOnOne",
238 title: "Mara Lindqvist",
239 members: people(&[(MARA_ID, "Mara Lindqvist")]),
240 time: at(0, 13, 40),
241 unread: false,
242 preview: Some((MARA_ID, "Mara Lindqvist", "Sure, 2 pm works")),
243 deleted: false,
244 },
245 DemoChat {
246 id: RELEASE_CHAT,
247 kind: "group",
248 title: "Release planning",
249 members: group(&[
250 (MARA_ID, "Mara Lindqvist"),
251 (JONAS_ID, "Jonas Ortega"),
252 (PRIYA_ID, "Priya Nair"),
253 (LEA_ID, "Lea Schneider"),
254 ]),
255 time: at(0, 13, 35),
256 unread: false,
257 preview: Some((
258 DEMO_USER_ID,
259 DEMO_USER_NAME,
260 "Build 42 is green, see pipeline",
261 )),
262 deleted: false,
263 },
264 DemoChat {
265 id: "demo-chat-customer-1",
266 kind: "group",
267 title: "Customer North - Operations",
268 members: group(&[(LEA_ID, "Lea Schneider"), (TOBIAS_ID, "Tobias Klein")]),
269 time: at(0, 12, 50),
270 unread: true,
271 preview: Some((LEA_ID, "Lea Schneider", "Access is enabled now")),
272 deleted: false,
273 },
274 DemoChat {
275 id: "demo-chat-customer-2",
276 kind: "group",
277 title: "Customer South - Rollout",
278 members: group(&[(JONAS_ID, "Jonas Ortega"), (PRIYA_ID, "Priya Nair")]),
279 time: at(0, 9, 5),
280 unread: true,
281 preview: Some((JONAS_ID, "Jonas Ortega", "Meeting is set for Friday")),
282 deleted: false,
283 },
284 DemoChat {
285 id: "demo-chat-customer-3",
286 kind: "group",
287 title: "Customer West - Support",
288 members: group(&[(TOBIAS_ID, "Tobias Klein"), (LEA_ID, "Lea Schneider")]),
289 time: at(1, 16, 0),
290 unread: false,
291 preview: Some((TOBIAS_ID, "Tobias Klein", "Ticket is closed")),
292 deleted: false,
293 },
294 DemoChat {
295 id: "demo-chat-customer-4",
296 kind: "group",
297 title: "Customer East - Pilot",
298 members: group(&[(MARA_ID, "Mara Lindqvist"), (PRIYA_ID, "Priya Nair")]),
299 time: at(3, 10, 0),
300 unread: false,
301 preview: Some((DEMO_USER_ID, DEMO_USER_NAME, "I'll send the documents")),
302 deleted: false,
303 },
304 DemoChat {
305 id: "demo-chat-atlas",
306 kind: "group",
307 title: "Atlas core team",
308 members: group(&[
309 (PRIYA_ID, "Priya Nair"),
310 (LEA_ID, "Lea Schneider"),
311 (MARA_ID, "Mara Lindqvist"),
312 ]),
313 time: at(0, 13, 12),
314 unread: true,
315 preview: Some((PRIYA_ID, "Priya Nair", "Who is taking the review?")),
316 deleted: false,
317 },
318 DemoChat {
319 id: ECHO_CHAT,
320 kind: "oneOnOne",
321 title: "Echo",
322 members: people(&[(ECHO_BOT_ID, "Echo")]),
323 time: at(0, 11, 20),
324 unread: false,
325 preview: Some(("", "", "Recording is ready")),
326 deleted: false,
327 },
328 DemoChat {
329 id: NOTES_CHAT_ID,
330 kind: "oneOnOne",
331 title: "Dana Demo (You)",
332 members: people(&[]),
333 time: at(0, 8, 20),
334 unread: false,
335 preview: Some((DEMO_USER_ID, DEMO_USER_NAME, "Release notes draft")),
336 deleted: false,
337 },
338 DemoChat {
339 id: "demo-chat-jonas",
340 kind: "oneOnOne",
341 title: "Jonas Ortega",
342 members: people(&[(JONAS_ID, "Jonas Ortega")]),
343 time: at(0, 11, 2),
344 unread: false,
345 preview: Some((DEMO_USER_ID, DEMO_USER_NAME, "Thanks, it's merged")),
346 deleted: false,
347 },
348 DemoChat {
349 id: "demo-chat-priya",
350 kind: "oneOnOne",
351 title: "Priya Nair",
352 members: people(&[(PRIYA_ID, "Priya Nair")]),
353 time: at(0, 10, 47),
354 unread: false,
355 preview: Some((PRIYA_ID, "Priya Nair", "Sent an image")),
356 deleted: false,
357 },
358 DemoChat {
359 id: "demo-chat-tobias",
360 kind: "oneOnOne",
361 title: "Tobias Klein",
362 members: people(&[(TOBIAS_ID, "Tobias Klein")]),
363 time: at(2, 9, 30),
364 unread: false,
365 preview: Some((DEMO_USER_ID, DEMO_USER_NAME, "Forwarded a message")),
366 deleted: false,
367 },
368 DemoChat {
369 id: "demo-chat-allhands",
370 kind: "group",
371 title: "All-hands announcements",
372 members: group(&[(LEA_ID, "Lea Schneider"), (MARA_ID, "Mara Lindqvist")]),
373 time: at(0, 9, 0),
374 unread: true,
375 preview: Some((LEA_ID, "Lea Schneider", "New vacation policy from November")),
376 deleted: false,
377 },
378 DemoChat {
379 id: "demo-chat-design",
380 kind: "group",
381 title: "Design review",
382 members: group(&[(MARA_ID, "Mara Lindqvist"), (TOBIAS_ID, "Tobias Klein")]),
383 time: at(2, 15, 0),
384 unread: false,
385 preview: Some((MARA_ID, "Mara Lindqvist", "alt")),
386 deleted: true,
387 },
388 DemoChat {
389 id: "demo-chat-quarterly",
390 kind: "group",
391 title: "Quarterly numbers, finance review and planning 2027",
392 members: group(&[(LEA_ID, "Lea Schneider"), (JONAS_ID, "Jonas Ortega")]),
393 time: at(4, 11, 0),
394 unread: false,
395 preview: Some((LEA_ID, "Lea Schneider", "Draft attached")),
396 deleted: false,
397 },
398 DemoChat {
399 id: "demo-chat-meeting-standup",
400 kind: "meeting",
401 title: "Daily standup",
402 members: group(&[(JONAS_ID, "Jonas Ortega"), (PRIYA_ID, "Priya Nair")]),
403 time: at(0, 9, 45),
404 unread: true,
405 preview: Some(("", "", "Recording is ready")),
406 deleted: false,
407 },
408 DemoChat {
409 id: "demo-chat-meeting-retro",
410 kind: "meeting",
411 title: "Sprint retrospective",
412 members: group(&[(MARA_ID, "Mara Lindqvist"), (TOBIAS_ID, "Tobias Klein")]),
413 time: at(3, 15, 30),
414 unread: false,
415 preview: Some((MARA_ID, "Mara Lindqvist", "Notes are in the wiki")),
416 deleted: false,
417 },
418 DemoChat {
419 id: "demo-chat-muted-lunch",
420 kind: "group",
421 title: "Lunch crew",
422 members: group(&[(JONAS_ID, "Jonas Ortega"), (LEA_ID, "Lea Schneider")]),
423 time: at(0, 12, 5),
424 unread: true,
425 preview: Some((JONAS_ID, "Jonas Ortega", "\u{1F4F7} GIF")),
426 deleted: false,
427 },
428 DemoChat {
429 id: "demo-chat-muted-offsite",
430 kind: "group",
431 title: "Team offsite 2027",
432 members: group(&[(LEA_ID, "Lea Schneider"), (LEA_ID, "Lea Schneider")]),
433 time: at(1, 16, 20),
434 unread: false,
435 preview: Some((LEA_ID, "Lea Schneider", "Voting closes tomorrow")),
436 deleted: false,
437 },
438 DemoChat {
439 id: "demo-chat-muted-kudos",
440 kind: "group",
441 title: "Kudos corner",
442 members: group(&[(MARA_ID, "Mara Lindqvist"), (LEA_ID, "Lea Schneider")]),
443 time: at(2, 10, 0),
444 unread: false,
445 preview: Some((MARA_ID, "Mara Lindqvist", "Thanks for the release!")),
446 deleted: false,
447 },
448 DemoChat {
449 id: "demo-chat-muted-bikes",
450 kind: "group",
451 title: "Bike to work",
452 members: group(&[(TOBIAS_ID, "Tobias Klein"), (LEA_ID, "Lea Schneider")]),
453 time: at(4, 8, 15),
454 unread: false,
455 preview: Some((TOBIAS_ID, "Tobias Klein", "Sent a file")),
456 deleted: false,
457 },
458 DemoChat {
459 id: "demo-chat-muted-book",
460 kind: "group",
461 title: "Book club",
462 members: group(&[(PRIYA_ID, "Priya Nair"), (LEA_ID, "Lea Schneider")]),
463 time: at(6, 19, 40),
464 unread: false,
465 preview: Some((PRIYA_ID, "Priya Nair", "Sent a card")),
466 deleted: false,
467 },
468 DemoChat {
469 id: "demo-chat-muted-games",
470 kind: "group",
471 title: "Board game night",
472 members: group(&[(JONAS_ID, "Jonas Ortega"), (LEA_ID, "Lea Schneider")]),
473 time: at(9, 18, 0),
474 unread: false,
475 preview: Some((JONAS_ID, "Jonas Ortega", "Who brings the snacks?")),
476 deleted: false,
477 },
478 ]
479}
480
481pub fn mention_candidates(conversation_id: &str, query: &str) -> Vec<MentionCandidate> {
482 let needle = query.trim().to_lowercase();
483 let matches = |name: &str| needle.is_empty() || name.to_lowercase().contains(&needle);
484 let people = PEOPLE_DIRECTORY
485 .iter()
486 .filter(|(_, name, _, _)| matches(name))
487 .map(|(user_id, name, job_title, mail)| {
488 MentionCandidate::Person(PersonCandidate {
489 user_id: (*user_id).to_owned(),
490 display_name: (*name).to_owned(),
491 mail: Some((*mail).to_owned()),
492 job_title: Some((*job_title).to_owned()),
493 source: PersonSource::Member,
494 })
495 });
496 let scope: Vec<MentionCandidate> = if conversation_id.starts_with("demo-channel") {
497 [
498 MentionCandidate::Channel {
499 channel_id: conversation_id.to_owned(),
500 name: "General".to_owned(),
501 },
502 MentionCandidate::Team {
503 team_id: "demo-team-1".to_owned(),
504 name: "Platform".to_owned(),
505 },
506 ]
507 .into_iter()
508 .filter(|candidate| matches(candidate.display_name()))
509 .collect()
510 } else {
511 Vec::new()
512 };
513 people.chain(scope).collect()
514}
515
516pub fn send_in_chat(
517 chat: &ChatRecord,
518 preview: &str,
519 html: &str,
520 now: DateTime<Utc>,
521) -> (ChatRecord, MessageRecord) {
522 let mut chat = chat.clone();
523 chat.last_message_at = Some(now);
524 chat.last_message_preview = Some(preview.to_owned());
525 chat.last_message_sender_id = Some(DEMO_USER_ID.to_owned());
526 chat.last_message_sender_name = Some(DEMO_USER_NAME.to_owned());
527 chat.last_message_deleted = false;
528 chat.unread = false;
529 let record = message(
530 &chat.id,
531 &format!("demo-sent-{}", now.timestamp_millis()),
532 None,
533 (DEMO_USER_ID, DEMO_USER_NAME),
534 now,
535 html,
536 "[]",
537 false,
538 );
539 (chat, record)
540}
541
542pub fn new_chat(
543 existing: &[ChatRecord],
544 people: &[(String, String)],
545 topic: Option<&str>,
546 preview: &str,
547 html: &str,
548 now: DateTime<Utc>,
549) -> (ChatRecord, MessageRecord) {
550 let number = existing
551 .iter()
552 .filter(|chat| chat.id.starts_with(NEW_CHAT_PREFIX))
553 .count()
554 + 1;
555 let one_on_one = people.len() == 1;
556 let members = std::iter::once(member(DEMO_USER_ID, DEMO_USER_NAME))
557 .chain(people.iter().map(|(user_id, name)| member(user_id, name)))
558 .collect();
559 let chat = ChatRecord {
560 id: format!("{NEW_CHAT_PREFIX}{number}"),
561 kind: if one_on_one { "oneOnOne" } else { "group" }.to_owned(),
562 title: if one_on_one {
563 String::new()
564 } else {
565 topic.unwrap_or_default().to_owned()
566 },
567 member_summary: people
568 .iter()
569 .map(|(_, name)| name.as_str())
570 .collect::<Vec<_>>()
571 .join(", "),
572 members,
573 ..Default::default()
574 };
575 send_in_chat(&chat, preview, html, now)
576}
577
578fn image_directory() -> PathBuf {
579 std::env::temp_dir().join("rusty-teams-demo")
580}
581
582pub fn search_gifs(query: &str) -> Vec<Gif> {
583 let query = query.trim().to_lowercase();
584 SEARCHABLE_GIFS
585 .get()
586 .into_iter()
587 .flatten()
588 .filter(|gif| gif.title.to_lowercase().contains(&query))
589 .cloned()
590 .collect()
591}
592
593pub fn language_settings() -> LanguageSettings {
594 LanguageSettings {
595 display_locale: Some("en-US".to_owned()),
596 target_locale: Some("en".to_owned()),
597 behavior: TranslationBehavior::Ask,
598 authoring_locales: vec!["de-DE".to_owned(), "en-US".to_owned()],
599 preferences: serde_json::Map::new(),
600 }
601}
602
603pub fn language_list() -> Vec<Language> {
604 [
605 ("de", "German"),
606 ("en", "English"),
607 ("es", "Spanish"),
608 ("fr", "French"),
609 ("it", "Italian"),
610 ("ja", "Japanese"),
611 ("nl", "Dutch"),
612 ("pt", "Portuguese"),
613 ]
614 .into_iter()
615 .map(|(code, name)| Language {
616 code: code.to_owned(),
617 name: name.to_owned(),
618 })
619 .collect()
620}
621
622pub fn language_stamps(conversation_id: &str) -> HashMap<String, String> {
623 if conversation_id != RELEASE_CHAT {
624 return HashMap::new();
625 }
626 HashMap::from([
627 (
628 FRENCH_MESSAGE.to_owned(),
629 "languages=fr:100;en:12;length:104;&detector=Bling".to_owned(),
630 ),
631 (
632 SPANISH_MESSAGE.to_owned(),
633 "languages=es:100;pt:31;length:94;&detector=Bling".to_owned(),
634 ),
635 ])
636}
637
638pub fn translations(message_ids: &[String]) -> Vec<Translation> {
639 let translated = |message_id: &str| match message_id {
640 FRENCH_MESSAGE => Some(
641 "<p>Hello everyone, <strong>version 0.2</strong> is ready. Can you check the checklist before Friday?</p>",
642 ),
643 SPANISH_MESSAGE => Some(
644 "<p>Thanks for the heads-up. I will test the build this afternoon and let you know if anything breaks.</p>",
645 ),
646 _ => None,
647 };
648 message_ids
649 .iter()
650 .map(|message_id| Translation {
651 message_id: message_id.clone(),
652 version: None,
653 status: if translated(message_id).is_some() {
654 TranslationStatus::Done
655 } else {
656 TranslationStatus::Failed
657 },
658 content_html: translated(message_id).map(str::to_owned),
659 subject: None,
660 title: None,
661 })
662 .collect()
663}
664
665pub fn first_unread(conversation_id: &str) -> Option<String> {
666 (conversation_id == UNREAD_CHAT).then(|| "u3".to_owned())
667}
668
669pub fn read_message_ids(records: &[MessageRecord]) -> std::collections::HashSet<String> {
670 let newest = records.iter().max_by_key(|record| record.created_at);
671 records
672 .iter()
673 .filter(|record| {
674 Some(record.message_id.as_str()) != newest.map(|newest| newest.message_id.as_str())
675 })
676 .map(|record| record.message_id.clone())
677 .collect()
678}
679
680pub fn start_session(state: &Entity<AppState>, cx: &mut App) {
681 state.update(cx, |state, cx| {
682 seed_directory(state);
683 state.demo_live_meetings();
684 state.select(first_selection(), cx);
685 });
686}
687
688pub fn first_selection() -> Selection {
689 Selection::Chat(RELEASE_CHAT.to_owned())
690}
691
692pub fn activity_entries() -> Vec<Entry> {
693 let actor = |user_id: &str, name: &str| Actor {
694 user_id: Some(user_id.to_owned()),
695 name: name.to_owned(),
696 };
697 let entry = |conversation_id: &str,
698 kind: Kind,
699 message_id: &str,
700 actors: Vec<Actor>,
701 preview: &str,
702 count: u32,
703 updated_at: DateTime<Utc>,
704 read: bool| Entry {
705 id: 0,
706 conversation_id: conversation_id.to_owned(),
707 kind,
708 message_id: message_id.to_owned(),
709 actors,
710 preview: preview.to_owned(),
711 glyphs: Vec::new(),
712 count,
713 updated_at,
714 read,
715 };
716 let reaction = Entry {
717 glyphs: vec!["\u{1F602}".to_owned(), "\u{1F44D}".to_owned()],
718 ..entry(
719 RELEASE_CHAT,
720 Kind::Reaction,
721 "m3",
722 vec![
723 actor(PRIYA_ID, "Priya Nair"),
724 actor(LEA_ID, "Lea Schneider"),
725 ],
726 "I'll take the changelog.",
727 2,
728 at(0, 13, 20),
729 false,
730 )
731 };
732 vec![
733 entry(
734 UNREAD_CHAT,
735 Kind::Messages,
736 "u3",
737 vec![
738 actor(LEA_ID, "Lea Schneider"),
739 actor(PRIYA_ID, "Priya Nair"),
740 ],
741 "Who is taking the review?",
742 3,
743 at(0, 13, 12),
744 false,
745 ),
746 entry(
747 "demo-channel-1-1",
748 Kind::Mention,
749 "t1",
750 vec![actor(MARA_ID, "Mara Lindqvist")],
751 "@Dana can you approve the merge? The pipeline is waiting.",
752 1,
753 at(0, 11, 40),
754 false,
755 ),
756 reaction,
757 entry(
758 "demo-chat-allhands",
759 Kind::Mention,
760 "demo-allhands-policy",
761 vec![actor(LEA_ID, "Lea Schneider")],
762 "@Dana please read the new vacation policy before Friday.",
763 1,
764 at(0, 9, 0),
765 false,
766 ),
767 entry(
768 "demo-chat-customer-3",
769 Kind::Messages,
770 "demo-customer-3-closed",
771 vec![actor(TOBIAS_ID, "Tobias Klein")],
772 "Ticket is closed",
773 1,
774 at(1, 16, 0),
775 true,
776 ),
777 ]
778}
779
780pub fn seed(store: &Store) {
781 let chats: Vec<ChatRecord> = demo_chats()
782 .into_iter()
783 .map(|demo| ChatRecord {
784 id: demo.id.to_owned(),
785 kind: demo.kind.to_owned(),
786 title: if demo.kind == "oneOnOne" {
787 String::new()
788 } else {
789 demo.title.to_owned()
790 },
791 member_summary: demo.title.to_owned(),
792 last_message_at: Some(demo.time),
793 unread: demo.unread,
794 members: demo.members,
795 last_message_preview: demo.preview.map(|(_, _, text)| text.to_owned()),
796 last_message_sender_id: demo.preview.map(|(id, _, _)| id.to_owned()),
797 last_message_sender_name: demo.preview.map(|(_, name, _)| name.to_owned()),
798 last_message_deleted: demo.deleted,
799 ..Default::default()
800 })
801 .collect();
802 let _ = store.upsert_chats(&chats);
803 for chat_id in MUTED_CHATS {
804 let _ = store.set_chat_muted(chat_id, true);
805 }
806 let teams: Vec<TeamRecord> = DEMO_TEAMS
807 .iter()
808 .map(|(id, name, _)| TeamRecord {
809 id: (*id).to_owned(),
810 name: (*name).to_owned(),
811 })
812 .collect();
813 let _ = store.upsert_teams(&teams);
814 let mut channels = Vec::new();
815 for (team_index, (team_id, _, names)) in DEMO_TEAMS.iter().enumerate() {
816 for (channel_index, name) in names.iter().enumerate() {
817 channels.push(ChannelRecord {
818 id: format!("demo-channel-{}-{}", team_index + 1, channel_index + 1),
819 team_id: (*team_id).to_owned(),
820 name: (*name).to_owned(),
821 membership_type: None,
822 last_message_at: Some(at(channel_index as i64, 12, 10)),
823 unread: (team_index == 0 && channel_index == 1)
824 || (team_index == 1 && channel_index == 0),
825 });
826 }
827 }
828 for channel in channels.iter_mut().filter(|channel| {
829 DEMO_CHANNEL_MENTIONS
830 .iter()
831 .any(|(id, _)| *id == channel.id)
832 }) {
833 channel.unread = true;
834 }
835 let _ = store.upsert_channels(&channels);
836 let _ = store.replace_team_layout(&demo_team_layout(&channels));
837 let _ = store.replace_channel_mentions(
838 &DEMO_CHANNEL_MENTIONS
839 .iter()
840 .map(|(id, mentions)| ((*id).to_owned(), *mentions))
841 .collect::<Vec<_>>(),
842 );
843 let _ = store.set_meta("me_user_id", DEMO_USER_ID);
844 let _ = store.set_meta("me_display_name", DEMO_USER_NAME);
845 let _ = store.upsert_messages(&release_messages());
846 let _ = store.upsert_messages(&unread_messages());
847 let _ = store.upsert_messages(&channel_messages());
848 let _ = store.upsert_messages(&priority_messages());
849 let _ = store.upsert_messages(&notes_messages());
850 let _ = store.upsert_messages(&meeting_link_messages());
851 let _ = store.upsert_messages(&standup_messages());
852 let _ = store.upsert_messages(&call_messages());
853 let _ = store.upsert_messages(&crate::demo_meetings::meeting_messages());
854 let _ = store.upsert_messages(&bot_messages());
855 seed_agent_access(store);
856}
857
858const AGENT_DEMO_PROPOSAL: &str = "I ran the regression suite on staging: 412 passed, 0 failed. The release candidate is good to ship, @Mara Lindqvist.";
859
860fn seed_agent_access(store: &Store) {
861 let selected =
862 |ids: &[&str]| mcp::Access::Selected(ids.iter().map(|id| (*id).to_owned()).collect());
863 mcp::save_policy(
864 store,
865 &mcp::AgentPolicy {
866 enabled: true,
867 chats: selected(&[RELEASE_CHAT, "demo-chat-mara", "demo-chat-meeting-standup"]),
868 channels: selected(&["demo-channel-1-1"]),
869 propose: true,
870 calendar: true,
871 transcripts: false,
872 ..mcp::AgentPolicy::default()
873 },
874 );
875 let _ = store.insert_agent_proposal(&store::AgentProposalRecord {
876 id: "demo-proposal".to_owned(),
877 conversation_id: RELEASE_CHAT.to_owned(),
878 reply_to_message_id: Some("m1".to_owned()),
879 text: AGENT_DEMO_PROPOSAL.to_owned(),
880 mentions: vec![store::AgentProposalMention {
881 user_id: MARA_ID.to_owned(),
882 name: "Mara Lindqvist".to_owned(),
883 }],
884 images: vec![store::AttachmentImage {
885 name: "image-1.png".to_owned(),
886 format: "image/png".to_owned(),
887 bytes: encode_png(&MARA),
888 width: Some(PHOTO_SIZE as u32),
889 height: Some(PHOTO_SIZE as u32),
890 }],
891 agent: Some("claude".to_owned()),
892 session_id: None,
893 created_at: Utc::now() - Duration::minutes(1),
894 state: "pending".to_owned(),
895 resolved_at: None,
896 });
897 let _ = store.insert_agent_reaction(&store::AgentReactionRecord {
898 id: "demo-reaction".to_owned(),
899 conversation_id: "demo-chat-mara".to_owned(),
900 message_id: "ml1".to_owned(),
901 emoji: "\u{1F44D}".to_owned(),
902 agent: Some("claude".to_owned()),
903 session_id: None,
904 created_at: Utc::now() - Duration::minutes(1),
905 state: "pending".to_owned(),
906 resolved_at: None,
907 });
908}
909
910fn photo(palette: &Palette) -> AvatarState {
911 crate::data::avatar_state_from("image/png", encode_png(palette), false)
912}
913
914pub fn seed_directory(state: &mut AppState) {
915 state.own_status = crate::own_status::demo_status();
916 state.own_email = DEMO_USER_EMAIL.to_owned();
917 state.own_time_zone = Some(DEMO_TIME_ZONE.to_owned());
918 state.translation.settings = Some(language_settings());
919 state.apply_date_locale();
920 state.translation.languages = language_list();
921 let directory = &mut state.directory;
922 directory.me = Some(Person {
923 user_id: DEMO_USER_ID.to_owned(),
924 display_name: DEMO_USER_NAME.to_owned(),
925 });
926 let ids = |list: &[&str]| list.iter().map(|id| (*id).to_owned()).collect::<Vec<_>>();
927 directory.folders = vec![
928 FolderInfo {
929 id: FAVORITES_ID.to_owned(),
930 name: String::new(),
931 kind: FolderKind::Favorites,
932 expanded: None,
933 conversation_ids: ids(&["demo-chat-mara", RELEASE_CHAT]),
934 },
935 FolderInfo {
936 id: CUSTOMERS_FOLDER.to_owned(),
937 name: "Customers".to_owned(),
938 kind: FolderKind::UserCreated,
939 expanded: None,
940 conversation_ids: ids(&[
941 "demo-chat-customer-1",
942 "demo-chat-customer-2",
943 "demo-chat-customer-3",
944 "demo-chat-customer-4",
945 ]),
946 },
947 FolderInfo {
948 id: ATLAS_FOLDER.to_owned(),
949 name: "Project Atlas".to_owned(),
950 kind: FolderKind::UserCreated,
951 expanded: None,
952 conversation_ids: ids(&["demo-chat-atlas", "demo-chat-jonas"]),
953 },
954 FolderInfo {
955 id: TODO_FOLDER.to_owned(),
956 name: "To do".to_owned(),
957 kind: FolderKind::UserCreated,
958 expanded: None,
959 conversation_ids: Vec::new(),
960 },
961 ];
962 state.bot_apps.insert(BOT_CHAT.to_owned(), vec![bot_app()]);
963 let directory = &mut state.directory;
964 directory.pinned_channels = ids(&["demo-channel-1-1", "demo-channel-3-2"]);
965 directory
966 .unread_counts
967 .insert("demo-chat-atlas".to_owned(), 5);
968 directory
969 .unread_counts
970 .insert("demo-chat-customer-1".to_owned(), 2);
971 directory
972 .unread_counts
973 .insert("demo-chat-customer-2".to_owned(), 1);
974 directory
975 .unread_counts
976 .insert("demo-chat-allhands".to_owned(), 120);
977 directory
978 .unread_importance
979 .insert(UNREAD_CHAT.to_owned(), MessageImportance::Urgent);
980 directory
981 .unread_importance
982 .insert("demo-chat-customer-1".to_owned(), MessageImportance::High);
983 directory.set_avatar(MARA_ID, photo(&MARA));
984 directory.set_avatar(PRIYA_ID, photo(&PRIYA));
985 directory.set_avatar(TOBIAS_ID, photo(&TOBIAS));
986 for (user_id, kind) in [
987 (MARA_ID, PresenceKind::Available),
988 (JONAS_ID, PresenceKind::Busy),
989 (PRIYA_ID, PresenceKind::Away),
990 (TOBIAS_ID, PresenceKind::Offline),
991 (LEA_ID, PresenceKind::Busy),
992 (DEMO_USER_ID, PresenceKind::Available),
993 ] {
994 directory.set_presence(user_id, kind);
995 }
996 directory.set_activity(JONAS_ID, Some(Activity::InACall));
997 directory.set_activity(LEA_ID, Some(Activity::InAConferenceCall));
998 let directory_path = image_directory();
999 if std::fs::create_dir_all(&directory_path).is_ok() {
1000 let path = directory_path.join("staging-dashboard.png");
1001 let png = encode_rgb(STAGING_SIZE.0, STAGING_SIZE.1, staging_pixel);
1002 if std::fs::write(&path, png).is_ok() {
1003 state.directory.set_image(STAGING_IMAGE_KEY, &path);
1004 state.directory.set_image(LINK_IMAGE_KEY, &path);
1005 }
1006 let _ = SEARCHABLE_GIFS.set(demo_gifs::generate(&directory_path));
1007 state.directory.set_image(
1008 demo_gifs::RECEIVED_GIF_KEY,
1009 &directory_path.join(demo_gifs::file_name(demo_gifs::RECEIVED_GIF_NAME)),
1010 );
1011 }
1012 state.typing.start(
1013 "demo-chat-mara",
1014 MARA_ID,
1015 "Mara Lindqvist",
1016 Instant::now(),
1017 Utc::now(),
1018 );
1019 state.collapsed.insert(CUSTOMERS_FOLDER.to_owned());
1020 state.last_sync = Some(Utc::now());
1021 state.apply_bot_titles();
1022 seed_message_actions(state);
1023}
1024
1025fn seed_message_actions(state: &mut AppState) {
1026 state.pins.insert(
1027 PINNED_CHANNEL.to_owned(),
1028 vec![PinnedMessage {
1029 message_id: PINNED_POST.to_owned(),
1030 pinned_at: Some(at(0, 9, 45)),
1031 parent_id: None,
1032 }],
1033 );
1034 state.pins.insert(
1035 RELEASE_CHAT.to_owned(),
1036 vec![PinnedMessage {
1037 message_id: PINNED_MESSAGE.to_owned(),
1038 pinned_at: Some(at(0, 11, 30)),
1039 parent_id: None,
1040 }],
1041 );
1042 let ids: Vec<String> = SAVED_MESSAGES.iter().map(|id| (*id).to_owned()).collect();
1043 let records = state
1044 .store
1045 .messages_by_id(RELEASE_CHAT, &ids)
1046 .unwrap_or_default();
1047 let saved = SAVED_MESSAGES
1048 .iter()
1049 .enumerate()
1050 .filter_map(|(position, id)| {
1051 let record = records.get(*id)?;
1052 Some(SavedMessage {
1053 conversation_id: record.conversation_id.clone(),
1054 message_id: record.message_id.clone(),
1055 root_id: record.message_id.clone(),
1056 author_id: record.sender_id.clone(),
1057 author_name: record.sender_name.clone(),
1058 preview: crate::rows::reply_excerpt(record),
1059 saved_at: at(position as i64, 15, 20),
1060 topic: None,
1061 })
1062 })
1063 .collect();
1064 state.saved.replace(saved);
1065}
1066
1067pub fn forwarded_message(
1068 chat: &ChatRecord,
1069 source: &ForwardSource,
1070 comment: &str,
1071 now: DateTime<Utc>,
1072) -> (ChatRecord, MessageRecord) {
1073 let comment_html = if comment.is_empty() {
1074 String::new()
1075 } else {
1076 format!("<p>{}</p>", teams_core::escape_html(comment))
1077 };
1078 let quotes: String = source
1079 .messages
1080 .iter()
1081 .map(|item| {
1082 format!(
1083 "<blockquote itemscope=\"\" itemtype=\"{FORWARD_ITEMTYPE}\" itemid=\"{}\"><strong>{}</strong><p>{}</p></blockquote>",
1084 teams_core::escape_html(&item.message_id),
1085 teams_core::escape_html(&item.author),
1086 teams_core::escape_html(&item.text),
1087 )
1088 })
1089 .collect();
1090 let preview = source
1091 .messages
1092 .first()
1093 .map(|item| item.text.as_str())
1094 .unwrap_or_default();
1095 send_in_chat(chat, preview, &format!("{comment_html}{quotes}"), now)
1096}
1097
1098#[allow(clippy::too_many_arguments)]
1099fn message(
1100 conversation: &str,
1101 id: &str,
1102 reply_to: Option<&str>,
1103 sender: (&str, &str),
1104 time: DateTime<Utc>,
1105 html: &str,
1106 reactions_json: &str,
1107 edited: bool,
1108) -> MessageRecord {
1109 MessageRecord {
1110 conversation_id: conversation.to_owned(),
1111 message_id: id.to_owned(),
1112 reply_to_id: reply_to.map(str::to_owned),
1113 sender_id: Some(sender.0.to_owned()),
1114 sender_name: Some(sender.1.to_owned()),
1115 sender_application_id: None,
1116 links_json: "[]".to_owned(),
1117 created_at: time,
1118 edited_at: edited.then_some(time + Duration::minutes(2)),
1119 deleted: false,
1120 body_html: html.to_owned(),
1121 attachments_json: "[]".to_owned(),
1122 reactions_json: reactions_json.to_owned(),
1123 mentions_json: "[]".to_owned(),
1124 subject: None,
1125 call_event_json: None,
1126 importance: Default::default(),
1127 }
1128}
1129
1130pub fn roster_record(
1131 conversation: &str,
1132 id: &str,
1133 time: DateTime<Utc>,
1134 event: &teams_core::roster_event::RosterEvent,
1135) -> MessageRecord {
1136 MessageRecord {
1137 conversation_id: conversation.to_owned(),
1138 message_id: id.to_owned(),
1139 created_at: time,
1140 links_json: "[]".to_owned(),
1141 attachments_json: "[]".to_owned(),
1142 reactions_json: "[]".to_owned(),
1143 mentions_json: "[]".to_owned(),
1144 call_event_json: Some(event.to_json()),
1145 ..MessageRecord::default()
1146 }
1147}
1148
1149fn call_record(
1150 conversation: &str,
1151 id: &str,
1152 time: DateTime<Utc>,
1153 event: CallEvent,
1154) -> MessageRecord {
1155 MessageRecord {
1156 conversation_id: conversation.to_owned(),
1157 message_id: id.to_owned(),
1158 created_at: time,
1159 links_json: "[]".to_owned(),
1160 attachments_json: "[]".to_owned(),
1161 reactions_json: "[]".to_owned(),
1162 mentions_json: "[]".to_owned(),
1163 call_event_json: Some(event.to_json()),
1164 ..MessageRecord::default()
1165 }
1166}
1167
1168fn call_event(
1169 phase: CallPhase,
1170 call_id: &str,
1171 initiator: (&str, &str),
1172 duration_seconds: Option<u64>,
1173 participant_ids: &[&str],
1174) -> CallEvent {
1175 CallEvent {
1176 phase,
1177 call_type: CallType::Call,
1178 call_id: call_id.to_owned(),
1179 duration_seconds,
1180 initiator_id: Some(initiator.0.to_owned()),
1181 initiator_name: Some(initiator.1.to_owned()),
1182 participant_ids: participant_ids.iter().map(|id| (*id).to_owned()).collect(),
1183 participant_names: Vec::new(),
1184 recording: None,
1185 }
1186}
1187
1188fn call_messages() -> Vec<MessageRecord> {
1189 let mara = (MARA_ID, "Mara Lindqvist");
1190 let me = (DEMO_USER_ID, DEMO_USER_NAME);
1191 let jonas = (JONAS_ID, "Jonas Ortega");
1192 let both = [DEMO_USER_ID, MARA_ID];
1193 vec![
1194 call_record(
1195 "demo-chat-mara",
1196 "call-1-started",
1197 at(0, 12, 4),
1198 call_event(CallPhase::Started, "demo-call-1", me, None, &[]),
1199 ),
1200 call_record(
1201 "demo-chat-mara",
1202 "call-1-ended",
1203 at(0, 12, 16),
1204 call_event(CallPhase::Ended, "demo-call-1", me, Some(723), &both),
1205 ),
1206 call_record(
1207 "demo-chat-mara",
1208 "call-2-started",
1209 at(0, 13, 9),
1210 call_event(CallPhase::Started, "demo-call-2", mara, None, &[]),
1211 ),
1212 call_record(
1213 "demo-chat-mara",
1214 "call-2-ended",
1215 at(0, 13, 10),
1216 call_event(CallPhase::Ended, "demo-call-2", mara, Some(60), &[MARA_ID]),
1217 ),
1218 call_record(
1219 "demo-chat-meeting-standup",
1220 "call-3-started",
1221 at(0, 9, 50),
1222 CallEvent {
1223 call_type: CallType::Meeting,
1224 ..call_event(CallPhase::Started, "demo-call-3", jonas, None, &[])
1225 },
1226 ),
1227 ]
1228}
1229
1230fn with_importance(mut record: MessageRecord, importance: MessageImportance) -> MessageRecord {
1231 record.importance = importance;
1232 record
1233}
1234
1235fn with_subject(mut record: MessageRecord, subject: &str) -> MessageRecord {
1236 record.subject = Some(subject.to_owned());
1237 record
1238}
1239
1240fn with_attachments(mut record: MessageRecord, attachments_json: &str) -> MessageRecord {
1241 record.attachments_json = attachments_json.to_owned();
1242 record
1243}
1244
1245fn with_links(mut record: MessageRecord, links_json: String) -> MessageRecord {
1246 record.links_json = links_json;
1247 record
1248}
1249
1250pub fn link_preview(url: &str) -> Option<LinkPreview> {
1251 Some(LinkPreview {
1252 url: url.to_owned(),
1253 title: Some("Release checklist Q4".to_owned()),
1254 description: Some(
1255 "Everything that has to be green before the release candidate goes out on Friday."
1256 .to_owned(),
1257 ),
1258 image_url: Some(LINK_IMAGE_KEY.to_owned()),
1259 image_width: Some(LINK_IMAGE_SIZE.0),
1260 image_height: Some(LINK_IMAGE_SIZE.1),
1261 })
1262}
1263
1264fn bot_messages() -> Vec<MessageRecord> {
1265 let card = serde_json::json!({
1266 "type": "AdaptiveCard",
1267 "body": [
1268 {"type": "ColumnSet", "columns": [
1269 {"type": "Column", "width": "auto", "verticalContentAlignment": "center", "items": [
1270 {"type": "Image", "url": CARD_PERSON_URL, "size": "small", "style": "person", "height": "32px"}
1271 ]},
1272 {"type": "Column", "width": "stretch", "verticalContentAlignment": "center", "items": [
1273 {"type": "TextBlock", "size": "medium", "weight": "bolder", "wrap": true, "text": "Mara Lindqvist edited your page"}
1274 ]}
1275 ]},
1276 {"type": "ColumnSet", "separator": true, "columns": [
1277 {"type": "Column", "width": "auto", "items": [
1278 {"type": "Image", "url": CARD_PAGE_URL, "width": "24px", "height": "24px"}
1279 ]},
1280 {"type": "Column", "width": "stretch", "items": [
1281 {"type": "TextBlock", "weight": "bolder", "wrap": true, "text": "[**Release Checklist Q4**](https://example.com/wiki/release-checklist) in [**Platform**](https://example.com/wiki/platform)"},
1282 {"type": "TextBlock", "spacing": "small", "isSubtle": true, "wrap": true, "text": "Owned by: Dana Demo"}
1283 ]}
1284 ]},
1285 {"type": "TextBlock", "id": "owner-note", "isVisible": false, "isSubtle": true, "wrap": true, "text": "Owner notes are only shown on request."},
1286 {"type": "ActionSet", "actions": [
1287 {"type": "Action.OpenUrl", "title": "View page", "url": "https://example.com/wiki/release-checklist"},
1288 {"type": "Action.OpenUrl", "title": "View changes", "url": "https://example.com/wiki/release-checklist/changes"},
1289 {"type": "Action.Submit", "title": "Watch page", "data": {"action": "watch"}},
1290 {"type": "Action.Submit", "title": "Stop watching", "data": {"action": "unwatch"}},
1291 {"type": "Action.Submit", "title": "Settings", "data": {"msteams": {"type": "task/fetch"}}},
1292 {"type": "Action.ToggleVisibility", "title": "Owner notes", "targetElements": ["owner-note"]},
1293 {"type": "Action.ShowCard", "title": "Details", "card": {"body": [
1294 {"type": "TextBlock", "wrap": true, "text": "Last edited by **Mara Lindqvist** on Tuesday."}
1295 ]}}
1296 ]}
1297 ]
1298 });
1299 let mut messages = vec![
1300 bot_card_message("b1", at(0, 13, 45), &card),
1301 bot_card_message("b2", at(0, 13, 52), &input_card()),
1302 bot_card_message(
1303 "b3",
1304 at(0, 13, 58),
1305 &crate::demo_input_cards::all_inputs_card(),
1306 ),
1307 ];
1308 messages.extend(
1309 crate::demo_cards::behaviour_cards()
1310 .iter()
1311 .zip(0u32..)
1312 .map(|(card, index)| bot_card_message(&format!("g{index}"), at(0, 14, index), card)),
1313 );
1314 messages.extend(crate::demo_chart_cards::cards().iter().zip(0..).map(
1315 |(chart_card, minute)| {
1316 bot_card_message(&format!("c{minute}"), at(0, 15, minute), chart_card)
1317 },
1318 ));
1319 messages
1320}
1321
1322fn bot_card_message(id: &str, time: DateTime<Utc>, card: &serde_json::Value) -> MessageRecord {
1323 let attachments = serde_json::json!([{
1324 "content_type": "application/vnd.microsoft.card.adaptive",
1325 "name": null,
1326 "url": null,
1327 "text": null,
1328 "content": card.to_string()
1329 }]);
1330 let mut record = with_attachments(
1331 message(
1332 BOT_CHAT,
1333 id,
1334 None,
1335 ("", BOT_NAME),
1336 time,
1337 &format!("<attachment id=\"{id}\"></attachment>"),
1338 "[]",
1339 false,
1340 ),
1341 &attachments.to_string(),
1342 );
1343 record.sender_id = None;
1344 record.sender_application_id = Some(BOT_ID.to_owned());
1345 record
1346}
1347
1348fn input_card() -> serde_json::Value {
1349 serde_json::json!({
1350 "type": "AdaptiveCard",
1351 "body": [
1352 {"type": "TextBlock", "size": "medium", "weight": "bolder", "text": "Release request"},
1353 {"type": "Input.Text", "id": "title", "label": "Title", "placeholder": "Short summary", "isRequired": true, "errorMessage": "Give the release a title"},
1354 {"type": "Input.Text", "id": "notes", "label": "Notes", "placeholder": "Anything the reviewers should know", "isMultiline": true},
1355 {"type": "Input.Text", "id": "token", "label": "Access code", "style": "Password", "regex": "^\\d{4}$", "errorMessage": "Enter four digits"},
1356 {"type": "ColumnSet", "columns": [
1357 {"type": "Column", "width": "stretch", "items": [
1358 {"type": "Input.Number", "id": "count", "label": "Servers", "placeholder": "1-20", "min": 1, "max": 20, "value": 4}
1359 ]},
1360 {"type": "Column", "width": "stretch", "items": [
1361 {"type": "Input.Date", "id": "day", "label": "Release day", "value": "2026-11-02"}
1362 ]},
1363 {"type": "Column", "width": "stretch", "items": [
1364 {"type": "Input.Time", "id": "hour", "label": "Start time", "value": "09:30"}
1365 ]}
1366 ]},
1367 {"type": "Input.ChoiceSet", "id": "channel", "label": "Channel", "placeholder": "Pick a channel", "isRequired": true, "choices": [
1368 {"title": "Stable", "value": "stable"}, {"title": "Beta", "value": "beta"}, {"title": "Nightly", "value": "nightly"}
1369 ]},
1370 {"type": "Input.ChoiceSet", "id": "region", "label": "Region", "style": "expanded", "value": "eu", "choices": [
1371 {"title": "Europe", "value": "eu"}, {"title": "North America", "value": "na"}
1372 ]},
1373 {"type": "Input.ChoiceSet", "id": "checks", "label": "Checks", "style": "expanded", "isMultiSelect": true, "value": "lint", "choices": [
1374 {"title": "Lint", "value": "lint"}, {"title": "Unit tests", "value": "unit"}, {"title": "Smoke tests", "value": "smoke"}
1375 ]},
1376 {"type": "Input.Toggle", "id": "notify", "title": "Notify the team", "value": "yes", "valueOn": "yes", "valueOff": "no"}
1377 ],
1378 "actions": [
1379 {"type": "Action.Submit", "title": "Request release", "data": {"action": "release"}},
1380 {"type": "Action.Submit", "title": "Cancel", "associatedInputs": "none", "data": {"action": "cancel"}}
1381 ]
1382 })
1383}
1384
1385fn bot_app() -> ChatApp {
1386 ChatApp {
1387 app_id: "demo-app-wiki".to_owned(),
1388 name: BOT_APP_NAME.to_owned(),
1389 bot_ids: vec![BOT_ID.to_owned()],
1390 small_image_url: None,
1391 accent_color: None,
1392 web_application_resource: None,
1393 }
1394}
1395
1396pub async fn card_answer(task: CardTask) -> CardAnswer {
1397 tokio::time::sleep(CARD_ANSWER_DELAY).await;
1398 let data = match task {
1399 CardTask::Submit(_) => {
1400 return Ok((
1401 CardActionOutcome::Message("Settings saved".into()),
1402 Some((bot_app(), BOT_ID.to_owned())),
1403 ));
1404 }
1405 CardTask::Action(action) => match action.invoke_payload() {
1406 Some(payload) => payload.value,
1407 None => return Err("Not supported".to_owned()),
1408 },
1409 };
1410 let outcome = if data.pointer("/data/type").and_then(|kind| kind.as_str()) == Some("task/fetch")
1411 {
1412 CardActionOutcome::Dialog(TaskDialog {
1413 title: None,
1414 width: 520,
1415 height: 300,
1416 kind: TaskDialogKind::Card(settings_card().to_string()),
1417 })
1418 } else if data.get("action").and_then(|action| action.as_str()) == Some("unwatch") {
1419 CardActionOutcome::Failed("The app answered 500: demo failure".into())
1420 } else {
1421 CardActionOutcome::Sent
1422 };
1423 Ok((outcome, Some((bot_app(), BOT_ID.to_owned()))))
1424}
1425
1426pub async fn refresh_answer() -> CardAnswer {
1427 tokio::time::sleep(CARD_ANSWER_DELAY).await;
1428 Ok((
1429 CardActionOutcome::ReplaceCard(crate::demo_cards::refreshed_card().to_string()),
1430 Some((bot_app(), BOT_ID.to_owned())),
1431 ))
1432}
1433
1434fn settings_card() -> serde_json::Value {
1435 serde_json::json!({
1436 "type": "AdaptiveCard",
1437 "body": [
1438 {"type": "TextBlock", "weight": "bolder", "text": "Notification settings"},
1439 {"type": "TextBlock", "wrap": true, "isSubtle": true, "text": "Choose how the bot tells you about page changes."},
1440 {"type": "Input.ChoiceSet", "id": "frequency", "label": "Frequency", "style": "expanded", "value": "daily", "choices": [
1441 {"title": "Immediately", "value": "now"}, {"title": "Daily digest", "value": "daily"}
1442 ]},
1443 {"type": "Input.Toggle", "id": "mentions", "title": "Only when I am mentioned", "value": "false"}
1444 ],
1445 "actions": [
1446 {"type": "Action.Submit", "title": "Save", "data": {"save": true}}
1447 ]
1448 })
1449}
1450
1451pub const DEMO_TENANT_ID: &str = "demo-tenant";
1452const DEMO_MEETING_LINK: &str = "https://teams.microsoft.com/l/meetup-join/19%3ameeting_ZGVtbw%40thread.v2/0?context=%7b%22Tid%22%3a%22demo-tenant%22%2c%22Oid%22%3a%22demo-mara%22%7d";
1453
1454fn meeting_link_messages() -> Vec<MessageRecord> {
1455 let mara = (MARA_ID, "Mara Lindqvist");
1456 vec![message(
1457 "demo-chat-mara",
1458 "ml1",
1459 None,
1460 mara,
1461 at(0, 13, 38),
1462 &format!(
1463 "<p>Let's sync live, here is the meeting: <a href=\"{DEMO_MEETING_LINK}\">Join the Teams meeting</a></p>"
1464 ),
1465 "[]",
1466 false,
1467 )]
1468}
1469
1470fn standup_messages() -> Vec<MessageRecord> {
1471 let jonas = (JONAS_ID, "Jonas Ortega");
1472 let priya = (PRIYA_ID, "Priya Nair");
1473 vec![
1474 with_attachments(
1475 message(
1476 "demo-chat-meeting-standup",
1477 "su1",
1478 None,
1479 priya,
1480 at(0, 9, 30),
1481 "<p>Notes from today.</p>",
1482 "[]",
1483 false,
1484 ),
1485 r#"[{"content_type":"reference","name":"Standup-notes.docx","url":"https://example.com/files/standup-notes.docx","text":null,"size":38900}]"#,
1486 ),
1487 message(
1488 "demo-chat-meeting-standup",
1489 "su2",
1490 None,
1491 jonas,
1492 at(0, 9, 45),
1493 "<p>Recording is available</p>",
1494 "[]",
1495 false,
1496 ),
1497 with_links(
1498 message(
1499 "demo-chat-meeting-standup",
1500 "su3",
1501 None,
1502 jonas,
1503 at(0, 9, 50),
1504 "<p><a href=\"https://example.com/checklist\">https://example.com/checklist</a></p>",
1505 "[]",
1506 false,
1507 ),
1508 link_preview("https://example.com/checklist")
1509 .map(|preview| preview.links_json())
1510 .unwrap_or_default(),
1511 ),
1512 message(
1513 "demo-chat-meeting-standup",
1514 "su4",
1515 None,
1516 priya,
1517 at(0, 9, 52),
1518 "<p>I will quickly fix the comments and then push the final version before the review starts.</p>",
1519 "[]",
1520 false,
1521 ),
1522 ]
1523}
1524
1525fn notes_messages() -> Vec<MessageRecord> {
1526 vec![message(
1527 NOTES_CHAT_ID,
1528 "n1",
1529 None,
1530 (DEMO_USER_ID, DEMO_USER_NAME),
1531 at(0, 8, 20),
1532 "<p>Release notes draft</p>",
1533 "[]",
1534 false,
1535 )]
1536}
1537
1538fn priority_messages() -> Vec<MessageRecord> {
1539 let priya = (PRIYA_ID, "Priya Nair");
1540 let me = (DEMO_USER_ID, DEMO_USER_NAME);
1541 vec![
1542 message(
1543 PRIORITY_CHAT,
1544 "p1",
1545 None,
1546 me,
1547 at(0, 10, 40),
1548 "<p>Have you seen the error on staging yet?</p>",
1549 "[]",
1550 false,
1551 ),
1552 message(
1553 PRIORITY_CHAT,
1554 "p2",
1555 None,
1556 priya,
1557 at(0, 10, 47),
1558 &format!(
1559 "<p>Yes, here is the screenshot:</p><img src=\"{PENDING_IMAGE_KEY}\" width=\"1280\" height=\"720\">"
1560 ),
1561 "[]",
1562 false,
1563 ),
1564 ]
1565 .into_iter()
1566 .map(|record| match record.message_id.as_str() {
1567 "p2" => with_importance(record, MessageImportance::High),
1568 _ => record,
1569 })
1570 .collect()
1571}
1572
1573fn reaction(kind: &str, users: &[(&str, &str, DateTime<Utc>)]) -> Vec<serde_json::Value> {
1574 users
1575 .iter()
1576 .map(|(user_id, user_name, created_at)| {
1577 serde_json::json!({
1578 "reaction_type": kind,
1579 "user_id": user_id,
1580 "user_name": user_name,
1581 "created_at": created_at,
1582 })
1583 })
1584 .collect()
1585}
1586
1587fn reactions_json(groups: Vec<Vec<serde_json::Value>>) -> String {
1588 serde_json::Value::Array(groups.into_iter().flatten().collect()).to_string()
1589}
1590
1591fn release_messages() -> Vec<MessageRecord> {
1592 let chat = RELEASE_CHAT;
1593 let mara = (MARA_ID, "Mara Lindqvist");
1594 let jonas = (JONAS_ID, "Jonas Ortega");
1595 let me = (DEMO_USER_ID, DEMO_USER_NAME);
1596 let jonas_name = "Jonas Ortega";
1597 let priya_name = "Priya Nair";
1598 let lea_name = "Lea Schneider";
1599 let mara_name = "Mara Lindqvist";
1600 let tobias_name = "Tobias Klein";
1601 let likes = reactions_json(vec![reaction(
1602 "like",
1603 &[
1604 (JONAS_ID, jonas_name, at(1, 16, 30)),
1605 (PRIYA_ID, priya_name, at(1, 17, 2)),
1606 (LEA_ID, lea_name, at(0, 8, 15)),
1607 ],
1608 )]);
1609 let hearts = reactions_json(vec![reaction(
1610 "heart",
1611 &[
1612 (DEMO_USER_ID, DEMO_USER_NAME, at(0, 10, 35)),
1613 (JONAS_ID, jonas_name, at(0, 10, 33)),
1614 ],
1615 )]);
1616 let single = reactions_json(vec![reaction(
1617 "laugh",
1618 &[(PRIYA_ID, priya_name, at(0, 9, 10))],
1619 )]);
1620 let many = reactions_json(vec![
1621 reaction(
1622 "like",
1623 &[
1624 (MARA_ID, mara_name, at(0, 13, 37)),
1625 (JONAS_ID, jonas_name, at(0, 13, 38)),
1626 (PRIYA_ID, priya_name, at(0, 13, 40)),
1627 (LEA_ID, lea_name, at(0, 13, 45)),
1628 (TOBIAS_ID, tobias_name, at(0, 13, 50)),
1629 ],
1630 ),
1631 reaction(
1632 "heart",
1633 &[
1634 (LEA_ID, lea_name, at(0, 13, 46)),
1635 (TOBIAS_ID, tobias_name, at(0, 13, 51)),
1636 ],
1637 ),
1638 reaction("\u{1F389}", &[(MARA_ID, mara_name, at(0, 13, 39))]),
1639 ]);
1640 vec![
1641 message(
1642 chat,
1643 "m1",
1644 None,
1645 mara,
1646 at(1, 16, 20),
1647 "<p>Release candidate is on staging. Can someone run the regression suite?</p>",
1648 "[]",
1649 false,
1650 ),
1651 message(
1652 chat,
1653 "m2",
1654 None,
1655 mara,
1656 at(1, 16, 22),
1657 "<p>Checklist lives in <a href=\"https://example.com/checklist\">release checklist</a>.</p>",
1658 &likes,
1659 false,
1660 ),
1661 with_links(
1662 message(
1663 chat,
1664 "m2a",
1665 None,
1666 mara,
1667 at(1, 16, 23),
1668 "<p><a href=\"https://example.com/checklist\">https://example.com/checklist</a></p>",
1669 "[]",
1670 false,
1671 ),
1672 link_preview("https://example.com/checklist")
1673 .map(|preview| preview.links_json())
1674 .unwrap_or_default(),
1675 ),
1676 message(
1677 chat,
1678 "m2b",
1679 None,
1680 mara,
1681 at(1, 16, 40),
1682 &format!(
1683 "<p>Staging dashboard right now:</p><img src=\"{STAGING_IMAGE_KEY}\" width=\"{}\" height=\"{}\">",
1684 STAGING_SIZE.0, STAGING_SIZE.1
1685 ),
1686 "[]",
1687 false,
1688 ),
1689 with_attachments(
1690 message(
1691 chat,
1692 "m2c",
1693 None,
1694 mara,
1695 at(1, 16, 41),
1696 "<p>Checklist and rollout plan attached.</p>",
1697 "[]",
1698 false,
1699 ),
1700 r#"[{"content_type":"reference","name":"Release-Checklist-Q4.xlsx","url":"https://example.com/files/checklist.xlsx","text":null,"size":48213},{"content_type":"reference","name":"Rollout-Plan.pdf","url":"https://example.com/files/plan.pdf","text":null,"size":2306867}]"#,
1701 ),
1702 message(
1703 chat,
1704 "m3",
1705 None,
1706 me,
1707 at(0, 9, 2),
1708 "<p>I'll take the changelog.</p>",
1709 &single,
1710 false,
1711 ),
1712 message(
1713 chat,
1714 "m4",
1715 None,
1716 jonas,
1717 at(0, 10, 14),
1718 "<p><at id=\"0\">Mara Lindqvist</at> can you take a quick look at this? It runs before <code>cargo test</code>.</p><pre><code class=\"language-rust\">// only release branches\nfn freeze(branch: &amp;str) -&gt; bool {\n branch.starts_with(\"release/\")\n}</code></pre>",
1719 "[]",
1720 false,
1721 ),
1722 message(
1723 chat,
1724 "m5",
1725 None,
1726 mara,
1727 at(0, 10, 31),
1728 "<blockquote itemscope=\"\" itemtype=\"http://schema.skype.com/Reply\" itemid=\"m4\"><strong itemprop=\"mri\">Jonas Ortega</strong><p itemprop=\"preview\">can you take a quick look at this?</p></blockquote><p>Looks good. Small thing: the name could say what it checks.</p>",
1729 &hearts,
1730 true,
1731 ),
1732 message(
1733 chat,
1734 "m5b",
1735 None,
1736 mara,
1737 at(0, 10, 40),
1738 "<p>Rollout for Friday:</p><ul><li>Freeze the release branch</li><li>Run the smoke tests on staging, then post the results in the channel</li><li>Ship<ul><li>Windows installer</li><li>Linux <code>.AppImage</code></li></ul></li></ul><p>Order:</p><ol><li>Tag</li><li>Build</li><li>Announce</li></ol>",
1739 "[]",
1740 false,
1741 ),
1742 message(
1743 chat,
1744 "m5c",
1745 None,
1746 jonas,
1747 at(0, 11, 5),
1748 "<h2>Release notes 0.2</h2><p>The <s>old sync path</s> <u>is gone</u>.</p><table><thead><tr><th>Area</th><th>Owner</th></tr></thead><tbody><tr><td>Sync</td><td>Priya</td></tr><tr><td>Render</td><td>Jonas</td></tr></tbody></table><hr><blockquote>Measure twice, cut once.</blockquote><p><span style=\"background-color: rgb(255, 255, 0)\">Important:</span> <span style=\"color: #c00000\">backup first</span>.</p><p style=\"margin-left:40px;\">Then <span style=\"color:#1E53A3;\">sync</span> <span style=\"background-color:#82CDA8;\">once</span>.</p><pre class=\"language-plaintext skipProofing\" spellcheck=\"false\"><code>backup --all<br>sync --once</code></pre>",
1749 "[]",
1750 false,
1751 ),
1752 message(
1753 chat,
1754 "m5d",
1755 None,
1756 (PRIYA_ID, priya_name),
1757 at(0, 12, 20),
1758 &format!(
1759 "<p>FYI, the customer asked for this.</p><blockquote itemscope=\"\" itemtype=\"{FORWARD_ITEMTYPE}\" itemid=\"1790000000000\"><strong>Tobias Klein</strong><p>Can we move the freeze to Thursday? The customer demo is on Friday morning.</p></blockquote>"
1760 ),
1761 "[]",
1762 false,
1763 ),
1764 message(
1765 chat,
1766 "m5e",
1767 None,
1768 jonas,
1769 at(0, 12, 40),
1770 "<p>Context from the old planning chat.</p><attachment id=\"1789000000000\"></attachment>",
1771 r#"[{"content_type":"forwardedMessageReference","name":null,"url":null,"text":null,"id":"1789000000000","content":null,"unavailable":true}]"#,
1772 false,
1773 ),
1774 message(
1775 chat,
1776 "m6",
1777 None,
1778 me,
1779 at(0, 13, 35),
1780 "<p>Thanks, renamed. Tagging now.</p>",
1781 "[]",
1782 false,
1783 ),
1784 message(
1785 chat,
1786 "m7",
1787 None,
1788 me,
1789 at(0, 13, 36),
1790 "<p>Build 42 is green, see <a href=\"https://example.com/build/42\">pipeline</a>.</p>",
1791 &many,
1792 false,
1793 ),
1794 with_links(
1795 message(
1796 chat,
1797 "m7a",
1798 None,
1799 me,
1800 at(0, 13, 37),
1801 "<p>Notes are in <a href=\"https://example.com/notes\">https://example.com/notes</a></p>",
1802 "[]",
1803 false,
1804 ),
1805 LinkPreview {
1806 url: "https://example.com/notes".to_owned(),
1807 title: Some("Release notes 0.2".to_owned()),
1808 description: Some("What changed since 0.1".to_owned()),
1809 image_url: None,
1810 image_width: None,
1811 image_height: None,
1812 }
1813 .links_json(),
1814 ),
1815 message(
1816 chat,
1817 "m8",
1818 None,
1819 jonas,
1820 at(0, 13, 40),
1821 "<p>Formula check: H<sub>2</sub>O and x<sup>2</sup> + y<sup>2</sup>. <span style=\"font-size:xx-small;\">Small print, reviewed by <at id=\"0\">Mara Lindqvist</at>.</span> <span style=\"font-size:x-large;\">Big news:</span> the <span style=\"font-size:x-large;\"><a href=\"https://example.com/notes\">release notes</a></span> are out.</p>",
1822 "[]",
1823 false,
1824 ),
1825 message(
1826 chat,
1827 "m9",
1828 None,
1829 (PRIYA_ID, priya_name),
1830 at(0, 13, 45),
1831 &format!(
1832 "<p>Ship it!</p><img src=\"{}\" width=\"{}\" height=\"{}\" alt=\"Party\" itemtype=\"http://schema.skype.com/Giphy\">",
1833 demo_gifs::RECEIVED_GIF_KEY,
1834 demo_gifs::RECEIVED_GIF_SIZE.0,
1835 demo_gifs::RECEIVED_GIF_SIZE.1
1836 ),
1837 "[]",
1838 false,
1839 ),
1840 message(
1841 chat,
1842 FRENCH_MESSAGE,
1843 None,
1844 (LEA_ID, lea_name),
1845 at(0, 13, 47),
1846 "<p>Bonjour \u{e0} tous, la <strong>version 0.2</strong> est pr\u{ea}te. Pouvez-vous v\u{e9}rifier la liste de contr\u{f4}le avant vendredi\u{a0}?</p>",
1847 "[]",
1848 false,
1849 ),
1850 message(
1851 chat,
1852 SPANISH_MESSAGE,
1853 None,
1854 jonas,
1855 at(0, 13, 49),
1856 "<p>Gracias por el aviso. Probar\u{e9} la compilaci\u{f3}n esta tarde y os dir\u{e9} si algo falla.</p>",
1857 "[]",
1858 false,
1859 ),
1860 message(
1861 chat,
1862 "m10",
1863 None,
1864 (PRIYA_ID, priya_name),
1865 at(0, 13, 50),
1866 "<p><emoji id=\"heart\" alt=\"\u{2764}\u{fe0f}\" title=\"Heart\"></emoji></p>",
1867 &many,
1868 false,
1869 ),
1870 message(
1871 chat,
1872 "m11",
1873 None,
1874 me,
1875 at(0, 13, 51),
1876 "<p>\u{1f44d}\u{1f389}</p>",
1877 "[]",
1878 false,
1879 ),
1880 ]
1881}
1882
1883fn unread_messages() -> Vec<MessageRecord> {
1884 let me = (DEMO_USER_ID, DEMO_USER_NAME);
1885 let lea = (LEA_ID, "Lea Schneider");
1886 let tobias = (TOBIAS_ID, "Tobias Klein");
1887 let rows = [
1888 (
1889 "u1",
1890 me,
1891 at(1, 17, 5),
1892 "<p>Can you enable access for North?</p>",
1893 ),
1894 ("u2", tobias, at(1, 17, 20), "<p>I'll check with IT.</p>"),
1895 (
1896 "u3",
1897 lea,
1898 at(0, 12, 40),
1899 "<p>Good morning, access is ready.</p>",
1900 ),
1901 (
1902 "u4",
1903 lea,
1904 at(0, 12, 41),
1905 "<p>Sign in with your company ID, no password needed.</p>",
1906 ),
1907 ("u5", lea, at(0, 12, 50), "<p>Access is enabled now</p>"),
1908 ];
1909 rows.into_iter()
1910 .map(|(id, sender, time, html)| {
1911 message(UNREAD_CHAT, id, None, sender, time, html, "[]", false)
1912 })
1913 .map(|record| match record.message_id.as_str() {
1914 "u5" => with_importance(record, MessageImportance::Urgent),
1915 _ => record,
1916 })
1917 .collect()
1918}
1919
1920const DEMO_EXTRA_TABS_CHANNEL: &str = "demo-channel-1-2";
1921const DEMO_EXTRA_TABS: [&str; 6] = [
1922 "Incident dashboard",
1923 "Postmortems",
1924 "Escalation policy",
1925 "Status page",
1926 "Vendor contacts",
1927 "On-call calendar",
1928];
1929
1930fn demo_tab(
1931 channel_id: &str,
1932 name: &str,
1933 definition_id: &str,
1934 open_url: Option<&str>,
1935) -> ChannelTabRecord {
1936 ChannelTabRecord {
1937 tab_id: format!("{channel_id}-{}", name.to_lowercase().replace(' ', "-")),
1938 name: name.to_owned(),
1939 definition_id: definition_id.to_owned(),
1940 open_url: open_url.map(str::to_owned),
1941 }
1942}
1943
1944fn demo_channel_tabs(channel_id: &str) -> Vec<ChannelTabRecord> {
1945 let mut tabs = vec![
1946 demo_tab(
1947 channel_id,
1948 "Runbook",
1949 "com.microsoft.teamspace.tab.web",
1950 Some("https://wiki.example.com/display/TEAM/Runbook"),
1951 ),
1952 demo_tab(
1953 channel_id,
1954 "Sprint board",
1955 "com.microsoft.teamspace.tab.planner",
1956 None,
1957 ),
1958 demo_tab(
1959 channel_id,
1960 "Team notes",
1961 "0d820ecd-def2-4297-adad-78056cde7c78",
1962 Some("https://onenote.example.com/notes"),
1963 ),
1964 ];
1965 if channel_id == DEMO_EXTRA_TABS_CHANNEL {
1966 tabs.extend(DEMO_EXTRA_TABS.iter().map(|name| {
1967 demo_tab(
1968 channel_id,
1969 name,
1970 "com.microsoft.teamspace.tab.web",
1971 Some("https://wiki.example.com/display/TEAM/Page"),
1972 )
1973 }));
1974 }
1975 tabs
1976}
1977
1978fn demo_team_layout(channels: &[ChannelRecord]) -> Vec<TeamLayoutRecord> {
1979 DEMO_TEAM_ORDER
1980 .iter()
1981 .map(|team_id| TeamLayoutRecord {
1982 team_id: (*team_id).to_owned(),
1983 hidden: *team_id == DEMO_HIDDEN_TEAM,
1984 channels: channels
1985 .iter()
1986 .filter(|channel| channel.team_id == *team_id)
1987 .map(|channel| ChannelLayoutRecord {
1988 channel_id: channel.id.clone(),
1989 general: channel.name == "General",
1990 hidden: channel.id == DEMO_HIDDEN_CHANNEL,
1991 tabs: demo_channel_tabs(&channel.id),
1992 notifications: DEMO_CHANNEL_NOTIFICATIONS
1993 .iter()
1994 .find(|(id, _, _)| *id == channel.id)
1995 .map(|(_, level, include_replies)| ChannelNotifications {
1996 level: *level,
1997 include_replies: *include_replies,
1998 })
1999 .unwrap_or_default(),
2000 })
2001 .collect(),
2002 })
2003 .collect()
2004}
2005
2006const ROLLOUT_REPLIES: [(&str, &str); 12] = [
2007 (MARA_ID, "Staging looks good on my side."),
2008 (JONAS_ID, "Smoke tests passed, no regressions."),
2009 (PRIYA_ID, "Docs for the new settings page are merged."),
2010 (LEA_ID, "Support is briefed, nothing blocking."),
2011 (MARA_ID, "Can we keep the old export for one more release?"),
2012 (JONAS_ID, "Yes, behind a flag. I will add it today."),
2013 (PRIYA_ID, "Changelog draft is ready for review."),
2014 (LEA_ID, "Customer success wants a heads-up the day before."),
2015 (MARA_ID, "I will send that mail on Thursday."),
2016 (JONAS_ID, "Flag is in, rebuilding staging now."),
2017 (PRIYA_ID, "Rollback steps are in the runbook."),
2018 (LEA_ID, "All green from QA. Go for Friday."),
2019];
2020
2021fn channel_messages() -> Vec<MessageRecord> {
2022 let channel = "demo-channel-1-1";
2023 let mara = (MARA_ID, "Mara Lindqvist");
2024 let tobias = (TOBIAS_ID, "Tobias Klein");
2025 let people = [
2026 (MARA_ID, "Mara Lindqvist"),
2027 (JONAS_ID, "Jonas Ortega"),
2028 (PRIYA_ID, "Priya Nair"),
2029 (LEA_ID, "Lea Schneider"),
2030 ];
2031 let rollout_replies = ROLLOUT_REPLIES
2032 .iter()
2033 .enumerate()
2034 .map(|(index, (sender, text))| {
2035 let sender = people
2036 .iter()
2037 .copied()
2038 .find(|(id, _)| id == sender)
2039 .expect("known person");
2040 message(
2041 channel,
2042 &format!("t3r{}", index + 1),
2043 Some("t3"),
2044 sender,
2045 at(0, 9, 40) + Duration::minutes(6 * index as i64),
2046 &format!("<p>{text}</p>"),
2047 "[]",
2048 false,
2049 )
2050 });
2051 let mut records = vec![
2052 message(
2053 channel,
2054 "t1",
2055 None,
2056 mara,
2057 at(0, 8, 0),
2058 "<p>Weekly sync notes are up.</p>",
2059 "[]",
2060 false,
2061 ),
2062 message(
2063 channel,
2064 "t1r1",
2065 Some("t1"),
2066 tobias,
2067 at(0, 8, 20),
2068 "<p>Thanks, adding my items.</p>",
2069 "[]",
2070 false,
2071 ),
2072 with_subject(
2073 message(
2074 channel,
2075 "t3",
2076 None,
2077 tobias,
2078 at(0, 9, 30),
2079 "<p>Release build 42 is green, deploying to staging now.</p>",
2080 "[]",
2081 false,
2082 ),
2083 "Release 42 rollout",
2084 ),
2085 message(
2086 channel,
2087 "t2",
2088 None,
2089 tobias,
2090 at(0, 10, 0),
2091 "<p>Who owns the on-call handover?</p>",
2092 "[]",
2093 false,
2094 ),
2095 message(
2096 channel,
2097 "t4",
2098 None,
2099 mara,
2100 at(3, 8, 42),
2101 "<p>Sprint Demos.</p><p>I added you both to the sprint. <at id=\"0\">Tobias Klein</at> did you present everything about the migration tool? The spec is at <a href=\"https://wiki.example.com/display/TEAM/Settings+types+and+password+policies\">https://wiki.example.com/display/TEAM/Settings+types+and+password+policies</a>Can you please review it?</p>",
2102 "[]",
2103 false,
2104 ),
2105 message(
2106 channel,
2107 "t4r1",
2108 Some("t4"),
2109 tobias,
2110 at(0, 9, 15),
2111 "<p>Yes, all done.</p>",
2112 "[]",
2113 false,
2114 ),
2115 ];
2116 records.extend(rollout_replies);
2117 records.extend(code_post(channel, tobias));
2118 records.extend(shared_channel_messages(channel, mara, tobias));
2119 records
2120}
2121
2122fn code_post(channel: &str, tobias: (&str, &str)) -> Vec<MessageRecord> {
2123 let laughs = reactions_json(vec![reaction(
2124 "laugh",
2125 &[
2126 (PRIYA_ID, "Priya Nair", at(0, 11, 20)),
2127 (JONAS_ID, "Jonas Ortega", at(0, 11, 22)),
2128 ],
2129 )]);
2130 vec![
2131 with_subject(
2132 message(
2133 channel,
2134 "t8",
2135 None,
2136 tobias,
2137 at(0, 11, 5),
2138 "<p>I got this error message when running \"Invoke-WebRequest\" in the build script:</p><p>&nbsp;</p><p><code>Invoke-WebRequest : The response content cannot be parsed because the Internet Explorer engine is not available, or Internet Explorer's first-launch configuration is not complete. Specify the UseBasicParsing parameter and try again.</code></p>",
2139 &laughs,
2140 false,
2141 ),
2142 "Build script error",
2143 ),
2144 message(
2145 channel,
2146 "t8r1",
2147 Some("t8"),
2148 (JONAS_ID, "Jonas Ortega"),
2149 at(0, 11, 30),
2150 "<p>Add <code>-UseBasicParsing</code> to the call, that fixes it.</p>",
2151 "[]",
2152 false,
2153 ),
2154 ]
2155}
2156
2157fn shared_channel_messages(
2158 channel: &str,
2159 mara: (&str, &str),
2160 tobias: (&str, &str),
2161) -> Vec<MessageRecord> {
2162 let priya = (PRIYA_ID, "Priya Nair");
2163 let jonas = (JONAS_ID, "Jonas Ortega");
2164 let reference = |name: &str, size: u64| {
2165 format!(
2166 r#"{{"content_type":"reference","name":"{name}","url":"https://demo.sharepoint.example/sites/demo/{name}","text":null,"size":{size}}}"#
2167 )
2168 };
2169 vec![
2170 with_attachments(
2171 with_subject(
2172 message(
2173 channel,
2174 "t5",
2175 None,
2176 priya,
2177 at(1, 14, 5),
2178 "<p>Roadmap deck and checklist for Q4 are attached.</p>",
2179 "[]",
2180 false,
2181 ),
2182 "Q4 planning files",
2183 ),
2184 &format!(
2185 "[{},{}]",
2186 reference("Roadmap-Q4.pptx", 3_412_000),
2187 reference("Release-Checklist-Q4.xlsx", 48_213)
2188 ),
2189 ),
2190 message(
2191 channel,
2192 "t5r1",
2193 Some("t5"),
2194 jonas,
2195 at(1, 14, 30),
2196 "<p>Rollback steps are here: <a href=\"https://docs.example.org/runbooks/rollback\">https://docs.example.org/runbooks/rollback</a></p>",
2197 "[]",
2198 false,
2199 ),
2200 with_attachments(
2201 message(
2202 channel,
2203 "t6",
2204 None,
2205 mara,
2206 at(12, 10, 0),
2207 "<p>Postmortem draft for the September outage. Status page: <a href=\"https://status.example.com/incidents/2026-09\">https://status.example.com/incidents/2026-09</a></p>",
2208 "[]",
2209 false,
2210 ),
2211 &format!("[{}]", reference("Postmortem-Draft.docx", 91_400)),
2212 ),
2213 with_attachments(
2214 message(
2215 channel,
2216 "t7",
2217 None,
2218 tobias,
2219 at(20, 9, 0),
2220 "<p>Rollout plan for the new export, please review.</p>",
2221 "[]",
2222 false,
2223 ),
2224 &format!("[{}]", reference("Rollout-Plan.pdf", 2_306_867)),
2225 ),
2226 ]
2227}
2228
2229fn crc32(bytes: &[u8]) -> u32 {
2230 let mut crc = 0xffff_ffffu32;
2231 for byte in bytes {
2232 crc ^= u32::from(*byte);
2233 for _ in 0..8 {
2234 crc = if crc & 1 == 1 {
2235 (crc >> 1) ^ 0xedb8_8320
2236 } else {
2237 crc >> 1
2238 };
2239 }
2240 }
2241 !crc
2242}
2243
2244fn adler32(bytes: &[u8]) -> u32 {
2245 let (mut low, mut high) = (1u32, 0u32);
2246 for byte in bytes {
2247 low = (low + u32::from(*byte)) % 65521;
2248 high = (high + low) % 65521;
2249 }
2250 (high << 16) | low
2251}
2252
2253fn png_chunk(output: &mut Vec<u8>, kind: &[u8; 4], data: &[u8]) {
2254 output.extend_from_slice(&(data.len() as u32).to_be_bytes());
2255 let mut body = kind.to_vec();
2256 body.extend_from_slice(data);
2257 output.extend_from_slice(&body);
2258 output.extend_from_slice(&crc32(&body).to_be_bytes());
2259}
2260
2261fn inside(x: f32, y: f32, center: (f32, f32), radius: (f32, f32)) -> bool {
2262 ((x - center.0) / radius.0).powi(2) + ((y - center.1) / radius.1).powi(2) <= 1.
2263}
2264
2265fn staging_pixel(column: usize, row: usize) -> [u8; 3] {
2266 let (width, height) = (STAGING_SIZE.0 as f32, STAGING_SIZE.1 as f32);
2267 let (x, y) = (column as f32, row as f32);
2268 let shade = y / height;
2269 let background = [
2270 (30. - 14. * shade) as u8,
2271 (41. - 16. * shade) as u8,
2272 (59. - 14. * shade) as u8,
2273 ];
2274 let bar_width = width / 14.;
2275 let slot = (x / bar_width) as usize;
2276 let in_bar = x - slot as f32 * bar_width > bar_width * 0.18;
2277 let bar_height = height * (0.25 + 0.5 * (((slot * 7 + 3) % 11) as f32 / 11.));
2278 let on_bars = in_bar && y > height * 0.86 - bar_height && y < height * 0.86 && slot < 14;
2279 let header = y < height * 0.1;
2280 if header {
2281 [22, 30, 45]
2282 } else if on_bars {
2283 if slot % 4 == 3 {
2284 [226, 87, 47]
2285 } else {
2286 [88, 133, 196]
2287 }
2288 } else if (y - height * 0.86).abs() < 1.5 {
2289 [71, 85, 105]
2290 } else {
2291 background
2292 }
2293}
2294
2295fn encode_png(palette: &Palette) -> Vec<u8> {
2296 let scale = PHOTO_SIZE as f32 / DEMO_PHOTO_SIDE as f32;
2297 encode_rgb(DEMO_PHOTO_SIDE, DEMO_PHOTO_SIDE, |column, row| {
2298 let (x, y) = ((column as f32 + 0.5) * scale, (row as f32 + 0.5) * scale);
2299 if inside(x, y, (24., 21.), (8.5, 9.5)) {
2300 palette.skin
2301 } else if inside(x, y, (24., 19.), (10.5, 11.)) && y < 22. {
2302 palette.hair
2303 } else if inside(x, y, (24., 50.), (22., 19.)) {
2304 palette.shirt
2305 } else {
2306 palette.background
2307 }
2308 })
2309}
2310
2311fn encode_rgb(width: usize, height: usize, pixel: impl Fn(usize, usize) -> [u8; 3]) -> Vec<u8> {
2312 let mut raw = Vec::with_capacity(height * (width * 3 + 1));
2313 for row in 0..height {
2314 raw.push(0);
2315 for column in 0..width {
2316 raw.extend_from_slice(&pixel(column, row));
2317 }
2318 }
2319 let mut zlib = vec![0x78, 0x01];
2320 let mut blocks = raw.chunks(65535).peekable();
2321 while let Some(block) = blocks.next() {
2322 zlib.push(u8::from(blocks.peek().is_none()));
2323 zlib.extend_from_slice(&(block.len() as u16).to_le_bytes());
2324 zlib.extend_from_slice(&(!(block.len() as u16)).to_le_bytes());
2325 zlib.extend_from_slice(block);
2326 }
2327 zlib.extend_from_slice(&adler32(&raw).to_be_bytes());
2328 let mut header = Vec::new();
2329 header.extend_from_slice(&(width as u32).to_be_bytes());
2330 header.extend_from_slice(&(height as u32).to_be_bytes());
2331 header.extend_from_slice(&[8, 2, 0, 0, 0]);
2332 let mut png = vec![0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a];
2333 png_chunk(&mut png, b"IHDR", &header);
2334 png_chunk(&mut png, b"IDAT", &zlib);
2335 png_chunk(&mut png, b"IEND", &[]);
2336 png
2337}
2338
2339#[cfg(test)]
2340mod tests {
2341 use super::*;
2342
2343 #[test]
2344 fn the_demo_has_one_important_and_one_urgent_message() {
2345 let store = Store::open_in_memory().unwrap();
2346 seed(&store);
2347 let importance = |chat: &str, message_id: &str| {
2348 store
2349 .messages(chat, None, 50)
2350 .unwrap()
2351 .into_iter()
2352 .find(|record| record.message_id == message_id)
2353 .map(|record| record.importance)
2354 };
2355 assert_eq!(
2356 importance(PRIORITY_CHAT, "p2"),
2357 Some(MessageImportance::High)
2358 );
2359 assert_eq!(
2360 importance(UNREAD_CHAT, "u5"),
2361 Some(MessageImportance::Urgent)
2362 );
2363 }
2364
2365 #[test]
2366 fn a_multi_forward_quotes_each_message_in_order_after_the_comment() {
2367 let store = Store::open_in_memory().unwrap();
2368 seed(&store);
2369 let chat = store
2370 .recent_chats(100)
2371 .unwrap()
2372 .into_iter()
2373 .find(|chat| chat.id == PRIORITY_CHAT)
2374 .unwrap();
2375 let item = |message_id: &str, text: &str| crate::message_actions::ForwardItem {
2376 message_id: message_id.to_owned(),
2377 author: "Synthetic Sender".to_owned(),
2378 time: "09:00".to_owned(),
2379 text: text.to_owned(),
2380 };
2381 let source = ForwardSource {
2382 conversation_id: PRIORITY_CHAT.to_owned(),
2383 messages: vec![item("m1", "first"), item("m2", "second")],
2384 };
2385 let (_, record) = forwarded_message(&chat, &source, "fyi", Utc::now());
2386 let html = &record.body_html;
2387 assert!(html.starts_with("<p>fyi</p>"));
2388 assert_eq!(html.matches(FORWARD_ITEMTYPE).count(), 2);
2389 assert!(html.find("first").unwrap() < html.find("second").unwrap());
2390 }
2391
2392 #[test]
2393 fn png_has_signature_and_ends_with_iend() {
2394 let png = encode_png(&MARA);
2395 assert_eq!(&png[..8], &[0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a]);
2396 assert_eq!(&png[png.len() - 8..png.len() - 4], b"IEND");
2397 }
2398
2399 #[test]
2400 fn crc_and_adler_match_known_values() {
2401 assert_eq!(crc32(b"IEND"), 0xae42_6082);
2402 assert_eq!(adler32(b"Wikipedia"), 0x11e6_0398);
2403 }
2404
2405 #[test]
2406 fn mention_candidates_filter_by_name_and_add_scope_in_channels() {
2407 let chat = mention_candidates("demo-chat-release", "ma");
2408 assert_eq!(chat.len(), 1);
2409 assert_eq!(chat[0].display_name(), "Mara Lindqvist");
2410 let channel = mention_candidates("demo-channel-1-1", "gen");
2411 assert!(matches!(channel[0], MentionCandidate::Channel { .. }));
2412 assert_eq!(mention_candidates("demo-chat-release", "").len(), 5);
2413 }
2414
2415 #[test]
2416 fn new_group_chat_gets_a_title_and_the_first_message() {
2417 let people = vec![
2418 (MARA_ID.to_owned(), "Mara Lindqvist".to_owned()),
2419 (JONAS_ID.to_owned(), "Jonas Ortega".to_owned()),
2420 ];
2421 let now = Utc::now();
2422 let (chat, record) = new_chat(
2423 &[],
2424 &people,
2425 Some("Crew"),
2426 "Hello all",
2427 "Hello <i>all</i>",
2428 now,
2429 );
2430 assert_eq!(chat.id, "demo-chat-new-1");
2431 assert_eq!(chat.kind, "group");
2432 assert_eq!(chat.title, "Crew");
2433 assert_eq!(chat.member_summary, "Mara Lindqvist, Jonas Ortega");
2434 assert_eq!(chat.members.len(), 3);
2435 assert_eq!(chat.members[0].user_id.as_deref(), Some(DEMO_USER_ID));
2436 assert_eq!(chat.last_message_preview.as_deref(), Some("Hello all"));
2437 assert_eq!(chat.last_message_at, Some(now));
2438 assert_eq!(record.conversation_id, chat.id);
2439 assert_eq!(record.sender_id.as_deref(), Some(DEMO_USER_ID));
2440 assert!(record.body_html.contains("Hello"));
2441 }
2442
2443 #[test]
2444 fn new_one_on_one_chat_has_no_title_and_counts_up() {
2445 let people = vec![(LEA_ID.to_owned(), "Lea Schneider".to_owned())];
2446 let (first, _) = new_chat(&[], &people, None, "Hi", "Hi", Utc::now());
2447 assert_eq!(first.kind, "oneOnOne");
2448 assert!(first.title.is_empty());
2449 let (second, _) = new_chat(&[first], &people, None, "Hi again", "Hi again", Utc::now());
2450 assert_eq!(second.id, "demo-chat-new-2");
2451 }
2452
2453 #[test]
2454 fn sending_into_a_chat_refreshes_its_preview() {
2455 let base = ChatRecord {
2456 id: "demo-chat-x".to_owned(),
2457 unread: true,
2458 ..Default::default()
2459 };
2460 let (chat, record) = send_in_chat(&base, "Ping", "Ping", Utc::now());
2461 assert!(!chat.unread);
2462 assert_eq!(chat.last_message_preview.as_deref(), Some("Ping"));
2463 assert_eq!(record.conversation_id, "demo-chat-x");
2464 }
2465
2466 #[test]
2467 fn demo_covers_the_sidebar_edge_cases() {
2468 let chats = demo_chats();
2469 assert!(chats.iter().any(|chat| chat.deleted));
2470 assert!(chats.iter().any(|chat| chat.title.len() > 40));
2471 assert!(chats.iter().filter(|chat| chat.unread).count() >= 3);
2472 }
2473}