BlueGit

ict rusty-teams

Files

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

demo.rs

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