BlueGit

ict rusty-teams

Files

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

store.rs

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