BlueGit

ict rusty-teams

Files

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

store.rs

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