BlueGit

ict rusty-teams

Files

rusty-teams / crates / store / tests / store.rs

store.rs

store.rs 49.1 KiB Download Raw
1use chrono::{DateTime, TimeZone, Utc};
2use rusqlite::Connection;
3use store::{
4 AvatarRecord, ChannelLayoutRecord, ChannelNotificationLevel, ChannelNotifications,
5 ChannelRecord, ChannelTabRecord, ChatPreview, ChatRecord, FolderRecord, MemberRecord,
6 MessageRecord, RecentScope, Store, SyncState, TeamLayoutRecord, TeamRecord,
7};
8
9#[test]
10fn a_system_event_keeps_the_previous_unread_state() {
11 let store = Store::open_in_memory().unwrap();
12 for (previous, expected) in [(true, true), (false, false)] {
13 let id = format!("chat-{previous}");
14 let mut seeded = chat(&id, "Planning", Some(at(5)));
15 seeded.unread = previous;
16 store.upsert_chats(&[seeded]).unwrap();
17
18 let mut event = chat(&id, "Planning", Some(at(12)));
19 event.unread = false;
20 event.last_event_system = true;
21 store.upsert_chats(&[event]).unwrap();
22 assert_eq!(store.chat(&id).unwrap().unwrap().unread, expected);
23 }
24}
25
26#[test]
27fn a_call_event_keeps_the_previous_preview() {
28 let store = Store::open_in_memory().unwrap();
29 let mut seeded = chat("chat-call", "Planning", Some(at(5)));
30 seeded.last_message_preview = Some("See you there".to_owned());
31 seeded.last_message_sender_id = Some("user-ada".to_owned());
32 seeded.last_message_sender_name = Some("Ada Example".to_owned());
33 store.upsert_chats(&[seeded]).unwrap();
34
35 let mut call = chat("chat-call", "Planning", Some(at(12)));
36 call.last_event_system = true;
37 call.last_event_call = true;
38 store.upsert_chats(&[call]).unwrap();
39 let stored = store.chat("chat-call").unwrap().unwrap();
40 assert_eq!(
41 stored.last_message_preview.as_deref(),
42 Some("See you there")
43 );
44 assert_eq!(
45 stored.last_message_sender_name.as_deref(),
46 Some("Ada Example")
47 );
48 assert_eq!(stored.last_message_at, Some(at(12)));
49
50 let mut recording = chat("chat-call", "Planning", Some(at(14)));
51 recording.last_event_system = true;
52 recording.last_message_preview = Some("Recording is ready".to_owned());
53 store.upsert_chats(&[recording]).unwrap();
54 let stored = store.chat("chat-call").unwrap().unwrap();
55 assert_eq!(
56 stored.last_message_preview.as_deref(),
57 Some("Recording is ready")
58 );
59 assert_eq!(stored.last_message_sender_name, None);
60}
61
62fn at(minute: u32) -> DateTime<Utc> {
63 Utc.with_ymd_and_hms(2026, 10, 6, 9, minute, 0).unwrap()
64}
65
66fn chat(id: &str, title: &str, last: Option<DateTime<Utc>>) -> ChatRecord {
67 ChatRecord {
68 id: id.to_owned(),
69 kind: "group".to_owned(),
70 title: title.to_owned(),
71 member_summary: "Ada Example, Bob Sample".to_owned(),
72 last_message_at: last,
73 last_read_at: Some(at(0)),
74 unread: true,
75 members: vec![
76 MemberRecord {
77 user_id: Some("user-ada".to_owned()),
78 display_name: "Ada Example".to_owned(),
79 },
80 MemberRecord {
81 user_id: None,
82 display_name: "Bob Sample".to_owned(),
83 },
84 ],
85 ..ChatRecord::default()
86 }
87}
88
89fn message(conversation_id: &str, message_id: &str, minute: u32) -> MessageRecord {
90 MessageRecord {
91 conversation_id: conversation_id.to_owned(),
92 message_id: message_id.to_owned(),
93 reply_to_id: None,
94 sender_id: Some("user-ada".to_owned()),
95 sender_name: Some("Ada Example".to_owned()),
96 created_at: at(minute),
97 edited_at: None,
98 deleted: false,
99 body_html: format!("<p>message {message_id}</p>"),
100 attachments_json: "[]".to_owned(),
101 reactions_json: "[]".to_owned(),
102 mentions_json: "[]".to_owned(),
103 sender_application_id: None,
104 links_json: "[]".to_owned(),
105 subject: None,
106 call_event_json: None,
107 }
108}
109
110#[test]
111fn subject_round_trips_and_survives_an_upsert_without_one() {
112 let store = Store::open_in_memory().unwrap();
113 let post = MessageRecord {
114 subject: Some("Release plan".to_owned()),
115 ..message("c1", "m1", 1)
116 };
117 store.upsert_messages(std::slice::from_ref(&post)).unwrap();
118 let found = store.messages_by_id("c1", &["m1".to_owned()]).unwrap();
119 assert_eq!(found["m1"], post);
120
121 store.upsert_messages(&[message("c1", "m1", 1)]).unwrap();
122 let found = store.messages_by_id("c1", &["m1".to_owned()]).unwrap();
123 assert_eq!(found["m1"].subject.as_deref(), Some("Release plan"));
124}
125
126#[test]
127fn thread_messages_return_root_and_replies_oldest_first_beyond_any_page() {
128 let store = Store::open_in_memory().unwrap();
129 let reply = |id: &str, minute: u32, root: &str| MessageRecord {
130 reply_to_id: Some(root.to_owned()),
131 ..message("c1", id, minute)
132 };
133 store
134 .upsert_messages(&[
135 reply("r2", 30, "root"),
136 message("c1", "root", 1),
137 message("c1", "other", 2),
138 reply("r1", 10, "root"),
139 reply("o1", 11, "other"),
140 ])
141 .unwrap();
142 let thread = store.thread_messages("c1", "root").unwrap();
143 assert_eq!(ids(&thread), ["root", "r1", "r2"]);
144}
145
146#[test]
147fn sender_application_round_trips() {
148 let store = Store::open_in_memory().unwrap();
149 let bot_message = MessageRecord {
150 sender_application_id: Some("bot-guid".to_owned()),
151 ..message("c1", "m1", 1)
152 };
153 store
154 .upsert_messages(std::slice::from_ref(&bot_message))
155 .unwrap();
156 let found = store.messages_by_id("c1", &["m1".to_owned()]).unwrap();
157 assert_eq!(found["m1"], bot_message);
158}
159
160#[test]
161fn an_upsert_without_links_keeps_the_stored_links() {
162 let store = Store::open_in_memory().unwrap();
163 store.upsert_messages(&[message("c1", "m1", 1)]).unwrap();
164 let links = r#"[{"url":"https://a.example"}]"#;
165 assert!(store.set_message_links("c1", "m1", links).unwrap());
166 assert!(!store.set_message_links("c1", "m1", links).unwrap());
167
168 let edited = MessageRecord {
169 body_html: "<p>edited</p>".to_owned(),
170 ..message("c1", "m1", 1)
171 };
172 store.upsert_messages(&[edited]).unwrap();
173 let found = store.messages_by_id("c1", &["m1".to_owned()]).unwrap();
174 assert_eq!(found["m1"].links_json, links);
175 assert_eq!(found["m1"].body_html, "<p>edited</p>");
176
177 let replaced = MessageRecord {
178 links_json: r#"[{"url":"https://b.example"}]"#.to_owned(),
179 ..message("c1", "m1", 1)
180 };
181 store
182 .upsert_messages(std::slice::from_ref(&replaced))
183 .unwrap();
184 let found = store.messages_by_id("c1", &["m1".to_owned()]).unwrap();
185 assert_eq!(found["m1"].links_json, replaced.links_json);
186}
187
188#[test]
189fn new_messages_start_without_links() {
190 let store = Store::open_in_memory().unwrap();
191 store.upsert_messages(&[message("c1", "m1", 1)]).unwrap();
192 let found = store.messages_by_id("c1", &["m1".to_owned()]).unwrap();
193 assert_eq!(found["m1"].links_json, "[]");
194}
195
196fn ids(messages: &[MessageRecord]) -> Vec<&str> {
197 messages
198 .iter()
199 .map(|message| message.message_id.as_str())
200 .collect()
201}
202
203#[test]
204fn chats_round_trip_with_members() {
205 let store = Store::open_in_memory().unwrap();
206 let original = chat("chat-1", "Planning", Some(at(5)));
207 store.upsert_chats(std::slice::from_ref(&original)).unwrap();
208 assert_eq!(store.chat("chat-1").unwrap(), Some(original));
209 assert_eq!(store.chat("missing").unwrap(), None);
210}
211
212#[test]
213fn chat_upsert_replaces_fields_and_members() {
214 let store = Store::open_in_memory().unwrap();
215 store
216 .upsert_chats(&[chat("chat-1", "Old", Some(at(1)))])
217 .unwrap();
218 let mut changed = chat("chat-1", "New", Some(at(9)));
219 changed.members.truncate(1);
220 changed.unread = false;
221 store.upsert_chats(&[changed.clone()]).unwrap();
222 assert_eq!(store.recent_chats(10).unwrap(), vec![changed]);
223}
224
225#[test]
226fn chat_upsert_keeps_a_real_title_over_the_only_you_fallback() {
227 let store = Store::open_in_memory().unwrap();
228 store
229 .upsert_chats(&[chat("chat-1", "Sample Bot", Some(at(1)))])
230 .unwrap();
231 store
232 .upsert_chats(&[chat("chat-1", "(only you)", Some(at(2)))])
233 .unwrap();
234 assert_eq!(store.chat("chat-1").unwrap().unwrap().title, "Sample Bot");
235 store
236 .upsert_chats(&[chat("chat-2", "(only you)", Some(at(2)))])
237 .unwrap();
238 store
239 .upsert_chats(&[chat("chat-2", "Sample Bot", Some(at(3)))])
240 .unwrap();
241 assert_eq!(store.chat("chat-2").unwrap().unwrap().title, "Sample Bot");
242}
243
244#[test]
245fn recent_chats_are_newest_first_with_unknown_last() {
246 let store = Store::open_in_memory().unwrap();
247 store
248 .upsert_chats(&[
249 chat("old", "Old", Some(at(1))),
250 chat("none", "None", None),
251 chat("new", "New", Some(at(30))),
252 chat("mid", "Mid", Some(at(10))),
253 ])
254 .unwrap();
255 let recent = store.recent_chats(3).unwrap();
256 let order: Vec<&str> = recent.iter().map(|chat| chat.id.as_str()).collect();
257 assert_eq!(order, ["new", "mid", "old"]);
258 assert_eq!(store.recent_chats(10).unwrap().last().unwrap().id, "none");
259}
260
261#[test]
262fn messages_page_backwards_oldest_first() {
263 let store = Store::open_in_memory().unwrap();
264 let all: Vec<MessageRecord> = (1..=10)
265 .map(|minute| message("chat-1", &format!("m{minute:02}"), minute))
266 .collect();
267 store.upsert_messages(&all).unwrap();
268 store
269 .upsert_messages(&[message("chat-2", "other", 5)])
270 .unwrap();
271
272 let newest = store.messages("chat-1", None, 4).unwrap();
273 assert_eq!(ids(&newest), ["m07", "m08", "m09", "m10"]);
274
275 let older = store
276 .messages("chat-1", Some(newest[0].created_at), 4)
277 .unwrap();
278 assert_eq!(ids(&older), ["m03", "m04", "m05", "m06"]);
279
280 let oldest = store
281 .messages("chat-1", Some(older[0].created_at), 4)
282 .unwrap();
283 assert_eq!(ids(&oldest), ["m01", "m02"]);
284 assert!(
285 store
286 .messages("chat-1", Some(oldest[0].created_at), 4)
287 .unwrap()
288 .is_empty()
289 );
290 assert_eq!(store.message_count("chat-1").unwrap(), 10);
291}
292
293#[test]
294fn equal_timestamps_keep_a_stable_order() {
295 let store = Store::open_in_memory().unwrap();
296 store
297 .upsert_messages(&[
298 message("c", "b", 1),
299 message("c", "a", 1),
300 message("c", "c", 1),
301 ])
302 .unwrap();
303 assert_eq!(
304 ids(&store.messages("c", None, 10).unwrap()),
305 ["a", "b", "c"]
306 );
307}
308
309#[test]
310fn message_upsert_updates_in_place() {
311 let store = Store::open_in_memory().unwrap();
312 let mut edited = message("c", "m1", 1);
313 store
314 .upsert_messages(std::slice::from_ref(&edited))
315 .unwrap();
316 edited.body_html = "<p>edited</p>".to_owned();
317 edited.edited_at = Some(at(2));
318 edited.reactions_json = r#"[{"type":"like"}]"#.to_owned();
319 store
320 .upsert_messages(std::slice::from_ref(&edited))
321 .unwrap();
322
323 let stored = store.messages("c", None, 10).unwrap();
324 assert_eq!(stored, vec![edited.clone()]);
325 let by_id = store
326 .messages_by_id("c", &["m1".to_owned(), "nope".to_owned()])
327 .unwrap();
328 assert_eq!(by_id.len(), 1);
329 assert_eq!(by_id["m1"], edited);
330}
331
332#[test]
333fn deleted_flag_and_json_columns_round_trip() {
334 let store = Store::open_in_memory().unwrap();
335 let mut record = message("c", "m1", 1);
336 record.deleted = true;
337 record.reply_to_id = Some("m0".to_owned());
338 record.attachments_json = r#"[{"name":"a.pdf"}]"#.to_owned();
339 record.mentions_json = r#"[{"id":"u1","name":"Ada Example"}]"#.to_owned();
340 store
341 .upsert_messages(std::slice::from_ref(&record))
342 .unwrap();
343 assert_eq!(store.messages("c", None, 1).unwrap(), vec![record]);
344}
345
346#[test]
347fn thread_has_sender_checks_root_and_replies() {
348 let store = Store::open_in_memory().unwrap();
349 let mut reply = message("c", "r1", 2);
350 reply.reply_to_id = Some("root".to_owned());
351 reply.sender_id = Some("user-bob".to_owned());
352 let mut other_reply = message("c", "r2", 3);
353 other_reply.reply_to_id = Some("other".to_owned());
354 other_reply.sender_id = Some("user-carl".to_owned());
355 store
356 .upsert_messages(&[message("c", "root", 1), reply, other_reply])
357 .unwrap();
358 assert!(store.thread_has_sender("c", "root", "user-ada").unwrap());
359 assert!(store.thread_has_sender("c", "root", "user-bob").unwrap());
360 assert!(!store.thread_has_sender("c", "root", "user-carl").unwrap());
361 assert!(!store.thread_has_sender("d", "root", "user-ada").unwrap());
362}
363
364#[test]
365fn sync_state_round_trip() {
366 let store = Store::open_in_memory().unwrap();
367 assert_eq!(store.sync_state("c").unwrap(), None);
368 let state = SyncState {
369 newest_seen: Some(at(9)),
370 oldest_loaded: Some(at(1)),
371 has_more: false,
372 older_cursor: Some("https://graph.microsoft.com/v1.0/next".to_owned()),
373 delta_link: Some("https://graph.microsoft.com/v1.0/delta".to_owned()),
374 };
375 store.set_sync_state("c", &state).unwrap();
376 assert_eq!(store.sync_state("c").unwrap(), Some(state));
377 let reset = SyncState {
378 has_more: true,
379 ..SyncState::default()
380 };
381 store.set_sync_state("c", &reset).unwrap();
382 assert_eq!(store.sync_state("c").unwrap(), Some(reset));
383}
384
385#[test]
386fn sidebar_groups_channels_under_teams() {
387 let store = Store::open_in_memory().unwrap();
388 store
389 .upsert_chats(&[chat("chat-1", "Planning", Some(at(5)))])
390 .unwrap();
391 store
392 .upsert_teams(&[
393 TeamRecord {
394 id: "t2".to_owned(),
395 name: "beta".to_owned(),
396 },
397 TeamRecord {
398 id: "t1".to_owned(),
399 name: "Alpha".to_owned(),
400 },
401 ])
402 .unwrap();
403 let channel = |id: &str, team_id: &str, name: &str| ChannelRecord {
404 id: id.to_owned(),
405 team_id: team_id.to_owned(),
406 name: name.to_owned(),
407 membership_type: Some("standard".to_owned()),
408 last_message_at: None,
409 unread: false,
410 };
411 store
412 .upsert_channels(&[
413 channel("c2", "t1", "Random"),
414 channel("c1", "t1", "General"),
415 channel("c3", "t2", "General"),
416 ])
417 .unwrap();
418
419 let sidebar = store.sidebar().unwrap();
420 assert_eq!(sidebar.chats.len(), 1);
421 let team_names: Vec<&str> = sidebar
422 .teams
423 .iter()
424 .map(|entry| entry.team.name.as_str())
425 .collect();
426 assert_eq!(team_names, ["Alpha", "beta"]);
427 let alpha_channels: Vec<&str> = sidebar.teams[0]
428 .channels
429 .iter()
430 .map(|entry| entry.name.as_str())
431 .collect();
432 assert_eq!(alpha_channels, ["General", "Random"]);
433 assert_eq!(store.channel("c3").unwrap().unwrap().team_id, "t2");
434}
435
436#[test]
437fn channel_upsert_keeps_known_last_message_time() {
438 let store = Store::open_in_memory().unwrap();
439 store
440 .upsert_teams(&[TeamRecord {
441 id: "t1".to_owned(),
442 name: "A".to_owned(),
443 }])
444 .unwrap();
445 let mut channel = ChannelRecord {
446 id: "c1".to_owned(),
447 team_id: "t1".to_owned(),
448 name: "General".to_owned(),
449 membership_type: None,
450 last_message_at: Some(at(7)),
451 unread: false,
452 };
453 store
454 .upsert_channels(std::slice::from_ref(&channel))
455 .unwrap();
456 channel.last_message_at = None;
457 store
458 .upsert_channels(std::slice::from_ref(&channel))
459 .unwrap();
460 assert_eq!(
461 store.channel("c1").unwrap().unwrap().last_message_at,
462 Some(at(7))
463 );
464}
465
466#[test]
467fn channel_read_state_survives_a_metadata_refresh() {
468 let store = Store::open_in_memory().unwrap();
469 store
470 .upsert_teams(&[TeamRecord {
471 id: "t1".to_owned(),
472 name: "A".to_owned(),
473 }])
474 .unwrap();
475 let channel = ChannelRecord {
476 id: "c1".to_owned(),
477 team_id: "t1".to_owned(),
478 name: "General".to_owned(),
479 membership_type: None,
480 last_message_at: None,
481 unread: false,
482 };
483 store
484 .upsert_channels(std::slice::from_ref(&channel))
485 .unwrap();
486 store
487 .apply_channel_read_states(&[
488 ("c1".to_owned(), true, Some(at(9))),
489 ("unknown".to_owned(), true, None),
490 ])
491 .unwrap();
492 store
493 .upsert_channels(std::slice::from_ref(&channel))
494 .unwrap();
495 let stored = store.channel("c1").unwrap().unwrap();
496 assert!(stored.unread);
497 assert_eq!(stored.last_message_at, Some(at(9)));
498 assert!(store.channel("unknown").unwrap().is_none());
499
500 store.mark_channel_read("c1").unwrap();
501 assert!(!store.channel("c1").unwrap().unwrap().unread);
502}
503
504#[test]
505fn pruning_removes_departed_teams_and_channels() {
506 let store = Store::open_in_memory().unwrap();
507 store
508 .upsert_teams(&[
509 TeamRecord {
510 id: "t1".to_owned(),
511 name: "A".to_owned(),
512 },
513 TeamRecord {
514 id: "t2".to_owned(),
515 name: "B".to_owned(),
516 },
517 ])
518 .unwrap();
519 let channel = |id: &str| ChannelRecord {
520 id: id.to_owned(),
521 team_id: "t1".to_owned(),
522 name: id.to_owned(),
523 membership_type: None,
524 last_message_at: None,
525 unread: false,
526 };
527 store
528 .upsert_channels(&[channel("c1"), channel("c2")])
529 .unwrap();
530 assert_eq!(
531 store
532 .remove_channels_except("t1", &["c1".to_owned()])
533 .unwrap(),
534 1
535 );
536 assert_eq!(store.remove_teams_except(&["t1".to_owned()]).unwrap(), 1);
537 let sidebar = store.sidebar().unwrap();
538 assert_eq!(sidebar.teams.len(), 1);
539 assert_eq!(sidebar.teams[0].channels.len(), 1);
540}
541
542#[test]
543fn file_database_uses_wal_persists_and_migrates_once() {
544 let directory = tempfile::tempdir().unwrap();
545 let path = directory.path().join("nested").join("cache.sqlite3");
546 {
547 let store = Store::open(&path).unwrap();
548 assert_eq!(store.schema_version().unwrap(), 21);
549 store.upsert_messages(&[message("c", "m1", 1)]).unwrap();
550 }
551 let reopened = Store::open(&path).unwrap();
552 assert_eq!(reopened.schema_version().unwrap(), 21);
553 assert_eq!(reopened.message_count("c").unwrap(), 1);
554 drop(reopened);
555 let mode: String = rusqlite_open(&path)
556 .pragma_query_value(None, "journal_mode", |row| row.get(0))
557 .unwrap();
558 assert_eq!(mode, "wal");
559}
560
561#[test]
562fn newer_schema_is_refused() {
563 let directory = tempfile::tempdir().unwrap();
564 let path = directory.path().join("cache.sqlite3");
565 drop(Store::open(&path).unwrap());
566 let connection = rusqlite_open(&path);
567 connection
568 .execute_batch("PRAGMA user_version = 99")
569 .unwrap();
570 drop(connection);
571 let error = Store::open(&path).err().expect("must refuse");
572 assert!(error.to_string().contains("99"), "{error}");
573}
574
575#[test]
576fn old_schema_is_upgraded_in_place() {
577 let directory = tempfile::tempdir().unwrap();
578 let path = directory.path().join("cache.sqlite3");
579 drop(Store::open(&path).unwrap());
580 let connection = rusqlite_open(&path);
581 connection.execute_batch("DROP TABLE messages; DROP TABLE sync_state; DROP TABLE chats; DROP TABLE chat_members; DROP TABLE channels; DROP TABLE teams; DROP TABLE meta; DROP TABLE avatars; DROP TABLE folder_items; DROP TABLE folders; DROP TABLE pinned_channels; DROP TABLE images; DROP TABLE search_keys; DROP TABLE message_search; DROP TABLE title_search; DROP TABLE team_layout; DROP TABLE channel_layout; DROP TABLE channel_tabs; DROP TABLE presence; DROP TABLE activity; DROP TABLE outbox; DROP TABLE drafts; DROP TABLE attachment_images; DROP TABLE agent_reaction_proposals; DROP TABLE agent_proposals; PRAGMA user_version = 0").unwrap();
582 drop(connection);
583 let store = Store::open(&path).unwrap();
584 assert_eq!(store.schema_version().unwrap(), 21);
585 store.upsert_messages(&[message("c", "m1", 1)]).unwrap();
586}
587
588fn rusqlite_open(path: &std::path::Path) -> Connection {
589 Connection::open(path).unwrap()
590}
591
592#[test]
593fn meta_values_and_times_round_trip() {
594 let store = Store::open_in_memory().unwrap();
595 assert_eq!(store.meta("k").unwrap(), None);
596 store.set_meta("k", "one").unwrap();
597 store.set_meta("k", "two").unwrap();
598 assert_eq!(store.meta("k").unwrap().as_deref(), Some("two"));
599 assert_eq!(store.meta_time("t").unwrap(), None);
600 store.set_meta_time("t", at(7)).unwrap();
601 assert_eq!(store.meta_time("t").unwrap(), Some(at(7)));
602 store.set_meta("bad", "not a number").unwrap();
603 assert_eq!(store.meta_time("bad").unwrap(), None);
604}
605
606#[test]
607fn chats_can_be_pruned_and_marked_read() {
608 let store = Store::open_in_memory().unwrap();
609 store
610 .upsert_chats(&[
611 chat("a", "A", Some(at(1))),
612 chat("b", "B", Some(at(2))),
613 chat("c", "C", None),
614 ])
615 .unwrap();
616 let times = store
617 .chat_last_message_times(&["a".to_owned(), "c".to_owned(), "zzz".to_owned()])
618 .unwrap();
619 assert_eq!(times.len(), 2);
620 assert_eq!(times["a"], Some(at(1)));
621 assert_eq!(times["c"], None);
622
623 assert_eq!(store.remove_chats(&["a".to_owned()]).unwrap(), 1);
624 assert_eq!(store.remove_chats_except(&["b".to_owned()]).unwrap(), 1);
625 assert_eq!(store.chat_count().unwrap(), 1);
626
627 store.mark_chat_read("b", at(30)).unwrap();
628 let read = store.chat("b").unwrap().unwrap();
629 assert!(!read.unread);
630 assert_eq!(read.last_read_at, Some(at(30)));
631}
632
633#[test]
634fn migration_to_v2_keeps_existing_sync_state() {
635 let directory = tempfile::tempdir().unwrap();
636 let path = directory.path().join("old.sqlite3");
637 {
638 let connection = Connection::open(&path).unwrap();
639 connection
640 .execute_batch(include_str!("../src/migrations/0001_initial.sql"))
641 .unwrap();
642 connection.pragma_update(None, "user_version", 1).unwrap();
643 connection
644 .execute("INSERT INTO sync_state (conversation_id, newest_seen, has_more) VALUES ('c', 5, 1)", [])
645 .unwrap();
646 }
647 let store = Store::open(&path).unwrap();
648 let state = store.sync_state("c").unwrap().unwrap();
649 assert_eq!(state.delta_link, None);
650 assert_eq!(store.schema_version().unwrap(), 21);
651}
652
653#[test]
654fn migration_to_v13_clears_channel_delta_links_only() {
655 let directory = tempfile::tempdir().unwrap();
656 let path = directory.path().join("old.sqlite3");
657 {
658 let store = Store::open(&path).unwrap();
659 drop(store);
660 let connection = Connection::open(&path).unwrap();
661 connection
662 .execute_batch(
663 "INSERT INTO teams (id, name) VALUES ('t', 'T');
664 INSERT INTO channels (id, team_id, name) VALUES ('ch', 't', 'C');
665 INSERT INTO sync_state (conversation_id, delta_link) VALUES ('ch', 'link'), ('chat', 'link');
666 ALTER TABLE messages DROP COLUMN subject;
667 ALTER TABLE messages DROP COLUMN call_event_json;
668 ALTER TABLE folders DROP COLUMN expanded;
669 DROP TABLE channel_tabs;
670 DROP TABLE agent_reaction_proposals; DROP TABLE agent_proposals;
671 ALTER TABLE channel_layout DROP COLUMN notification_level;
672 ALTER TABLE channel_layout DROP COLUMN include_replies;
673 PRAGMA user_version = 12",
674 )
675 .unwrap();
676 }
677 let store = Store::open(&path).unwrap();
678 assert_eq!(
679 store.sync_state("ch").unwrap().and_then(|state| state.delta_link),
680 None
681 );
682 assert_eq!(
683 store
684 .sync_state("chat")
685 .unwrap()
686 .unwrap()
687 .delta_link
688 .as_deref(),
689 Some("link")
690 );
691}
692
693#[test]
694fn preview_updates_only_for_newer_messages() {
695 let store = Store::open_in_memory().unwrap();
696 store.upsert_chats(&[chat("a", "A", Some(at(5)))]).unwrap();
697 let preview = |text| ChatPreview {
698 text: Some(text),
699 sender_id: Some("user-ada"),
700 sender_name: Some("Ada Example"),
701 deleted: false,
702 };
703 assert!(
704 !store
705 .update_chat_preview("a", at(4), &preview("older"))
706 .unwrap()
707 );
708 assert!(
709 store
710 .update_chat_preview("a", at(6), &preview("newer"))
711 .unwrap()
712 );
713 let record = store.chat("a").unwrap().unwrap();
714 assert_eq!(record.last_message_preview.as_deref(), Some("newer"));
715 assert_eq!(
716 record.last_message_sender_name.as_deref(),
717 Some("Ada Example")
718 );
719 assert_eq!(record.last_message_at, Some(at(6)));
720 assert!(!record.last_message_deleted);
721}
722
723#[test]
724fn avatars_round_trip_and_report_stale_ids() {
725 let store = Store::open_in_memory().unwrap();
726 store
727 .upsert_avatar(&AvatarRecord {
728 user_id: "fresh".into(),
729 bytes: Some(vec![1, 2, 3]),
730 content_type: "image/jpeg".into(),
731 fetched_at: at(50),
732 })
733 .unwrap();
734 store
735 .upsert_avatar(&AvatarRecord {
736 user_id: "missing".into(),
737 bytes: None,
738 content_type: String::new(),
739 fetched_at: at(1),
740 })
741 .unwrap();
742 assert_eq!(
743 store.avatar("fresh").unwrap().unwrap().bytes,
744 Some(vec![1, 2, 3])
745 );
746 assert_eq!(store.avatar("missing").unwrap().unwrap().bytes, None);
747 assert!(store.avatar("unknown").unwrap().is_none());
748 let ids: Vec<String> = ["fresh", "missing", "unknown"].map(String::from).to_vec();
749 assert_eq!(
750 store.avatar_ids_needing_fetch(&ids, at(10)).unwrap(),
751 ["missing", "unknown"]
752 );
753}
754
755#[test]
756fn folders_and_pinned_channels_are_replaced_in_order() {
757 let store = Store::open_in_memory().unwrap();
758 let folder = |id: &str, kind: &str, items: &[&str]| FolderRecord {
759 id: id.into(),
760 name: id.into(),
761 kind: kind.into(),
762 expanded: kind != "MutedChats",
763 conversation_ids: items.iter().map(|item| item.to_string()).collect(),
764 };
765 let first = [
766 folder("f1", "Favorites", &["b", "a"]),
767 folder("f2", "UserCreated", &[]),
768 folder("f4", "MutedChats", &[]),
769 ];
770 store
771 .replace_folders(&first, &["c2".into(), "c1".into()])
772 .unwrap();
773 assert_eq!(store.folders().unwrap(), first);
774 assert_eq!(store.pinned_channel_ids().unwrap(), ["c2", "c1"]);
775 store.set_folder_expanded("f2", false).unwrap();
776 assert!(!store.folders().unwrap()[1].expanded);
777 store
778 .replace_folders(&[folder("f3", "UserCreated", &["z"])], &[])
779 .unwrap();
780 assert_eq!(store.folders().unwrap().len(), 1);
781 assert!(store.pinned_channel_ids().unwrap().is_empty());
782}
783
784#[test]
785fn counts_messages_after_a_time_from_others() {
786 let store = Store::open_in_memory().unwrap();
787 let mut mine = message("c", "m3", 3);
788 mine.sender_id = Some("me".into());
789 store
790 .upsert_messages(&[message("c", "m1", 1), message("c", "m2", 2), mine])
791 .unwrap();
792 assert_eq!(
793 store.count_messages_after("c", Some(at(1)), "me").unwrap(),
794 1
795 );
796 assert_eq!(store.count_messages_after("c", None, "me").unwrap(), 2);
797}
798
799#[test]
800fn messages_between_is_inclusive_and_oldest_first() {
801 let store = Store::open_in_memory().unwrap();
802 store
803 .upsert_messages(&[
804 message("c", "m4", 4),
805 message("c", "m1", 1),
806 message("c", "m3", 3),
807 message("c", "m2", 2),
808 message("other", "o3", 3),
809 ])
810 .unwrap();
811 let ids: Vec<String> = store
812 .messages_between("c", at(2), at(3))
813 .unwrap()
814 .into_iter()
815 .map(|record| record.message_id)
816 .collect();
817 assert_eq!(ids, ["m2", "m3"]);
818}
819
820fn html_message(
821 conversation_id: &str,
822 message_id: &str,
823 minute: u32,
824 sender: &str,
825 html: &str,
826) -> MessageRecord {
827 MessageRecord {
828 sender_name: Some(sender.to_owned()),
829 body_html: html.to_owned(),
830 ..message(conversation_id, message_id, minute)
831 }
832}
833
834#[test]
835fn fts5_is_available_and_matches_prefixes_with_highlights() {
836 let store = Store::open_in_memory().unwrap();
837 store
838 .upsert_messages(&[
839 html_message(
840 "c1",
841 "m1",
842 1,
843 "Ada Example",
844 "<p>The <b>budget</b> planning is done</p>",
845 ),
846 html_message("c1", "m2", 2, "Bob Sample", "<p>Lunch at noon</p>"),
847 html_message("c2", "m3", 3, "Bob Sample", "<p>Budget approved</p>"),
848 ])
849 .unwrap();
850 let hits = store.search_messages("budg plan", None, 10).unwrap();
851 assert_eq!(hits.len(), 1);
852 assert_eq!(hits[0].message_id, "m1");
853 assert_eq!(hits[0].sender_name.as_deref(), Some("Ada Example"));
854 assert_eq!(hits[0].created_at, at(1));
855 assert!(
856 hits[0].snippet.contains("\u{1}budget\u{2}"),
857 "{}",
858 hits[0].snippet
859 );
860 let all = store.search_messages("budget", None, 10).unwrap();
861 assert_eq!(ids_of(&all), ["m3", "m1"]);
862 let scoped = store.search_messages("budget", Some("c1"), 10).unwrap();
863 assert_eq!(ids_of(&scoped), ["m1"]);
864 assert_eq!(store.search_messages("budget", None, 1).unwrap().len(), 1);
865}
866
867fn ids_of(hits: &[store::SearchHit]) -> Vec<&str> {
868 hits.iter().map(|hit| hit.message_id.as_str()).collect()
869}
870
871#[test]
872fn search_filters_by_sender_and_ignores_unsearchable_input() {
873 let store = Store::open_in_memory().unwrap();
874 store
875 .upsert_messages(&[
876 html_message("c1", "m1", 1, "Ada Example", "<p>report</p>"),
877 html_message("c1", "m2", 2, "Bob Sample", "<p>report</p>"),
878 ])
879 .unwrap();
880 assert_eq!(
881 ids_of(&store.search_messages("from:bob report", None, 10).unwrap()),
882 ["m2"]
883 );
884 assert!(store.search_messages(" ", None, 10).unwrap().is_empty());
885 assert!(store.search_messages("\"-*", None, 10).unwrap().is_empty());
886 assert!(store.search_messages("rep) OR (", None, 10).is_ok());
887}
888
889#[test]
890fn search_follows_edits_and_deletes() {
891 let store = Store::open_in_memory().unwrap();
892 store
893 .upsert_messages(&[html_message("c1", "m1", 1, "Ada", "<p>alpha</p>")])
894 .unwrap();
895 store
896 .upsert_messages(&[html_message("c1", "m1", 1, "Ada", "<p>beta</p>")])
897 .unwrap();
898 assert!(store.search_messages("alpha", None, 10).unwrap().is_empty());
899 assert_eq!(store.search_messages("beta", None, 10).unwrap().len(), 1);
900 let mut deleted = html_message("c1", "m1", 1, "Ada", "");
901 deleted.deleted = true;
902 store.upsert_messages(&[deleted]).unwrap();
903 assert!(store.search_messages("beta", None, 10).unwrap().is_empty());
904}
905
906#[test]
907fn title_search_follows_chat_renames() {
908 let store = Store::open_in_memory().unwrap();
909 store
910 .upsert_chats(&[chat("c1", "Budget planning", None)])
911 .unwrap();
912 assert_eq!(
913 store.search_conversations("budg", 10).unwrap()[0].conversation_id,
914 "c1"
915 );
916 store.upsert_chats(&[chat("c1", "Holiday", None)]).unwrap();
917 assert!(store.search_conversations("budget", 10).unwrap().is_empty());
918 assert_eq!(store.search_conversations("holi", 10).unwrap().len(), 1);
919 assert!(
920 store
921 .search_conversations("from:holi", 10)
922 .unwrap()
923 .is_empty()
924 );
925}
926
927#[test]
928fn migration_indexes_rows_that_predate_search() {
929 let directory = tempfile::tempdir().unwrap();
930 let path = directory.path().join("cache.sqlite3");
931 {
932 let store = Store::open(&path).unwrap();
933 store.upsert_chats(&[chat("c1", "Old chat", None)]).unwrap();
934 store
935 .upsert_messages(&[html_message("c1", "m1", 1, "Ada", "<p>legacy text</p>")])
936 .unwrap();
937 }
938 {
939 let connection = Connection::open(&path).unwrap();
940 connection
941 .execute_batch(
942 "DROP TRIGGER chats_title_insert; DROP TRIGGER chats_title_update; DROP TRIGGER chats_title_delete;
943 DROP TRIGGER channels_title_insert; DROP TRIGGER channels_title_update; DROP TRIGGER channels_title_delete;
944 DROP TABLE images; DROP TABLE search_keys; DROP TABLE message_search; DROP TABLE title_search;
945 DROP TABLE team_layout; DROP TABLE channel_layout; DROP TABLE channel_tabs; DROP TABLE presence; DROP TABLE activity; DROP TABLE outbox; DROP TABLE drafts; DROP TABLE attachment_images; DROP TABLE agent_reaction_proposals; DROP TABLE agent_proposals;
946 DROP INDEX messages_by_sender; DROP INDEX chat_members_by_user;
947 ALTER TABLE messages DROP COLUMN sender_application_id;
948 ALTER TABLE messages DROP COLUMN links_json;
949 ALTER TABLE messages DROP COLUMN subject;
950 ALTER TABLE messages DROP COLUMN call_event_json;
951 ALTER TABLE chats DROP COLUMN muted;
952 ALTER TABLE folders DROP COLUMN expanded;
953 PRAGMA user_version = 3;",
954 )
955 .unwrap();
956 }
957 let store = Store::open(&path).unwrap();
958 assert_eq!(store.search_messages("legacy", None, 10).unwrap().len(), 1);
959 assert_eq!(store.search_conversations("old", 10).unwrap().len(), 1);
960}
961
962fn image(key: &str, minute: u32, size: usize) -> store::ImageRecord {
963 store::ImageRecord {
964 key: key.to_owned(),
965 bytes: vec![7; size],
966 content_type: "image/png".to_owned(),
967 fetched_at: at(minute),
968 }
969}
970
971#[test]
972fn images_round_trip_and_evict_the_oldest_over_the_cap() {
973 let store = Store::open_in_memory().unwrap();
974 store.put_image(&image("a", 1, 40), 100).unwrap();
975 store.put_image(&image("b", 2, 40), 100).unwrap();
976 assert_eq!(store.image("a").unwrap().unwrap().bytes.len(), 40);
977 store.put_image(&image("c", 3, 40), 100).unwrap();
978 assert!(store.image("a").unwrap().is_none());
979 assert!(store.has_image("b").unwrap());
980 assert!(store.has_image("c").unwrap());
981 assert_eq!(store.image_cache_bytes().unwrap(), 80);
982 store.put_image(&image("big", 0, 500), 100).unwrap();
983 assert!(store.has_image("big").unwrap());
984 assert_eq!(store.image_cache_bytes().unwrap(), 500);
985}
986
987#[test]
988fn first_message_after_from_others_skips_own_and_deleted() {
989 let store = Store::open_in_memory().unwrap();
990 let mut own = message("c1", "own", 2);
991 own.sender_id = Some("me".to_owned());
992 let mut gone = message("c1", "gone", 3);
993 gone.deleted = true;
994 store
995 .upsert_messages(&[message("c1", "old", 1), own, gone, message("c1", "new", 4)])
996 .unwrap();
997 assert_eq!(
998 store
999 .first_message_after_from_others("c1", Some(at(1)), "me")
1000 .unwrap()
1001 .as_deref(),
1002 Some("new")
1003 );
1004 assert_eq!(
1005 store
1006 .first_message_after_from_others("c1", None, "me")
1007 .unwrap()
1008 .as_deref(),
1009 Some("old")
1010 );
1011 assert!(
1012 store
1013 .first_message_after_from_others("c1", Some(at(4)), "me")
1014 .unwrap()
1015 .is_none()
1016 );
1017}
1018
1019#[test]
1020fn a_team_is_found_by_id() {
1021 let store = Store::open_in_memory().unwrap();
1022 store
1023 .upsert_teams(&[TeamRecord {
1024 id: "t1".to_owned(),
1025 name: "Alpha".to_owned(),
1026 }])
1027 .unwrap();
1028 assert_eq!(store.team("t1").unwrap().unwrap().name, "Alpha");
1029 assert!(store.team("nope").unwrap().is_none());
1030}
1031
1032#[test]
1033fn sync_does_not_resurrect_a_locally_read_chat() {
1034 let store = Store::open_in_memory().unwrap();
1035 store
1036 .upsert_chats(&[chat("chat-1", "Planning", Some(at(5)))])
1037 .unwrap();
1038 store.mark_chat_read("chat-1", at(10)).unwrap();
1039
1040 store
1041 .upsert_chats(&[chat("chat-1", "Planning", Some(at(5)))])
1042 .unwrap();
1043 let stale = store.chat("chat-1").unwrap().unwrap();
1044 assert!(!stale.unread);
1045 assert_eq!(stale.last_read_at, Some(at(10)));
1046
1047 store
1048 .upsert_chats(&[chat("chat-1", "Planning", Some(at(12)))])
1049 .unwrap();
1050 assert!(store.chat("chat-1").unwrap().unwrap().unread);
1051}
1052
1053#[test]
1054fn mark_chat_unread_sets_the_flag_and_horizon() {
1055 let store = Store::open_in_memory().unwrap();
1056 store
1057 .upsert_chats(&[chat("chat-1", "Planning", Some(at(5)))])
1058 .unwrap();
1059 store.mark_chat_read("chat-1", at(10)).unwrap();
1060
1061 store.mark_chat_unread("chat-1", at(4)).unwrap();
1062 let unread = store.chat("chat-1").unwrap().unwrap();
1063 assert!(unread.unread);
1064 assert_eq!(unread.last_read_at, Some(at(4)));
1065}
1066
1067#[test]
1068fn muted_flag_survives_a_chat_refresh() {
1069 let store = Store::open_in_memory().unwrap();
1070 store
1071 .upsert_chats(&[chat("a", "A", Some(at(1))), chat("b", "B", Some(at(2)))])
1072 .unwrap();
1073 assert!(!store.chat("a").unwrap().unwrap().muted);
1074
1075 store.set_chat_muted("a", true).unwrap();
1076 store
1077 .upsert_chats(&[chat("a", "A", Some(at(3))), chat("b", "B", Some(at(2)))])
1078 .unwrap();
1079 assert!(store.chat("a").unwrap().unwrap().muted);
1080 assert!(!store.chat("b").unwrap().unwrap().muted);
1081
1082 store.set_chat_muted("a", false).unwrap();
1083 assert!(!store.chat("a").unwrap().unwrap().muted);
1084}
1085
1086#[test]
1087fn muted_states_touch_only_the_listed_chats() {
1088 let store = Store::open_in_memory().unwrap();
1089 store
1090 .upsert_chats(&[
1091 chat("a", "A", Some(at(1))),
1092 chat("b", "B", Some(at(2))),
1093 chat("c", "C", Some(at(3))),
1094 ])
1095 .unwrap();
1096 store.set_chat_muted("a", true).unwrap();
1097 store.set_chat_muted("c", true).unwrap();
1098
1099 store
1100 .apply_muted_states(&[
1101 ("a".to_owned(), false),
1102 ("b".to_owned(), true),
1103 ("gone".to_owned(), true),
1104 ])
1105 .unwrap();
1106 assert!(!store.chat("a").unwrap().unwrap().muted);
1107 assert!(store.chat("b").unwrap().unwrap().muted);
1108 assert!(store.chat("c").unwrap().unwrap().muted);
1109}
1110
1111#[test]
1112fn presence_upsert_keeps_the_latest_availability() {
1113 let store = Store::open_in_memory().unwrap();
1114 let first = [("ada".to_owned(), "Available".to_owned())];
1115 store.upsert_presences(&first, at(1)).unwrap();
1116 let second = [
1117 ("ada".to_owned(), "Away".to_owned()),
1118 ("bob".to_owned(), "Busy".to_owned()),
1119 ];
1120 store.upsert_presences(&second, at(2)).unwrap();
1121 let mut presences = store.presences().unwrap();
1122 presences.sort();
1123 assert_eq!(presences, second.to_vec());
1124}
1125
1126fn activity(id: i64, minute: u32) -> store::ActivityRecord {
1127 store::ActivityRecord {
1128 id,
1129 conversation_id: "c1".to_owned(),
1130 kind: "messages".to_owned(),
1131 message_id: format!("m{id}"),
1132 actors_json: r#"[{"user_id":"user-ada","name":"Ada Example"}]"#.to_owned(),
1133 preview: "hello".to_owned(),
1134 glyphs: String::new(),
1135 count: 1,
1136 updated_at: at(minute),
1137 read: false,
1138 }
1139}
1140
1141#[test]
1142fn activity_upsert_inserts_then_updates_in_place() {
1143 let store = Store::open_in_memory().unwrap();
1144 store
1145 .upsert_activity(&[activity(1, 5), activity(2, 9)])
1146 .unwrap();
1147 let mut changed = activity(1, 12);
1148 changed.count = 3;
1149 changed.read = true;
1150 store
1151 .upsert_activity(std::slice::from_ref(&changed))
1152 .unwrap();
1153 let records = store.activity().unwrap();
1154 assert_eq!(records.len(), 2);
1155 assert_eq!(records[0], changed);
1156 assert_eq!(records[1].id, 2);
1157}
1158
1159#[test]
1160fn activity_prune_drops_only_older_rows() {
1161 let store = Store::open_in_memory().unwrap();
1162 store
1163 .upsert_activity(&[activity(1, 5), activity(2, 9), activity(3, 20)])
1164 .unwrap();
1165 assert_eq!(store.prune_activity(at(9)).unwrap(), 1);
1166 let ids: Vec<i64> = store
1167 .activity()
1168 .unwrap()
1169 .iter()
1170 .map(|record| record.id)
1171 .collect();
1172 assert_eq!(ids, vec![3, 2]);
1173}
1174
1175#[test]
1176fn display_names_prefer_members_then_latest_sender_name() {
1177 let store = Store::open_in_memory().unwrap();
1178 store
1179 .upsert_chats(&[chat("chat-1", "Planning", Some(at(5)))])
1180 .unwrap();
1181 let sent_by = |message_id: &str, minute: u32, sender: &str, name: Option<&str>| MessageRecord {
1182 sender_id: Some(sender.to_owned()),
1183 sender_name: name.map(str::to_owned),
1184 ..message("channel", message_id, minute)
1185 };
1186 store
1187 .upsert_messages(&[
1188 sent_by("m1", 1, "user-ada", Some("Ada Sender")),
1189 sent_by("m2", 2, "user-sam", Some("Sam Old")),
1190 sent_by("m3", 3, "user-sam", Some("Sam New")),
1191 sent_by("m4", 4, "user-sam", None),
1192 sent_by("m5", 5, "user-blank", Some("")),
1193 ])
1194 .unwrap();
1195 let wanted: Vec<String> = ["user-ada", "user-sam", "user-blank", "user-none"]
1196 .map(str::to_owned)
1197 .to_vec();
1198 let names = store.display_names(&wanted).unwrap();
1199 assert_eq!(names.len(), 2);
1200 assert_eq!(names["user-ada"], "Ada Example");
1201 assert_eq!(names["user-sam"], "Sam New");
1202 assert!(store.display_names(&[]).unwrap().is_empty());
1203}
1204
1205#[test]
1206fn channel_tabs_keep_their_saved_order_and_are_replaced_on_refresh() {
1207 let store = Store::open_in_memory().unwrap();
1208 let tab = |tab_id: &str, open_url: Option<&str>| ChannelTabRecord {
1209 tab_id: tab_id.to_owned(),
1210 name: format!("Tab {tab_id}"),
1211 definition_id: "com.microsoft.teamspace.tab.web".to_owned(),
1212 open_url: open_url.map(str::to_owned),
1213 };
1214 let layout = |tabs: Vec<ChannelTabRecord>| {
1215 vec![TeamLayoutRecord {
1216 team_id: "team".to_owned(),
1217 hidden: false,
1218 channels: vec![ChannelLayoutRecord {
1219 channel_id: "channel".to_owned(),
1220 general: false,
1221 hidden: false,
1222 tabs,
1223 notifications: ChannelNotifications::default(),
1224 }],
1225 }]
1226 };
1227 store
1228 .replace_team_layout(&layout(vec![
1229 tab("b", Some("https://b.example")),
1230 tab("a", None),
1231 ]))
1232 .unwrap();
1233 let tabs = store.channel_tabs("channel").unwrap();
1234 let ids: Vec<&str> = tabs.iter().map(|tab| tab.tab_id.as_str()).collect();
1235 assert_eq!(ids, ["b", "a"]);
1236 assert_eq!(tabs[0].open_url.as_deref(), Some("https://b.example"));
1237 assert!(store.channel_tabs("other").unwrap().is_empty());
1238 store.replace_team_layout(&layout(Vec::new())).unwrap();
1239 assert!(store.channel_tabs("channel").unwrap().is_empty());
1240}
1241
1242#[test]
1243fn channel_notifications_default_to_feed_and_survive_layout_and_local_writes() {
1244 let store = Store::open_in_memory().unwrap();
1245 store
1246 .upsert_teams(&[TeamRecord {
1247 id: "t1".to_owned(),
1248 name: "Alpha".to_owned(),
1249 }])
1250 .unwrap();
1251 let channel = |id: &str, name: &str| ChannelRecord {
1252 id: id.to_owned(),
1253 team_id: "t1".to_owned(),
1254 name: name.to_owned(),
1255 membership_type: None,
1256 last_message_at: None,
1257 unread: false,
1258 };
1259 store
1260 .upsert_channels(&[channel("c1", "General"), channel("c2", "Random")])
1261 .unwrap();
1262 let team = || store.sidebar().unwrap().teams.remove(0);
1263 assert_eq!(
1264 team().channel_notifications("c2"),
1265 ChannelNotifications::default()
1266 );
1267
1268 let banner = ChannelNotifications {
1269 level: ChannelNotificationLevel::BannerAndFeed,
1270 include_replies: true,
1271 };
1272 store.set_channel_notifications("c2", banner).unwrap();
1273 let sidebar_team = team();
1274 assert_eq!(sidebar_team.channel_notifications("c2"), banner);
1275 assert_eq!(sidebar_team.channels[0].name, "General");
1276
1277 let off = ChannelNotifications {
1278 level: ChannelNotificationLevel::Off,
1279 include_replies: false,
1280 };
1281 store
1282 .replace_team_layout(&[TeamLayoutRecord {
1283 team_id: "t1".to_owned(),
1284 hidden: false,
1285 channels: vec![ChannelLayoutRecord {
1286 channel_id: "c2".to_owned(),
1287 general: false,
1288 hidden: false,
1289 tabs: Vec::new(),
1290 notifications: off,
1291 }],
1292 }])
1293 .unwrap();
1294 assert_eq!(team().channel_notifications("c2"), off);
1295}
1296
1297#[test]
1298fn recent_messages_run_newest_first_across_scopes_with_a_cursor() {
1299 let store = Store::open_in_memory().unwrap();
1300 let mut deleted = message("chat-a", "a3", 8);
1301 deleted.deleted = true;
1302 store
1303 .upsert_messages(&[
1304 message("chat-a", "a1", 1),
1305 message("chat-a", "a2", 6),
1306 deleted,
1307 message("chat-b", "b1", 5),
1308 message("chat-b", "b2", 7),
1309 message("chat-c", "c1", 9),
1310 ])
1311 .unwrap();
1312 let scope = |conversation_id: &str, minute: u32| RecentScope {
1313 conversation_id: conversation_id.to_owned(),
1314 after: at(minute),
1315 };
1316 let scopes = [scope("chat-a", 0), scope("chat-b", 5)];
1317 let ids = |messages: Vec<MessageRecord>| -> Vec<String> {
1318 messages
1319 .into_iter()
1320 .map(|message| message.message_id)
1321 .collect()
1322 };
1323 assert_eq!(
1324 ids(store.recent_messages(&scopes, None, 10).unwrap()),
1325 ["b2", "a2", "a1"]
1326 );
1327 assert_eq!(
1328 ids(store.recent_messages(&scopes, None, 2).unwrap()),
1329 ["b2", "a2"]
1330 );
1331 assert_eq!(
1332 ids(store
1333 .recent_messages(&scopes, Some((at(6), "a2", "chat-a")), 10)
1334 .unwrap()),
1335 ["a1"]
1336 );
1337 assert!(store.recent_messages(&[], None, 10).unwrap().is_empty());
1338}
1339
1340#[test]
1341fn recent_messages_break_ties_by_conversation_across_the_cursor() {
1342 let store = Store::open_in_memory().unwrap();
1343 store
1344 .upsert_messages(&[message("chat-a", "m1", 5), message("chat-b", "m1", 5)])
1345 .unwrap();
1346 let scopes: Vec<RecentScope> = ["chat-a", "chat-b"]
1347 .into_iter()
1348 .map(|conversation_id| RecentScope {
1349 conversation_id: conversation_id.to_owned(),
1350 after: at(0),
1351 })
1352 .collect();
1353 let first = store.recent_messages(&scopes, None, 1).unwrap();
1354 assert_eq!(first[0].conversation_id, "chat-b");
1355 let second = store
1356 .recent_messages(&scopes, Some((at(5), "m1", "chat-b")), 1)
1357 .unwrap();
1358 assert_eq!(second[0].conversation_id, "chat-a");
1359 assert!(
1360 store
1361 .recent_messages(&scopes, Some((at(5), "m1", "chat-a")), 1)
1362 .unwrap()
1363 .is_empty()
1364 );
1365}
1366
1367fn call_message(message_id: &str, minute: u32) -> MessageRecord {
1368 MessageRecord {
1369 sender_id: None,
1370 sender_name: None,
1371 body_html: String::new(),
1372 call_event_json: Some(r#"{"phase":"Ended"}"#.to_owned()),
1373 ..message("c", message_id, minute)
1374 }
1375}
1376
1377#[test]
1378fn call_event_round_trips_and_is_not_indexed_or_unread() {
1379 let store = Store::open_in_memory().unwrap();
1380 store
1381 .upsert_messages(&[call_message("call", 1), message("c", "text", 2)])
1382 .unwrap();
1383 let stored = store.messages("c", None, 10).unwrap();
1384 assert_eq!(
1385 stored[0].call_event_json.as_deref(),
1386 Some(r#"{"phase":"Ended"}"#)
1387 );
1388 assert_eq!(stored[1].call_event_json, None);
1389 assert_eq!(store.count_messages_after("c", None, "me").unwrap(), 1);
1390 assert_eq!(
1391 store
1392 .first_message_after_from_others("c", None, "me")
1393 .unwrap()
1394 .as_deref(),
1395 Some("text")
1396 );
1397}
1398
1399#[test]
1400fn migration_to_v20_adds_the_call_event_column() {
1401 let directory = tempfile::tempdir().unwrap();
1402 let path = directory.path().join("old.sqlite3");
1403 {
1404 let store = Store::open(&path).unwrap();
1405 store.upsert_messages(&[message("c", "old", 1)]).unwrap();
1406 store.upsert_chats(&[chat("c", "Chat", Some(at(1)))]).unwrap();
1407 store.set_sync_state("c", &SyncState::default()).unwrap();
1408 store.set_sync_state("channel", &SyncState::default()).unwrap();
1409 drop(store);
1410 Connection::open(&path)
1411 .unwrap()
1412 .execute_batch("ALTER TABLE messages DROP COLUMN call_event_json; PRAGMA user_version = 19")
1413 .unwrap();
1414 }
1415 let store = Store::open(&path).unwrap();
1416 assert_eq!(store.schema_version().unwrap(), 21);
1417 let old = store.messages("c", None, 10).unwrap();
1418 assert_eq!(old[0].call_event_json, None);
1419 assert!(store.sync_state("c").unwrap().is_none());
1420 assert!(store.sync_state("channel").unwrap().is_some());
1421 store.upsert_messages(&[call_message("call", 2)]).unwrap();
1422 assert!(store.messages("c", None, 10).unwrap()[1].call_event_json.is_some());
1423}
1424
1425#[test]
1426fn migration_to_v21_refetches_chats_and_channels_for_recordings() {
1427 let directory = tempfile::tempdir().unwrap();
1428 let path = directory.path().join("old.sqlite3");
1429 {
1430 let store = Store::open(&path).unwrap();
1431 store.upsert_chats(&[chat("c", "Chat", Some(at(1)))]).unwrap();
1432 store
1433 .upsert_teams(&[TeamRecord {
1434 id: "team".to_owned(),
1435 name: "Team".to_owned(),
1436 }])
1437 .unwrap();
1438 store
1439 .upsert_channels(&[ChannelRecord {
1440 id: "channel".to_owned(),
1441 team_id: "team".to_owned(),
1442 name: "General".to_owned(),
1443 membership_type: None,
1444 last_message_at: None,
1445 unread: false,
1446 }])
1447 .unwrap();
1448 for conversation_id in ["c", "channel", "other"] {
1449 store
1450 .set_sync_state(conversation_id, &SyncState::default())
1451 .unwrap();
1452 }
1453 drop(store);
1454 Connection::open(&path)
1455 .unwrap()
1456 .execute_batch("PRAGMA user_version = 20")
1457 .unwrap();
1458 }
1459 let store = Store::open(&path).unwrap();
1460 assert_eq!(store.schema_version().unwrap(), 21);
1461 assert!(store.sync_state("c").unwrap().is_none());
1462 assert!(store.sync_state("channel").unwrap().is_none());
1463 assert!(store.sync_state("other").unwrap().is_some());
1464}