BlueGit

ict rusty-teams

Files

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

store.rs

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