BlueGit

ict rusty-teams

Files

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

demo.rs

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