BlueGit

ict rusty-teams

Files

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

demo.rs

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