BlueGit

ict rusty-teams

Files

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

store.rs

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