BlueGit

ict rusty-teams

feat(chat): link previews like Teams, received, while typing and sent

- Messages show Teams' own preview card (image, title, description, site) from the chat service links property
- The composer shows a preview of the first public link with an X to drop it
- After a send the preview is attached to the message, so colleagues in Teams see it too
- Internal links (SharePoint, OneDrive, Teams) get no card

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

metis Daniel Däschle · pushed by metis

Authored 2026-10-09 · 7 weeks ago

Hash
2e0d2924b8a67e608b2f9d9dac049ca7bc442426
Parent
a3649f1d
31 files changed +1740 −29
Cargo.lock +1 −0
@@ -1086,6 +1086,7 @@ dependencies = [
1086 1086 name = "chatsvc"
1087 1087 version = "0.1.0"
1088 1088 dependencies = [
1089 "base64 0.22.1",
1089 1090 "chrono",
1090 1091 "futures-util",
1091 1092 "percent-encoding",
@@ -1086,6 +1086,7 @@ dependencies = [
1086name = "chatsvc"
1086name = "chatsvc"
1087version = "0.1.0"
1087version = "0.1.0"
1088dependencies = [
1088dependencies = [
1089 "base64 0.22.1",
1089 "chrono",
1090 "chrono",
1090 "futures-util",
1091 "futures-util",
1091 "percent-encoding",
1092 "percent-encoding",
README.md +1 −0
@@ -15,6 +15,7 @@ It does chats and channels. Calls, meetings and channel tabs are planned (see [R
15 15 - Send, edit, delete, react, quote-reply, @mentions
16 16 - Rich text composer: format bar over a selection, `Ctrl+B` / `Ctrl+I` / `Ctrl+U`, lists, quotes, code; Markdown converts as you type or paste
17 17 - Emoji by `:` code with English codes and German aliases, `:thumbsup:` and `:)` convert as you type
18 - Link previews: card under messages, preview above the composer that goes out with the message
18 19 - Inline images, file cards, Adaptive Cards (layout, links, images, buttons: submit, execute, show card, toggle; input fields; task dialogs)
19 20 - Read receipts, typing indicator (shown and sent), presence (last known status shown at start), unread jump
20 21 - Select and copy message text, `Ctrl+A` in the composer
@@ -15,6 +15,7 @@ It does chats and channels. Calls, meetings and channel tabs are planned (see [R
15- Send, edit, delete, react, quote-reply, @mentions
15- Send, edit, delete, react, quote-reply, @mentions
16- Rich text composer: format bar over a selection, `Ctrl+B` / `Ctrl+I` / `Ctrl+U`, lists, quotes, code; Markdown converts as you type or paste
16- Rich text composer: format bar over a selection, `Ctrl+B` / `Ctrl+I` / `Ctrl+U`, lists, quotes, code; Markdown converts as you type or paste
17- Emoji by `:` code with English codes and German aliases, `:thumbsup:` and `:)` convert as you type
17- Emoji by `:` code with English codes and German aliases, `:thumbsup:` and `:)` convert as you type
18- Link previews: card under messages, preview above the composer that goes out with the message
18- Inline images, file cards, Adaptive Cards (layout, links, images, buttons: submit, execute, show card, toggle; input fields; task dialogs)
19- Inline images, file cards, Adaptive Cards (layout, links, images, buttons: submit, execute, show card, toggle; input fields; task dialogs)
19- Read receipts, typing indicator (shown and sent), presence (last known status shown at start), unread jump
20- Read receipts, typing indicator (shown and sent), presence (last known status shown at start), unread jump
20- Select and copy message text, `Ctrl+A` in the composer
21- Select and copy message text, `Ctrl+A` in the composer
ROADMAP.md +3 −3
@@ -2,7 +2,7 @@
2 2
3 3 Feature parity with the Microsoft Teams desktop client.
4 4
5 **Parity: 65 %** (53 done, 4 partial, 28 missing of 85). Partial counts half.
5 **Parity: 66 %** (54 done, 4 partial, 27 missing of 85). Partial counts half.
6 6
7 7 ## By area
8 8
@@ -10,7 +10,7 @@ Feature parity with the Microsoft Teams desktop client.
10 10 |---|---|---|---|---|
11 11 | [Sign-in and app](#sign-in-and-app) | 75 % | 4 | 1 | 1 |
12 12 | [Chat list](#chat-list) | 90 % | 9 | 0 | 1 |
13 | [Reading](#reading) | 76 % | 14 | 1 | 4 |
13 | [Reading](#reading) | 82 % | 15 | 1 | 3 |
14 14 | [Writing](#writing) | 75 % | 10 | 1 | 3 |
15 15 | [Message actions](#message-actions) | 0 % | 0 | 0 | 4 |
16 16 | [Channels](#channels) | 36 % | 2 | 1 | 4 |
@@ -76,7 +76,7 @@ Feature parity with the Microsoft Teams desktop client.
76 76 | Select and copy message text | Done | |
77 77 | Adaptive Cards | Partial | Buttons work (submit, execute, show card, toggle, task dialog card). Input fields work in messages and card dialogs (text, number, date, time, toggle, choice set) with validation. URL task dialogs run in a hosted window on Windows (Teams JS SDK host, see docs/research/card-actions.md), in the browser on Linux. Date and time are plain text fields, no picker |
78 78 | Typing indicator | Done | Shows who types in the chat, thread and list preview; sends your own typing |
79 | Link previews | Missing | |
79 | Link previews | Done | One card per message from the chat service, see docs/research/link-previews.md |
80 80 | Loop components | Missing | |
81 81 | Translate a message | Missing | |
82 82
@@ -2,7 +2,7 @@
2
2
3Feature parity with the Microsoft Teams desktop client.
3Feature parity with the Microsoft Teams desktop client.
4
4
5**Parity: 65 %** (53 done, 4 partial, 28 missing of 85). Partial counts half.
5**Parity: 66 %** (54 done, 4 partial, 27 missing of 85). Partial counts half.
6
6
7## By area
7## By area
8
8
@@ -10,7 +10,7 @@ Feature parity with the Microsoft Teams desktop client.
10|---|---|---|---|---|
10|---|---|---|---|---|
11| [Sign-in and app](#sign-in-and-app) | 75 % | 4 | 1 | 1 |
11| [Sign-in and app](#sign-in-and-app) | 75 % | 4 | 1 | 1 |
12| [Chat list](#chat-list) | 90 % | 9 | 0 | 1 |
12| [Chat list](#chat-list) | 90 % | 9 | 0 | 1 |
13| [Reading](#reading) | 76 % | 14 | 1 | 4 |
13| [Reading](#reading) | 82 % | 15 | 1 | 3 |
14| [Writing](#writing) | 75 % | 10 | 1 | 3 |
14| [Writing](#writing) | 75 % | 10 | 1 | 3 |
15| [Message actions](#message-actions) | 0 % | 0 | 0 | 4 |
15| [Message actions](#message-actions) | 0 % | 0 | 0 | 4 |
16| [Channels](#channels) | 36 % | 2 | 1 | 4 |
16| [Channels](#channels) | 36 % | 2 | 1 | 4 |
@@ -76,7 +76,7 @@ Feature parity with the Microsoft Teams desktop client.
76| Select and copy message text | Done | |
76| Select and copy message text | Done | |
77| Adaptive Cards | Partial | Buttons work (submit, execute, show card, toggle, task dialog card). Input fields work in messages and card dialogs (text, number, date, time, toggle, choice set) with validation. URL task dialogs run in a hosted window on Windows (Teams JS SDK host, see docs/research/card-actions.md), in the browser on Linux. Date and time are plain text fields, no picker |
77| Adaptive Cards | Partial | Buttons work (submit, execute, show card, toggle, task dialog card). Input fields work in messages and card dialogs (text, number, date, time, toggle, choice set) with validation. URL task dialogs run in a hosted window on Windows (Teams JS SDK host, see docs/research/card-actions.md), in the browser on Linux. Date and time are plain text fields, no picker |
78| Typing indicator | Done | Shows who types in the chat, thread and list preview; sends your own typing |
78| Typing indicator | Done | Shows who types in the chat, thread and list preview; sends your own typing |
79| Link previews | Missing | |
79| Link previews | Done | One card per message from the chat service, see docs/research/link-previews.md |
80| Loop components | Missing | |
80| Loop components | Missing | |
81| Translate a message | Missing | |
81| Translate a message | Missing | |
82
82
crates/app/src/demo.rs +62 −1
@@ -9,7 +9,8 @@ use store::{
9 9 TeamLayoutRecord, TeamRecord,
10 10 };
11 11 use teams_core::{
12 CardActionOutcome, ChatApp, MentionCandidate, PersonCandidate, PersonSource, TaskDialog,
12 CardActionOutcome, ChatApp, LinkPreview, MentionCandidate, PersonCandidate, PersonSource,
13 TaskDialog,
13 14 TaskDialogKind,
14 15 };
15 16
@@ -24,6 +25,9 @@ const PHOTO_SIZE: usize = 48;
24 25 const STAGING_IMAGE_KEY: &str = "demo://staging-dashboard";
25 26 const PENDING_IMAGE_KEY: &str = "demo://pending-screenshot";
26 27 const STAGING_SIZE: (usize, usize) = (960, 540);
28 const LINK_IMAGE_KEY: &str =
29 "https://de-prod.asyncgw.teams.microsoft.com/urlp/v1/url/image/Thumbnail?url=demo";
30 const LINK_IMAGE_SIZE: (u32, u32) = (320, 180);
27 31 const PRIORITY_CHAT: &str = "demo-chat-priya";
28 32 const BOT_CHAT: &str = "demo-chat-wiki-bot";
29 33 const BOT_NAME: &str = "Wiki Bot";
@@ -649,6 +653,7 @@ pub fn seed_directory(state: &mut AppState) {
649 653 let png = encode_rgb(STAGING_SIZE.0, STAGING_SIZE.1, staging_pixel);
650 654 if std::fs::write(&path, png).is_ok() {
651 655 state.directory.set_image(STAGING_IMAGE_KEY, &path);
656 state.directory.set_image(LINK_IMAGE_KEY, &path);
652 657 }
653 658 }
654 659 state.typing.start(
@@ -681,6 +686,7 @@ fn message(
681 686 sender_id: Some(sender.0.to_owned()),
682 687 sender_name: Some(sender.1.to_owned()),
683 688 sender_application_id: None,
689 links_json: "[]".to_owned(),
684 690 created_at: time,
685 691 edited_at: edited.then_some(time + Duration::minutes(2)),
686 692 deleted: false,
@@ -696,6 +702,25 @@ fn with_attachments(mut record: MessageRecord, attachments_json: &str) -> Messag
696 702 record
697 703 }
698 704
705 fn with_links(mut record: MessageRecord, links_json: String) -> MessageRecord {
706 record.links_json = links_json;
707 record
708 }
709
710 pub fn link_preview(url: &str) -> Option<LinkPreview> {
711 Some(LinkPreview {
712 url: url.to_owned(),
713 title: Some("Release checklist Q4".to_owned()),
714 description: Some(
715 "Everything that has to be green before the release candidate goes out on Friday."
716 .to_owned(),
717 ),
718 image_url: Some(LINK_IMAGE_KEY.to_owned()),
719 image_width: Some(LINK_IMAGE_SIZE.0),
720 image_height: Some(LINK_IMAGE_SIZE.1),
721 })
722 }
723
699 724 fn bot_messages() -> Vec<MessageRecord> {
700 725 let card = serde_json::json!({
701 726 "type": "AdaptiveCard",
@@ -975,6 +1000,21 @@ fn release_messages() -> Vec<MessageRecord> {
975 1000 &likes,
976 1001 false,
977 1002 ),
1003 with_links(
1004 message(
1005 chat,
1006 "m2a",
1007 None,
1008 mara,
1009 at(1, 16, 23),
1010 "<p><a href=\"https://example.com/checklist\">https://example.com/checklist</a></p>",
1011 "[]",
1012 false,
1013 ),
1014 link_preview("https://example.com/checklist")
1015 .map(|preview| preview.links_json())
1016 .unwrap_or_default(),
1017 ),
978 1018 message(
979 1019 chat,
980 1020 "m2b",
@@ -1071,6 +1111,27 @@ fn release_messages() -> Vec<MessageRecord> {
1071 1111 &many,
1072 1112 false,
1073 1113 ),
1114 with_links(
1115 message(
1116 chat,
1117 "m7a",
1118 None,
1119 me,
1120 at(0, 13, 37),
1121 "<p>Notes are in <a href=\"https://example.com/notes\">https://example.com/notes</a></p>",
1122 "[]",
1123 false,
1124 ),
1125 LinkPreview {
1126 url: "https://example.com/notes".to_owned(),
1127 title: Some("Release notes 0.2".to_owned()),
1128 description: None,
1129 image_url: None,
1130 image_width: None,
1131 image_height: None,
1132 }
1133 .links_json(),
1134 ),
1074 1135 message(
1075 1136 chat,
1076 1137 "m8",
@@ -9,7 +9,8 @@ use store::{
9 TeamLayoutRecord, TeamRecord,
9 TeamLayoutRecord, TeamRecord,
10};
10};
11use teams_core::{
11use teams_core::{
12 CardActionOutcome, ChatApp, MentionCandidate, PersonCandidate, PersonSource, TaskDialog,
12 CardActionOutcome, ChatApp, LinkPreview, MentionCandidate, PersonCandidate, PersonSource,
13 TaskDialog,
13 TaskDialogKind,
14 TaskDialogKind,
14};
15};
15
16
@@ -24,6 +25,9 @@ const PHOTO_SIZE: usize = 48;
24const STAGING_IMAGE_KEY: &str = "demo://staging-dashboard";
25const STAGING_IMAGE_KEY: &str = "demo://staging-dashboard";
25const PENDING_IMAGE_KEY: &str = "demo://pending-screenshot";
26const PENDING_IMAGE_KEY: &str = "demo://pending-screenshot";
26const STAGING_SIZE: (usize, usize) = (960, 540);
27const STAGING_SIZE: (usize, usize) = (960, 540);
28const LINK_IMAGE_KEY: &str =
29 "https://de-prod.asyncgw.teams.microsoft.com/urlp/v1/url/image/Thumbnail?url=demo";
30const LINK_IMAGE_SIZE: (u32, u32) = (320, 180);
27const PRIORITY_CHAT: &str = "demo-chat-priya";
31const PRIORITY_CHAT: &str = "demo-chat-priya";
28const BOT_CHAT: &str = "demo-chat-wiki-bot";
32const BOT_CHAT: &str = "demo-chat-wiki-bot";
29const BOT_NAME: &str = "Wiki Bot";
33const BOT_NAME: &str = "Wiki Bot";
@@ -649,6 +653,7 @@ pub fn seed_directory(state: &mut AppState) {
649 let png = encode_rgb(STAGING_SIZE.0, STAGING_SIZE.1, staging_pixel);
653 let png = encode_rgb(STAGING_SIZE.0, STAGING_SIZE.1, staging_pixel);
650 if std::fs::write(&path, png).is_ok() {
654 if std::fs::write(&path, png).is_ok() {
651 state.directory.set_image(STAGING_IMAGE_KEY, &path);
655 state.directory.set_image(STAGING_IMAGE_KEY, &path);
656 state.directory.set_image(LINK_IMAGE_KEY, &path);
652 }
657 }
653 }
658 }
654 state.typing.start(
659 state.typing.start(
@@ -681,6 +686,7 @@ fn message(
681 sender_id: Some(sender.0.to_owned()),
686 sender_id: Some(sender.0.to_owned()),
682 sender_name: Some(sender.1.to_owned()),
687 sender_name: Some(sender.1.to_owned()),
683 sender_application_id: None,
688 sender_application_id: None,
689 links_json: "[]".to_owned(),
684 created_at: time,
690 created_at: time,
685 edited_at: edited.then_some(time + Duration::minutes(2)),
691 edited_at: edited.then_some(time + Duration::minutes(2)),
686 deleted: false,
692 deleted: false,
@@ -696,6 +702,25 @@ fn with_attachments(mut record: MessageRecord, attachments_json: &str) -> Messag
696 record
702 record
697}
703}
698
704
705fn with_links(mut record: MessageRecord, links_json: String) -> MessageRecord {
706 record.links_json = links_json;
707 record
708}
709
710pub fn link_preview(url: &str) -> Option<LinkPreview> {
711 Some(LinkPreview {
712 url: url.to_owned(),
713 title: Some("Release checklist Q4".to_owned()),
714 description: Some(
715 "Everything that has to be green before the release candidate goes out on Friday."
716 .to_owned(),
717 ),
718 image_url: Some(LINK_IMAGE_KEY.to_owned()),
719 image_width: Some(LINK_IMAGE_SIZE.0),
720 image_height: Some(LINK_IMAGE_SIZE.1),
721 })
722}
723
699fn bot_messages() -> Vec<MessageRecord> {
724fn bot_messages() -> Vec<MessageRecord> {
700 let card = serde_json::json!({
725 let card = serde_json::json!({
701 "type": "AdaptiveCard",
726 "type": "AdaptiveCard",
@@ -975,6 +1000,21 @@ fn release_messages() -> Vec<MessageRecord> {
975 &likes,
1000 &likes,
976 false,
1001 false,
977 ),
1002 ),
1003 with_links(
1004 message(
1005 chat,
1006 "m2a",
1007 None,
1008 mara,
1009 at(1, 16, 23),
1010 "<p><a href=\"https://example.com/checklist\">https://example.com/checklist</a></p>",
1011 "[]",
1012 false,
1013 ),
1014 link_preview("https://example.com/checklist")
1015 .map(|preview| preview.links_json())
1016 .unwrap_or_default(),
1017 ),
978 message(
1018 message(
979 chat,
1019 chat,
980 "m2b",
1020 "m2b",
@@ -1071,6 +1111,27 @@ fn release_messages() -> Vec<MessageRecord> {
1071 &many,
1111 &many,
1072 false,
1112 false,
1073 ),
1113 ),
1114 with_links(
1115 message(
1116 chat,
1117 "m7a",
1118 None,
1119 me,
1120 at(0, 13, 37),
1121 "<p>Notes are in <a href=\"https://example.com/notes\">https://example.com/notes</a></p>",
1122 "[]",
1123 false,
1124 ),
1125 LinkPreview {
1126 url: "https://example.com/notes".to_owned(),
1127 title: Some("Release notes 0.2".to_owned()),
1128 description: None,
1129 image_url: None,
1130 image_width: None,
1131 image_height: None,
1132 }
1133 .links_json(),
1134 ),
1074 message(
1135 message(
1075 chat,
1136 chat,
1076 "m8",
1137 "m8",
crates/app/src/notify/incoming.rs +1 −0
@@ -271,6 +271,7 @@ mod tests {
271 271 sender_id: Some(sender.into()),
272 272 sender_name: Some("Sender".into()),
273 273 sender_application_id: None,
274 links_json: "[]".to_owned(),
274 275 created_at: at,
275 276 edited_at: None,
276 277 deleted: false,
@@ -271,6 +271,7 @@ mod tests {
271 sender_id: Some(sender.into()),
271 sender_id: Some(sender.into()),
272 sender_name: Some("Sender".into()),
272 sender_name: Some("Sender".into()),
273 sender_application_id: None,
273 sender_application_id: None,
274 links_json: "[]".to_owned(),
274 created_at: at,
275 created_at: at,
275 edited_at: None,
276 edited_at: None,
276 deleted: false,
277 deleted: false,
crates/app/src/rows.rs +5 −2
@@ -6,8 +6,8 @@ use chrono::{DateTime, Duration, FixedOffset, NaiveDate, Utc};
6 6 use gpui_kit::Image;
7 7 use store::MessageRecord;
8 8 use teams_core::{
9 AdaptiveCard, Draft, FileCard, ImageRef, ReactionInfo, Span, adaptive_cards, card_texts, files,
10 images, message_spans, reactions,
9 AdaptiveCard, Draft, FileCard, ImageRef, LinkPreview, ReactionInfo, Span, adaptive_cards,
10 card_texts, files, images, link_preview, message_spans, reactions,
11 11 };
12 12
13 13 use crate::card_state::CardOverride;
@@ -129,6 +129,7 @@ pub struct MessageRow {
129 129 pub images: Vec<ImageRef>,
130 130 pub local_images: Vec<LocalImage>,
131 131 pub files: Vec<FileCard>,
132 pub link_preview: Option<LinkPreview>,
132 133 pub adaptive_cards: Vec<AdaptiveCard>,
133 134 pub reply_count: Option<usize>,
134 135 pub new_marker: bool,
@@ -504,6 +505,7 @@ pub fn message_row(record: &MessageRecord, context: &RowContext) -> MessageRow {
504 505 images,
505 506 local_images: Vec::new(),
506 507 files: files(record),
508 link_preview: link_preview(record),
507 509 adaptive_cards: match context.card_overrides.get(&record.message_id) {
508 510 Some(replaced) if replaced.basis == record.attachments_json => replaced.cards.clone(),
509 511 _ => adaptive_cards(record),
@@ -713,6 +715,7 @@ mod tests {
713 715 sender_id: Some("u".into()),
714 716 sender_name: Some("Author".into()),
715 717 sender_application_id: None,
718 links_json: "[]".to_owned(),
716 719 created_at: Utc.with_ymd_and_hms(2026, 10, day, hour, 0, 0).unwrap(),
717 720 edited_at: None,
718 721 deleted: false,
@@ -6,8 +6,8 @@ use chrono::{DateTime, Duration, FixedOffset, NaiveDate, Utc};
6use gpui_kit::Image;
6use gpui_kit::Image;
7use store::MessageRecord;
7use store::MessageRecord;
8use teams_core::{
8use teams_core::{
9 AdaptiveCard, Draft, FileCard, ImageRef, ReactionInfo, Span, adaptive_cards, card_texts, files,
9 AdaptiveCard, Draft, FileCard, ImageRef, LinkPreview, ReactionInfo, Span, adaptive_cards,
10 images, message_spans, reactions,
10 card_texts, files, images, link_preview, message_spans, reactions,
11};
11};
12
12
13use crate::card_state::CardOverride;
13use crate::card_state::CardOverride;
@@ -129,6 +129,7 @@ pub struct MessageRow {
129 pub images: Vec<ImageRef>,
129 pub images: Vec<ImageRef>,
130 pub local_images: Vec<LocalImage>,
130 pub local_images: Vec<LocalImage>,
131 pub files: Vec<FileCard>,
131 pub files: Vec<FileCard>,
132 pub link_preview: Option<LinkPreview>,
132 pub adaptive_cards: Vec<AdaptiveCard>,
133 pub adaptive_cards: Vec<AdaptiveCard>,
133 pub reply_count: Option<usize>,
134 pub reply_count: Option<usize>,
134 pub new_marker: bool,
135 pub new_marker: bool,
@@ -504,6 +505,7 @@ pub fn message_row(record: &MessageRecord, context: &RowContext) -> MessageRow {
504 images,
505 images,
505 local_images: Vec::new(),
506 local_images: Vec::new(),
506 files: files(record),
507 files: files(record),
508 link_preview: link_preview(record),
507 adaptive_cards: match context.card_overrides.get(&record.message_id) {
509 adaptive_cards: match context.card_overrides.get(&record.message_id) {
508 Some(replaced) if replaced.basis == record.attachments_json => replaced.cards.clone(),
510 Some(replaced) if replaced.basis == record.attachments_json => replaced.cards.clone(),
509 _ => adaptive_cards(record),
511 _ => adaptive_cards(record),
@@ -713,6 +715,7 @@ mod tests {
713 sender_id: Some("u".into()),
715 sender_id: Some("u".into()),
714 sender_name: Some("Author".into()),
716 sender_name: Some("Author".into()),
715 sender_application_id: None,
717 sender_application_id: None,
718 links_json: "[]".to_owned(),
716 created_at: Utc.with_ymd_and_hms(2026, 10, day, hour, 0, 0).unwrap(),
719 created_at: Utc.with_ymd_and_hms(2026, 10, day, hour, 0, 0).unwrap(),
717 edited_at: None,
720 edited_at: None,
718 deleted: false,
721 deleted: false,
crates/app/src/views/composer.rs +103 −3
@@ -21,7 +21,7 @@ use gpui_kit::prelude::FluentBuilder as _;
21 21 use gpui_kit::*;
22 22 use teams_core::{
23 23 Draft, DraftLine, Edit, FileReference, FormatState, HostedImage, LineKind, MarkKind,
24 MentionCandidate, MentionInput, MessageExtras, OBJECT_MARK, SizeStep, TypingStyle,
24 LinkPreview, MentionCandidate, MentionInput, MessageExtras, OBJECT_MARK, SizeStep, TypingStyle,
25 25 UploadedFile, changed_span, has_markdown, link_url, map_offset, reverse_edits,
26 26 };
27 27
@@ -34,6 +34,7 @@ use super::avatar::{person_avatar, square_avatar};
34 34 use super::draft_style::draft_style;
35 35 use super::emoji_popup::{self, EmojiPopup};
36 36 use super::format_toolbar::{self, FormatButton};
37 use super::link_preview::{ComposeLink, draft_link, link_preview_card};
37 38 use super::widgets::{icon, symbol};
38 39 use crate::app_state::AppState;
39 40 use crate::emoji;
@@ -45,6 +46,7 @@ const MIN_ROWS: usize = 1;
45 46 const MAX_ROWS: usize = 8;
46 47 const MENTION_DEBOUNCE: Duration = Duration::from_millis(150);
47 48 const MENTION_LIMIT: usize = 8;
49 const LINK_PREVIEW_DEBOUNCE: Duration = Duration::from_millis(600);
48 50 const MENTION_QUERY_MAX_CHARS: usize = 32;
49 51 const MENTION_QUERY_MAX_WORDS: usize = 3;
50 52 const POPUP_WIDTH: f32 = 380.;
@@ -113,6 +115,7 @@ pub struct Outgoing {
113 115 pub edit: Option<EditPreview>,
114 116 pub images: Vec<OutgoingImage>,
115 117 pub files: Vec<OutgoingFile>,
118 pub link_preview: Option<LinkPreview>,
116 119 }
117 120
118 121 impl Outgoing {
@@ -264,7 +267,8 @@ pub struct Composer {
264 267 demo_failed: HashSet<u64>,
265 268 carry_images_into: Option<String>,
266 269 pending_anchors: HashMap<u64, usize>,
267 _subscriptions: [Subscription; 2],
270 link: ComposeLink,
271 _subscriptions: [Subscription; 3],
268 272 }
269 273
270 274 impl EventEmitter<ComposerEvent> for Composer {}
@@ -401,6 +405,11 @@ impl Composer {
401 405 });
402 406 let subscription = cx.subscribe_in(&input, window, Self::on_input_event);
403 407 let observer = cx.observe(&input, |_, _, cx| cx.notify());
408 let image_observer = cx.observe(&app, |this, _, cx| {
409 if this.link_image_pending(cx) {
410 cx.notify();
411 }
412 });
404 413 let decorations = input.update(cx, |state, cx| {
405 414 (
406 415 state.create_decorations_collection(Vec::new(), cx),
@@ -447,7 +456,8 @@ impl Composer {
447 456 demo_failed: HashSet::new(),
448 457 carry_images_into: None,
449 458 pending_anchors: HashMap::new(),
450 _subscriptions: [subscription, observer],
459 link: ComposeLink::default(),
460 _subscriptions: [subscription, observer, image_observer],
451 461 }
452 462 }
453 463
@@ -463,6 +473,7 @@ impl Composer {
463 473 self.on_change(window, cx);
464 474 self.update_emoji(cx);
465 475 self.update_mention(cx);
476 self.update_link_preview(cx);
466 477 }
467 478 let value = input.read(cx).value();
468 479 if submitted_text(event, &value).is_some()
@@ -1262,6 +1273,86 @@ impl Composer {
1262 1273 cx.notify();
1263 1274 }
1264 1275
1276 fn update_link_preview(&mut self, cx: &mut Context<Self>) {
1277 if self.editing.is_some() {
1278 self.link.reset();
1279 return;
1280 }
1281 let draft = self.current_draft(cx);
1282 if let Some(url) = self.link.observe(draft_link(&draft), draft.is_blank()) {
1283 self.fetch_link_preview(url, cx);
1284 }
1285 cx.notify();
1286 }
1287
1288 fn fetch_link_preview(&mut self, url: String, cx: &mut Context<Self>) {
1289 let (demo, engine) = {
1290 let state = self.app.read(cx);
1291 (state.mode.demo, state.engine.clone())
1292 };
1293 if demo {
1294 let preview = crate::demo::link_preview(&url);
1295 self.finish_link_preview(&url, preview, cx);
1296 return;
1297 }
1298 let Some(engine) = engine else {
1299 return;
1300 };
1301 self.link.lookup = Some(cx.spawn(async move |this, cx| {
1302 cx.background_executor()
1303 .timer(LINK_PREVIEW_DEBOUNCE)
1304 .await;
1305 let task_url = url.clone();
1306 let receiver =
1307 runtime::spawn(async move { engine.link_preview_for(&task_url).await });
1308 if let Ok(Ok(preview)) = receiver.await {
1309 this.update(cx, |this, cx| this.finish_link_preview(&url, preview, cx))
1310 .ok();
1311 }
1312 }));
1313 }
1314
1315 fn finish_link_preview(&mut self, url: &str, preview: Option<LinkPreview>, cx: &mut Context<Self>) {
1316 let image = preview.as_ref().and_then(LinkPreview::image);
1317 if !self.link.apply(url, preview) {
1318 return;
1319 }
1320 if let Some(image) = image {
1321 self.app
1322 .update(cx, |state, cx| state.request_images(vec![image], cx));
1323 }
1324 cx.notify();
1325 }
1326
1327 fn link_image_pending(&self, cx: &App) -> bool {
1328 self.link
1329 .shown()
1330 .and_then(LinkPreview::image)
1331 .is_some_and(|image| self.app.read(cx).directory.image(&image.url).is_none())
1332 }
1333
1334 fn render_link_preview(&self, cx: &mut Context<Self>) -> Option<Div> {
1335 let preview = self.link.shown()?;
1336 let composer = cx.weak_entity();
1337 let close: super::link_preview::CloseHandler = Rc::new(move |_, cx| {
1338 composer
1339 .update(cx, |this, cx| {
1340 this.link.dismiss();
1341 cx.notify();
1342 })
1343 .ok();
1344 });
1345 Some(
1346 div().w_full().mb(px(6.)).child(link_preview_card(
1347 preview,
1348 "composer-link-preview".to_owned(),
1349 &self.app.read(cx).directory,
1350 true,
1351 Some(close),
1352 )),
1353 )
1354 }
1355
1265 1356 fn popup_is_open(&self) -> bool {
1266 1357 self.emoji_popup.is_some()
1267 1358 || self
@@ -1345,6 +1436,7 @@ impl Composer {
1345 1436 self.discard_uploaded(dropped, cx);
1346 1437 self.remove_orphan_image_tokens(window, cx);
1347 1438 self.reply = None;
1439 self.link.reset();
1348 1440 if self.editing.take().is_some() {
1349 1441 self.load_draft(Draft::default(), InputContent::new(""), window, cx);
1350 1442 }
@@ -1425,6 +1517,7 @@ impl Composer {
1425 1517 mentions,
1426 1518 reply: self.reply.clone(),
1427 1519 edit: self.editing.clone(),
1520 link_preview: self.link.shown().filter(|_| attachments_apply).cloned(),
1428 1521 images: if attachments_apply {
1429 1522 self.tray.images_in(&image_ids)
1430 1523 } else {
@@ -1864,6 +1957,7 @@ impl Composer {
1864 1957 }
1865 1958 self.reply = None;
1866 1959 self.editing = None;
1960 self.link.reset();
1867 1961 self.close_popup();
1868 1962 cx.emit(ComposerEvent::Submit(Box::new(outgoing)));
1869 1963 cx.notify();
@@ -1904,6 +1998,7 @@ impl Composer {
1904 1998 self.load_draft(outgoing.draft.clone(), content, window, cx);
1905 1999 self.reply = outgoing.reply.clone();
1906 2000 self.editing = outgoing.edit.clone();
2001 self.link.restore(outgoing.link_preview.clone());
1907 2002 self.close_popup();
1908 2003 cx.notify();
1909 2004 }
@@ -1916,6 +2011,7 @@ impl Composer {
1916 2011 self.mention_inputs.clear();
1917 2012 self.update_emoji(cx);
1918 2013 self.update_mention(cx);
2014 self.update_link_preview(cx);
1919 2015 cx.notify();
1920 2016 }
1921 2017
@@ -2480,6 +2576,7 @@ impl Render for Composer {
2480 2576 .children(notice)
2481 2577 .children(self.render_reply_strip(cx))
2482 2578 .children(self.render_edit_strip(cx))
2579 .children(self.render_link_preview(cx))
2483 2580 .child(
2484 2581 div()
2485 2582 .relative()
@@ -2633,6 +2730,7 @@ mod tests {
2633 2730 let outgoing = Outgoing {
2634 2731 draft: teams_core::Draft::default(),
2635 2732 mentions: Vec::new(),
2733 link_preview: None,
2636 2734 reply: None,
2637 2735 edit: None,
2638 2736 images: vec![OutgoingImage {
@@ -2675,6 +2773,7 @@ mod tests {
2675 2773 super::Outgoing {
2676 2774 draft: teams_core::Draft::plain(text),
2677 2775 mentions: Vec::new(),
2776 link_preview: None,
2678 2777 reply: None,
2679 2778 edit: None,
2680 2779 images,
@@ -3662,6 +3761,7 @@ mod tests {
3662 3761 let draft = Outgoing {
3663 3762 draft: teams_core::Draft::plain("old"),
3664 3763 mentions: Vec::new(),
3764 link_preview: None,
3665 3765 reply: None,
3666 3766 edit: Some(EditPreview {
3667 3767 message_id: "m1".into(),
@@ -21,7 +21,7 @@ use gpui_kit::prelude::FluentBuilder as _;
21use gpui_kit::*;
21use gpui_kit::*;
22use teams_core::{
22use teams_core::{
23 Draft, DraftLine, Edit, FileReference, FormatState, HostedImage, LineKind, MarkKind,
23 Draft, DraftLine, Edit, FileReference, FormatState, HostedImage, LineKind, MarkKind,
24 MentionCandidate, MentionInput, MessageExtras, OBJECT_MARK, SizeStep, TypingStyle,
24 LinkPreview, MentionCandidate, MentionInput, MessageExtras, OBJECT_MARK, SizeStep, TypingStyle,
25 UploadedFile, changed_span, has_markdown, link_url, map_offset, reverse_edits,
25 UploadedFile, changed_span, has_markdown, link_url, map_offset, reverse_edits,
26};
26};
27
27
@@ -34,6 +34,7 @@ use super::avatar::{person_avatar, square_avatar};
34use super::draft_style::draft_style;
34use super::draft_style::draft_style;
35use super::emoji_popup::{self, EmojiPopup};
35use super::emoji_popup::{self, EmojiPopup};
36use super::format_toolbar::{self, FormatButton};
36use super::format_toolbar::{self, FormatButton};
37use super::link_preview::{ComposeLink, draft_link, link_preview_card};
37use super::widgets::{icon, symbol};
38use super::widgets::{icon, symbol};
38use crate::app_state::AppState;
39use crate::app_state::AppState;
39use crate::emoji;
40use crate::emoji;
@@ -45,6 +46,7 @@ const MIN_ROWS: usize = 1;
45const MAX_ROWS: usize = 8;
46const MAX_ROWS: usize = 8;
46const MENTION_DEBOUNCE: Duration = Duration::from_millis(150);
47const MENTION_DEBOUNCE: Duration = Duration::from_millis(150);
47const MENTION_LIMIT: usize = 8;
48const MENTION_LIMIT: usize = 8;
49const LINK_PREVIEW_DEBOUNCE: Duration = Duration::from_millis(600);
48const MENTION_QUERY_MAX_CHARS: usize = 32;
50const MENTION_QUERY_MAX_CHARS: usize = 32;
49const MENTION_QUERY_MAX_WORDS: usize = 3;
51const MENTION_QUERY_MAX_WORDS: usize = 3;
50const POPUP_WIDTH: f32 = 380.;
52const POPUP_WIDTH: f32 = 380.;
@@ -113,6 +115,7 @@ pub struct Outgoing {
113 pub edit: Option<EditPreview>,
115 pub edit: Option<EditPreview>,
114 pub images: Vec<OutgoingImage>,
116 pub images: Vec<OutgoingImage>,
115 pub files: Vec<OutgoingFile>,
117 pub files: Vec<OutgoingFile>,
118 pub link_preview: Option<LinkPreview>,
116}
119}
117
120
118impl Outgoing {
121impl Outgoing {
@@ -264,7 +267,8 @@ pub struct Composer {
264 demo_failed: HashSet<u64>,
267 demo_failed: HashSet<u64>,
265 carry_images_into: Option<String>,
268 carry_images_into: Option<String>,
266 pending_anchors: HashMap<u64, usize>,
269 pending_anchors: HashMap<u64, usize>,
267 _subscriptions: [Subscription; 2],
270 link: ComposeLink,
271 _subscriptions: [Subscription; 3],
268}
272}
269
273
270impl EventEmitter<ComposerEvent> for Composer {}
274impl EventEmitter<ComposerEvent> for Composer {}
@@ -401,6 +405,11 @@ impl Composer {
401 });
405 });
402 let subscription = cx.subscribe_in(&input, window, Self::on_input_event);
406 let subscription = cx.subscribe_in(&input, window, Self::on_input_event);
403 let observer = cx.observe(&input, |_, _, cx| cx.notify());
407 let observer = cx.observe(&input, |_, _, cx| cx.notify());
408 let image_observer = cx.observe(&app, |this, _, cx| {
409 if this.link_image_pending(cx) {
410 cx.notify();
411 }
412 });
404 let decorations = input.update(cx, |state, cx| {
413 let decorations = input.update(cx, |state, cx| {
405 (
414 (
406 state.create_decorations_collection(Vec::new(), cx),
415 state.create_decorations_collection(Vec::new(), cx),
@@ -447,7 +456,8 @@ impl Composer {
447 demo_failed: HashSet::new(),
456 demo_failed: HashSet::new(),
448 carry_images_into: None,
457 carry_images_into: None,
449 pending_anchors: HashMap::new(),
458 pending_anchors: HashMap::new(),
450 _subscriptions: [subscription, observer],
459 link: ComposeLink::default(),
460 _subscriptions: [subscription, observer, image_observer],
451 }
461 }
452 }
462 }
453
463
@@ -463,6 +473,7 @@ impl Composer {
463 self.on_change(window, cx);
473 self.on_change(window, cx);
464 self.update_emoji(cx);
474 self.update_emoji(cx);
465 self.update_mention(cx);
475 self.update_mention(cx);
476 self.update_link_preview(cx);
466 }
477 }
467 let value = input.read(cx).value();
478 let value = input.read(cx).value();
468 if submitted_text(event, &value).is_some()
479 if submitted_text(event, &value).is_some()
@@ -1262,6 +1273,86 @@ impl Composer {
1262 cx.notify();
1273 cx.notify();
1263 }
1274 }
1264
1275
1276 fn update_link_preview(&mut self, cx: &mut Context<Self>) {
1277 if self.editing.is_some() {
1278 self.link.reset();
1279 return;
1280 }
1281 let draft = self.current_draft(cx);
1282 if let Some(url) = self.link.observe(draft_link(&draft), draft.is_blank()) {
1283 self.fetch_link_preview(url, cx);
1284 }
1285 cx.notify();
1286 }
1287
1288 fn fetch_link_preview(&mut self, url: String, cx: &mut Context<Self>) {
1289 let (demo, engine) = {
1290 let state = self.app.read(cx);
1291 (state.mode.demo, state.engine.clone())
1292 };
1293 if demo {
1294 let preview = crate::demo::link_preview(&url);
1295 self.finish_link_preview(&url, preview, cx);
1296 return;
1297 }
1298 let Some(engine) = engine else {
1299 return;
1300 };
1301 self.link.lookup = Some(cx.spawn(async move |this, cx| {
1302 cx.background_executor()
1303 .timer(LINK_PREVIEW_DEBOUNCE)
1304 .await;
1305 let task_url = url.clone();
1306 let receiver =
1307 runtime::spawn(async move { engine.link_preview_for(&task_url).await });
1308 if let Ok(Ok(preview)) = receiver.await {
1309 this.update(cx, |this, cx| this.finish_link_preview(&url, preview, cx))
1310 .ok();
1311 }
1312 }));
1313 }
1314
1315 fn finish_link_preview(&mut self, url: &str, preview: Option<LinkPreview>, cx: &mut Context<Self>) {
1316 let image = preview.as_ref().and_then(LinkPreview::image);
1317 if !self.link.apply(url, preview) {
1318 return;
1319 }
1320 if let Some(image) = image {
1321 self.app
1322 .update(cx, |state, cx| state.request_images(vec![image], cx));
1323 }
1324 cx.notify();
1325 }
1326
1327 fn link_image_pending(&self, cx: &App) -> bool {
1328 self.link
1329 .shown()
1330 .and_then(LinkPreview::image)
1331 .is_some_and(|image| self.app.read(cx).directory.image(&image.url).is_none())
1332 }
1333
1334 fn render_link_preview(&self, cx: &mut Context<Self>) -> Option<Div> {
1335 let preview = self.link.shown()?;
1336 let composer = cx.weak_entity();
1337 let close: super::link_preview::CloseHandler = Rc::new(move |_, cx| {
1338 composer
1339 .update(cx, |this, cx| {
1340 this.link.dismiss();
1341 cx.notify();
1342 })
1343 .ok();
1344 });
1345 Some(
1346 div().w_full().mb(px(6.)).child(link_preview_card(
1347 preview,
1348 "composer-link-preview".to_owned(),
1349 &self.app.read(cx).directory,
1350 true,
1351 Some(close),
1352 )),
1353 )
1354 }
1355
1265 fn popup_is_open(&self) -> bool {
1356 fn popup_is_open(&self) -> bool {
1266 self.emoji_popup.is_some()
1357 self.emoji_popup.is_some()
1267 || self
1358 || self
@@ -1345,6 +1436,7 @@ impl Composer {
1345 self.discard_uploaded(dropped, cx);
1436 self.discard_uploaded(dropped, cx);
1346 self.remove_orphan_image_tokens(window, cx);
1437 self.remove_orphan_image_tokens(window, cx);
1347 self.reply = None;
1438 self.reply = None;
1439 self.link.reset();
1348 if self.editing.take().is_some() {
1440 if self.editing.take().is_some() {
1349 self.load_draft(Draft::default(), InputContent::new(""), window, cx);
1441 self.load_draft(Draft::default(), InputContent::new(""), window, cx);
1350 }
1442 }
@@ -1425,6 +1517,7 @@ impl Composer {
1425 mentions,
1517 mentions,
1426 reply: self.reply.clone(),
1518 reply: self.reply.clone(),
1427 edit: self.editing.clone(),
1519 edit: self.editing.clone(),
1520 link_preview: self.link.shown().filter(|_| attachments_apply).cloned(),
1428 images: if attachments_apply {
1521 images: if attachments_apply {
1429 self.tray.images_in(&image_ids)
1522 self.tray.images_in(&image_ids)
1430 } else {
1523 } else {
@@ -1864,6 +1957,7 @@ impl Composer {
1864 }
1957 }
1865 self.reply = None;
1958 self.reply = None;
1866 self.editing = None;
1959 self.editing = None;
1960 self.link.reset();
1867 self.close_popup();
1961 self.close_popup();
1868 cx.emit(ComposerEvent::Submit(Box::new(outgoing)));
1962 cx.emit(ComposerEvent::Submit(Box::new(outgoing)));
1869 cx.notify();
1963 cx.notify();
@@ -1904,6 +1998,7 @@ impl Composer {
1904 self.load_draft(outgoing.draft.clone(), content, window, cx);
1998 self.load_draft(outgoing.draft.clone(), content, window, cx);
1905 self.reply = outgoing.reply.clone();
1999 self.reply = outgoing.reply.clone();
1906 self.editing = outgoing.edit.clone();
2000 self.editing = outgoing.edit.clone();
2001 self.link.restore(outgoing.link_preview.clone());
1907 self.close_popup();
2002 self.close_popup();
1908 cx.notify();
2003 cx.notify();
1909 }
2004 }
@@ -1916,6 +2011,7 @@ impl Composer {
1916 self.mention_inputs.clear();
2011 self.mention_inputs.clear();
1917 self.update_emoji(cx);
2012 self.update_emoji(cx);
1918 self.update_mention(cx);
2013 self.update_mention(cx);
2014 self.update_link_preview(cx);
1919 cx.notify();
2015 cx.notify();
1920 }
2016 }
1921
2017
@@ -2480,6 +2576,7 @@ impl Render for Composer {
2480 .children(notice)
2576 .children(notice)
2481 .children(self.render_reply_strip(cx))
2577 .children(self.render_reply_strip(cx))
2482 .children(self.render_edit_strip(cx))
2578 .children(self.render_edit_strip(cx))
2579 .children(self.render_link_preview(cx))
2483 .child(
2580 .child(
2484 div()
2581 div()
2485 .relative()
2582 .relative()
@@ -2633,6 +2730,7 @@ mod tests {
2633 let outgoing = Outgoing {
2730 let outgoing = Outgoing {
2634 draft: teams_core::Draft::default(),
2731 draft: teams_core::Draft::default(),
2635 mentions: Vec::new(),
2732 mentions: Vec::new(),
2733 link_preview: None,
2636 reply: None,
2734 reply: None,
2637 edit: None,
2735 edit: None,
2638 images: vec![OutgoingImage {
2736 images: vec![OutgoingImage {
@@ -2675,6 +2773,7 @@ mod tests {
2675 super::Outgoing {
2773 super::Outgoing {
2676 draft: teams_core::Draft::plain(text),
2774 draft: teams_core::Draft::plain(text),
2677 mentions: Vec::new(),
2775 mentions: Vec::new(),
2776 link_preview: None,
2678 reply: None,
2777 reply: None,
2679 edit: None,
2778 edit: None,
2680 images,
2779 images,
@@ -3662,6 +3761,7 @@ mod tests {
3662 let draft = Outgoing {
3761 let draft = Outgoing {
3663 draft: teams_core::Draft::plain("old"),
3762 draft: teams_core::Draft::plain("old"),
3664 mentions: Vec::new(),
3763 mentions: Vec::new(),
3764 link_preview: None,
3665 reply: None,
3765 reply: None,
3666 edit: Some(EditPreview {
3766 edit: Some(EditPreview {
3667 message_id: "m1".into(),
3767 message_id: "m1".into(),
crates/app/src/views/conversation.rs +23 −5
@@ -16,7 +16,7 @@ use gpui_kit::component::{
16 16 use gpui_kit::prelude::FluentBuilder as _;
17 17 use gpui_kit::*;
18 18 use store::MessageRecord;
19 use teams_core::{FileCard, ImageRef};
19 use teams_core::{FileCard, ImageRef, LinkPreview};
20 20
21 21 use super::adaptive_card::ensure_cards_inputs;
22 22 use super::attachments::FileActions;
@@ -731,7 +731,12 @@ impl ConversationView {
731 731 .enumerate()
732 732 .filter_map(|(index, row)| match row {
733 733 Row::Message(message)
734 if message.images.iter().any(|image| keys.contains(&image.url)) =>
734 if message.images.iter().any(|image| keys.contains(&image.url))
735 || message
736 .link_preview
737 .as_ref()
738 .and_then(LinkPreview::image)
739 .is_some_and(|image| keys.contains(&image.url)) =>
735 740 {
736 741 Some(index)
737 742 }
@@ -1647,7 +1652,7 @@ impl ConversationView {
1647 1652 let Outgoing {
1648 1653 mentions, reply, ..
1649 1654 } = &sent;
1650 match (&view_mode, reply) {
1655 let record = match (&view_mode, reply) {
1651 1656 (_, Some(reply)) => {
1652 1657 engine
1653 1658 .reply_to_with_extras(
@@ -1686,8 +1691,13 @@ impl ConversationView {
1686 1691 )
1687 1692 .await
1688 1693 }
1694 }?;
1695 if let Some(preview) = &sent.link_preview {
1696 let _ = engine
1697 .attach_link_preview(&conversation_id, &record.message_id, preview)
1698 .await;
1689 1699 }
1690 .map(|_| ())
1700 Ok(())
1691 1701 });
1692 1702 cx.spawn_in(window, async move |this, cx| {
1693 1703 let result = receiver.await;
@@ -1749,6 +1759,7 @@ impl ConversationView {
1749 1759 })
1750 1760 .collect(),
1751 1761 adaptive_cards: Vec::new(),
1762 link_preview: outgoing.link_preview.clone(),
1752 1763 files: outgoing
1753 1764 .files
1754 1765 .iter()
@@ -1848,6 +1859,11 @@ impl ConversationView {
1848 1859 &outgoing.extras(),
1849 1860 )
1850 1861 .await;
1862 if let (Ok(record), Some(preview)) = (&sent, &outgoing.link_preview) {
1863 let _ = engine
1864 .attach_link_preview(&chat_id, &record.message_id, preview)
1865 .await;
1866 }
1851 1867 (Some(chat_id), sent.err().map(|error| short_error(&error)))
1852 1868 });
1853 1869 cx.spawn_in(window, async move |this, cx| {
@@ -2160,6 +2176,7 @@ impl ConversationView {
2160 2176 edit: Some(edit),
2161 2177 images: Vec::new(),
2162 2178 files: Vec::new(),
2179 link_preview: None,
2163 2180 };
2164 2181 self.composer
2165 2182 .update(cx, |composer, cx| composer.begin_edit(draft, window, cx));
@@ -2699,8 +2716,9 @@ impl Render for ConversationView {
2699 2716 let missing_images: Vec<ImageRef> = message
2700 2717 .images
2701 2718 .iter()
2702 .filter(|image| app.read(cx).directory.image(&image.url).is_none())
2703 2719 .cloned()
2720 .chain(message.link_preview.as_ref().and_then(LinkPreview::image))
2721 .filter(|image| app.read(cx).directory.image(&image.url).is_none())
2704 2722 .collect();
2705 2723 if !missing_images.is_empty() {
2706 2724 let app = app.clone();
@@ -16,7 +16,7 @@ use gpui_kit::component::{
16use gpui_kit::prelude::FluentBuilder as _;
16use gpui_kit::prelude::FluentBuilder as _;
17use gpui_kit::*;
17use gpui_kit::*;
18use store::MessageRecord;
18use store::MessageRecord;
19use teams_core::{FileCard, ImageRef};
19use teams_core::{FileCard, ImageRef, LinkPreview};
20
20
21use super::adaptive_card::ensure_cards_inputs;
21use super::adaptive_card::ensure_cards_inputs;
22use super::attachments::FileActions;
22use super::attachments::FileActions;
@@ -731,7 +731,12 @@ impl ConversationView {
731 .enumerate()
731 .enumerate()
732 .filter_map(|(index, row)| match row {
732 .filter_map(|(index, row)| match row {
733 Row::Message(message)
733 Row::Message(message)
734 if message.images.iter().any(|image| keys.contains(&image.url)) =>
734 if message.images.iter().any(|image| keys.contains(&image.url))
735 || message
736 .link_preview
737 .as_ref()
738 .and_then(LinkPreview::image)
739 .is_some_and(|image| keys.contains(&image.url)) =>
735 {
740 {
736 Some(index)
741 Some(index)
737 }
742 }
@@ -1647,7 +1652,7 @@ impl ConversationView {
1647 let Outgoing {
1652 let Outgoing {
1648 mentions, reply, ..
1653 mentions, reply, ..
1649 } = &sent;
1654 } = &sent;
1650 match (&view_mode, reply) {
1655 let record = match (&view_mode, reply) {
1651 (_, Some(reply)) => {
1656 (_, Some(reply)) => {
1652 engine
1657 engine
1653 .reply_to_with_extras(
1658 .reply_to_with_extras(
@@ -1686,8 +1691,13 @@ impl ConversationView {
1686 )
1691 )
1687 .await
1692 .await
1688 }
1693 }
1694 }?;
1695 if let Some(preview) = &sent.link_preview {
1696 let _ = engine
1697 .attach_link_preview(&conversation_id, &record.message_id, preview)
1698 .await;
1689 }
1699 }
1690 .map(|_| ())
1700 Ok(())
1691 });
1701 });
1692 cx.spawn_in(window, async move |this, cx| {
1702 cx.spawn_in(window, async move |this, cx| {
1693 let result = receiver.await;
1703 let result = receiver.await;
@@ -1749,6 +1759,7 @@ impl ConversationView {
1749 })
1759 })
1750 .collect(),
1760 .collect(),
1751 adaptive_cards: Vec::new(),
1761 adaptive_cards: Vec::new(),
1762 link_preview: outgoing.link_preview.clone(),
1752 files: outgoing
1763 files: outgoing
1753 .files
1764 .files
1754 .iter()
1765 .iter()
@@ -1848,6 +1859,11 @@ impl ConversationView {
1848 &outgoing.extras(),
1859 &outgoing.extras(),
1849 )
1860 )
1850 .await;
1861 .await;
1862 if let (Ok(record), Some(preview)) = (&sent, &outgoing.link_preview) {
1863 let _ = engine
1864 .attach_link_preview(&chat_id, &record.message_id, preview)
1865 .await;
1866 }
1851 (Some(chat_id), sent.err().map(|error| short_error(&error)))
1867 (Some(chat_id), sent.err().map(|error| short_error(&error)))
1852 });
1868 });
1853 cx.spawn_in(window, async move |this, cx| {
1869 cx.spawn_in(window, async move |this, cx| {
@@ -2160,6 +2176,7 @@ impl ConversationView {
2160 edit: Some(edit),
2176 edit: Some(edit),
2161 images: Vec::new(),
2177 images: Vec::new(),
2162 files: Vec::new(),
2178 files: Vec::new(),
2179 link_preview: None,
2163 };
2180 };
2164 self.composer
2181 self.composer
2165 .update(cx, |composer, cx| composer.begin_edit(draft, window, cx));
2182 .update(cx, |composer, cx| composer.begin_edit(draft, window, cx));
@@ -2699,8 +2716,9 @@ impl Render for ConversationView {
2699 let missing_images: Vec<ImageRef> = message
2716 let missing_images: Vec<ImageRef> = message
2700 .images
2717 .images
2701 .iter()
2718 .iter()
2702 .filter(|image| app.read(cx).directory.image(&image.url).is_none())
2703 .cloned()
2719 .cloned()
2720 .chain(message.link_preview.as_ref().and_then(LinkPreview::image))
2721 .filter(|image| app.read(cx).directory.image(&image.url).is_none())
2704 .collect();
2722 .collect();
2705 if !missing_images.is_empty() {
2723 if !missing_images.is_empty() {
2706 let app = app.clone();
2724 let app = app.clone();
crates/app/src/views/message_row.rs +19 −0
@@ -7,6 +7,7 @@ use std::time::Duration;
7 7 use super::adaptive_card::cards_view;
8 8 use super::attachments::{FileActions, attachments_view, message_body};
9 9 use super::avatar::{bot_avatar, member_stack, person_avatar};
10 use super::link_preview::link_preview_card;
10 11 use super::message_actions::{HoverChange, MessageMenu, message_toolbar};
11 12 use super::reaction_picker::PickHandler;
12 13 use super::reaction_pills::{ReactionControls, reaction_pills};
@@ -146,6 +147,15 @@ fn bubble(
146 147 directory,
147 148 extras.files.as_ref(),
148 149 ));
150 content = content.children(row.link_preview.as_ref().map(|preview| {
151 link_preview_card(
152 preview,
153 format!("message-{index}-link"),
154 directory,
155 false,
156 None,
157 )
158 }));
149 159 content = content.children(cards_view(
150 160 &row.adaptive_cards,
151 161 &row.conversation_id,
@@ -478,6 +488,15 @@ fn post_card(
478 488 directory,
479 489 files,
480 490 ));
491 body = body.children(row.link_preview.as_ref().map(|preview| {
492 link_preview_card(
493 preview,
494 format!("message-{index}-link"),
495 directory,
496 false,
497 None,
498 )
499 }));
481 500 body = body.children(cards_view(
482 501 &row.adaptive_cards,
483 502 &row.conversation_id,
@@ -7,6 +7,7 @@ use std::time::Duration;
7use super::adaptive_card::cards_view;
7use super::adaptive_card::cards_view;
8use super::attachments::{FileActions, attachments_view, message_body};
8use super::attachments::{FileActions, attachments_view, message_body};
9use super::avatar::{bot_avatar, member_stack, person_avatar};
9use super::avatar::{bot_avatar, member_stack, person_avatar};
10use super::link_preview::link_preview_card;
10use super::message_actions::{HoverChange, MessageMenu, message_toolbar};
11use super::message_actions::{HoverChange, MessageMenu, message_toolbar};
11use super::reaction_picker::PickHandler;
12use super::reaction_picker::PickHandler;
12use super::reaction_pills::{ReactionControls, reaction_pills};
13use super::reaction_pills::{ReactionControls, reaction_pills};
@@ -146,6 +147,15 @@ fn bubble(
146 directory,
147 directory,
147 extras.files.as_ref(),
148 extras.files.as_ref(),
148 ));
149 ));
150 content = content.children(row.link_preview.as_ref().map(|preview| {
151 link_preview_card(
152 preview,
153 format!("message-{index}-link"),
154 directory,
155 false,
156 None,
157 )
158 }));
149 content = content.children(cards_view(
159 content = content.children(cards_view(
150 &row.adaptive_cards,
160 &row.adaptive_cards,
151 &row.conversation_id,
161 &row.conversation_id,
@@ -478,6 +488,15 @@ fn post_card(
478 directory,
488 directory,
479 files,
489 files,
480 ));
490 ));
491 body = body.children(row.link_preview.as_ref().map(|preview| {
492 link_preview_card(
493 preview,
494 format!("message-{index}-link"),
495 directory,
496 false,
497 None,
498 )
499 }));
481 body = body.children(cards_view(
500 body = body.children(cards_view(
482 &row.adaptive_cards,
501 &row.adaptive_cards,
483 &row.conversation_id,
502 &row.conversation_id,
crates/app/src/views/mod.rs +1 −0
@@ -10,6 +10,7 @@ pub mod dialog_overlay;
10 10 pub mod draft_style;
11 11 pub mod emoji_popup;
12 12 pub mod format_toolbar;
13 pub mod link_preview;
13 14 pub mod message_actions;
14 15 pub mod message_row;
15 16 pub mod new_chat;
@@ -10,6 +10,7 @@ pub mod dialog_overlay;
10pub mod draft_style;
10pub mod draft_style;
11pub mod emoji_popup;
11pub mod emoji_popup;
12pub mod format_toolbar;
12pub mod format_toolbar;
13pub mod link_preview;
13pub mod message_actions;
14pub mod message_actions;
14pub mod message_row;
15pub mod message_row;
15pub mod new_chat;
16pub mod new_chat;
crates/chatsvc/Cargo.toml +1 −0
@@ -6,6 +6,7 @@ license.workspace = true
6 6 publish.workspace = true
7 7
8 8 [dependencies]
9 base64.workspace = true
9 10 chrono.workspace = true
10 11 futures-util.workspace = true
11 12 percent-encoding.workspace = true
@@ -6,6 +6,7 @@ license.workspace = true
6publish.workspace = true
6publish.workspace = true
7
7
8[dependencies]
8[dependencies]
9base64.workspace = true
9chrono.workspace = true
10chrono.workspace = true
10futures-util.workspace = true
11futures-util.workspace = true
11percent-encoding.workspace = true
12percent-encoding.workspace = true
crates/chatsvc/src/lib.rs +2 −0
@@ -1,6 +1,7 @@
1 1 pub mod cards;
2 2 pub mod conversations;
3 3 mod error;
4 pub mod links;
4 5 mod mask;
5 6 pub mod messages;
6 7 pub mod pins;
@@ -14,6 +15,7 @@ pub use cards::{
14 15 pub use conversations::Conversations;
15 16 pub use error::{Error, Result};
16 17 pub use mask::mask_conversation_id;
18 pub use links::{LinkImage, LinkInfo, MessageLinks, is_link_image_url};
17 19 pub use messages::{ConversationRef, Messages};
18 20 pub use pins::{
19 21 ChannelLayout, Folder, FolderKind, Folders, PinnedChannels, PinnedChats, Pins, TeamLayout,
@@ -1,6 +1,7 @@
1pub mod cards;
1pub mod cards;
2pub mod conversations;
2pub mod conversations;
3mod error;
3mod error;
4pub mod links;
4mod mask;
5mod mask;
5pub mod messages;
6pub mod messages;
6pub mod pins;
7pub mod pins;
@@ -14,6 +15,7 @@ pub use cards::{
14pub use conversations::Conversations;
15pub use conversations::Conversations;
15pub use error::{Error, Result};
16pub use error::{Error, Result};
16pub use mask::mask_conversation_id;
17pub use mask::mask_conversation_id;
18pub use links::{LinkImage, LinkInfo, MessageLinks, is_link_image_url};
17pub use messages::{ConversationRef, Messages};
19pub use messages::{ConversationRef, Messages};
18pub use pins::{
20pub use pins::{
19 ChannelLayout, Folder, FolderKind, Folders, PinnedChannels, PinnedChats, Pins, TeamLayout,
21 ChannelLayout, Folder, FolderKind, Folders, PinnedChannels, PinnedChats, Pins, TeamLayout,
crates/chatsvc/src/messages.rs +2 −2
@@ -95,8 +95,8 @@ impl MessageTransport for SessionMessageTransport {
95 95 }
96 96
97 97 pub struct Messages<T: MessageTransport = SessionMessageTransport> {
98 transport: T,
99 base_url: String,
98 pub(crate) transport: T,
99 pub(crate) base_url: String,
100 100 retry_delay: Duration,
101 101 }
102 102
@@ -95,8 +95,8 @@ impl MessageTransport for SessionMessageTransport {
95}
95}
96
96
97pub struct Messages<T: MessageTransport = SessionMessageTransport> {
97pub struct Messages<T: MessageTransport = SessionMessageTransport> {
98 transport: T,
98 pub(crate) transport: T,
99 base_url: String,
99 pub(crate) base_url: String,
100 retry_delay: Duration,
100 retry_delay: Duration,
101}
101}
102
102
crates/chatsvc/tests/messages.rs +75 −0
@@ -291,3 +291,78 @@ async fn send_typing_addresses_a_channel_reply_thread() {
291 291 format!("{BASE}/19%3Ac%40thread.tacv2%3Bmessageid%3D99/messages")
292 292 );
293 293 }
294
295 #[tokio::test]
296 async fn set_links_puts_the_array_as_a_string() {
297 let mock = Mock::new(&[200]);
298 let links = r#"[{"itemid":"0","url":"https://a.example"}]"#;
299 messages(&mock)
300 .set_links(&ConversationRef::chat("19:a@thread.v2"), "m1", links)
301 .await
302 .unwrap();
303 let requests = mock.requests();
304 assert_eq!(requests[0].method, Method::Put);
305 assert_eq!(
306 requests[0].url,
307 format!("{BASE}/19%3Aa%40thread.v2/messages/m1/properties?name=links")
308 );
309 assert_eq!(requests[0].body.as_ref().unwrap()["links"], links);
310 }
311
312 #[tokio::test]
313 async fn set_links_in_a_channel_reply_targets_the_thread_conversation() {
314 let mock = Mock::new(&[200]);
315 messages(&mock)
316 .set_links(
317 &ConversationRef::channel_reply("19:c@thread.tacv2", "root1"),
318 "r1",
319 "[]",
320 )
321 .await
322 .unwrap();
323 assert_eq!(
324 mock.requests()[0].url,
325 format!(
326 "{BASE}/19%3Ac%40thread.tacv2%3Bmessageid%3Droot1/messages/r1/properties?name=links"
327 )
328 );
329 }
330
331 #[tokio::test]
332 async fn link_info_encodes_the_url_for_the_preview_service() {
333 let mock = Mock::new(&[200]);
334 messages(&mock)
335 .link_info("https://a.example/x?y=1&z=2")
336 .await
337 .unwrap();
338 assert_eq!(mock.requests()[0].method, Method::Get);
339 assert_eq!(
340 mock.requests()[0].url,
341 "https://de-prod.asyncgw.teams.microsoft.com/urlp/v1/url/info?url=https%3A%2F%2Fa.example%2Fx%3Fy%3D1%26z%3D2"
342 );
343 }
344
345 #[tokio::test]
346 async fn link_images_outside_the_preview_service_are_refused_without_a_request() {
347 let mock = Mock::new(&[]);
348 assert!(
349 messages(&mock)
350 .link_image("https://evil.example/a.png")
351 .await
352 .is_err()
353 );
354 assert!(mock.requests().is_empty());
355 }
356
357 #[tokio::test]
358 async fn list_message_links_asks_for_the_msnp24_view() {
359 let mock = Mock::new(&[200]);
360 messages(&mock)
361 .list_message_links(&ConversationRef::channel_root("19:c@thread.tacv2"), 50)
362 .await
363 .unwrap();
364 assert_eq!(
365 mock.requests()[0].url,
366 format!("{BASE}/19%3Ac%40thread.tacv2/messages?view=msnp24Equivalent&pageSize=50")
367 );
368 }
@@ -291,3 +291,78 @@ async fn send_typing_addresses_a_channel_reply_thread() {
291 format!("{BASE}/19%3Ac%40thread.tacv2%3Bmessageid%3D99/messages")
291 format!("{BASE}/19%3Ac%40thread.tacv2%3Bmessageid%3D99/messages")
292 );
292 );
293}
293}
294
295#[tokio::test]
296async fn set_links_puts_the_array_as_a_string() {
297 let mock = Mock::new(&[200]);
298 let links = r#"[{"itemid":"0","url":"https://a.example"}]"#;
299 messages(&mock)
300 .set_links(&ConversationRef::chat("19:a@thread.v2"), "m1", links)
301 .await
302 .unwrap();
303 let requests = mock.requests();
304 assert_eq!(requests[0].method, Method::Put);
305 assert_eq!(
306 requests[0].url,
307 format!("{BASE}/19%3Aa%40thread.v2/messages/m1/properties?name=links")
308 );
309 assert_eq!(requests[0].body.as_ref().unwrap()["links"], links);
310}
311
312#[tokio::test]
313async fn set_links_in_a_channel_reply_targets_the_thread_conversation() {
314 let mock = Mock::new(&[200]);
315 messages(&mock)
316 .set_links(
317 &ConversationRef::channel_reply("19:c@thread.tacv2", "root1"),
318 "r1",
319 "[]",
320 )
321 .await
322 .unwrap();
323 assert_eq!(
324 mock.requests()[0].url,
325 format!(
326 "{BASE}/19%3Ac%40thread.tacv2%3Bmessageid%3Droot1/messages/r1/properties?name=links"
327 )
328 );
329}
330
331#[tokio::test]
332async fn link_info_encodes_the_url_for_the_preview_service() {
333 let mock = Mock::new(&[200]);
334 messages(&mock)
335 .link_info("https://a.example/x?y=1&z=2")
336 .await
337 .unwrap();
338 assert_eq!(mock.requests()[0].method, Method::Get);
339 assert_eq!(
340 mock.requests()[0].url,
341 "https://de-prod.asyncgw.teams.microsoft.com/urlp/v1/url/info?url=https%3A%2F%2Fa.example%2Fx%3Fy%3D1%26z%3D2"
342 );
343}
344
345#[tokio::test]
346async fn link_images_outside_the_preview_service_are_refused_without_a_request() {
347 let mock = Mock::new(&[]);
348 assert!(
349 messages(&mock)
350 .link_image("https://evil.example/a.png")
351 .await
352 .is_err()
353 );
354 assert!(mock.requests().is_empty());
355}
356
357#[tokio::test]
358async fn list_message_links_asks_for_the_msnp24_view() {
359 let mock = Mock::new(&[200]);
360 messages(&mock)
361 .list_message_links(&ConversationRef::channel_root("19:c@thread.tacv2"), 50)
362 .await
363 .unwrap();
364 assert_eq!(
365 mock.requests()[0].url,
366 format!("{BASE}/19%3Ac%40thread.tacv2/messages?view=msnp24Equivalent&pageSize=50")
367 );
368}
crates/core/src/actions.rs +22 −1
@@ -7,6 +7,7 @@ use store::MessageRecord;
7 7
8 8 use crate::engine::{Conversation, META_USER_ID, SyncEngine};
9 9 use crate::error::{Error, Result};
10 use crate::links::LinkPreview;
10 11 use crate::mapping::{chat_record, message_record};
11 12 use crate::markdown::markdown_to_html;
12 13 use crate::mentions::{MentionInput, apply_mentions, ensure_allowed_in_chat};
@@ -328,11 +329,31 @@ impl<R: Remote> SyncEngine<R> {
328 329 let Some(record) = message_record(conversation_id, &message) else {
329 330 return Ok(None);
330 331 };
332 let mut record = record;
331 333 let delta = self.ingest(conversation_id, vec![record.clone()])?;
332 self.announce(conversation_id, !delta.is_empty());
334 let links_changed = self.attach_links(conversation_id, &mut [&mut record]).await;
335 self.announce(conversation_id, !delta.is_empty() || links_changed);
333 336 Ok(Some(record))
334 337 }
335 338
339 pub async fn attach_link_preview(
340 &self,
341 conversation_id: &str,
342 message_id: &str,
343 preview: &LinkPreview,
344 ) -> Result<()> {
345 let target = self.message_target(conversation_id, message_id)?;
346 let links_json = preview.links_json();
347 self.remote.set_message_links(&target, &links_json).await?;
348 if self
349 .store
350 .set_message_links(conversation_id, message_id, &links_json)?
351 {
352 self.announce(conversation_id, true);
353 }
354 Ok(())
355 }
356
336 357 pub async fn mark_read(&self, conversation_id: &str) -> Result<()> {
337 358 if !matches!(self.resolve(conversation_id)?, Conversation::Chat) {
338 359 return Err(Error::Unsupported("marking a channel as read"));
@@ -7,6 +7,7 @@ use store::MessageRecord;
7
7
8use crate::engine::{Conversation, META_USER_ID, SyncEngine};
8use crate::engine::{Conversation, META_USER_ID, SyncEngine};
9use crate::error::{Error, Result};
9use crate::error::{Error, Result};
10use crate::links::LinkPreview;
10use crate::mapping::{chat_record, message_record};
11use crate::mapping::{chat_record, message_record};
11use crate::markdown::markdown_to_html;
12use crate::markdown::markdown_to_html;
12use crate::mentions::{MentionInput, apply_mentions, ensure_allowed_in_chat};
13use crate::mentions::{MentionInput, apply_mentions, ensure_allowed_in_chat};
@@ -328,11 +329,31 @@ impl<R: Remote> SyncEngine<R> {
328 let Some(record) = message_record(conversation_id, &message) else {
329 let Some(record) = message_record(conversation_id, &message) else {
329 return Ok(None);
330 return Ok(None);
330 };
331 };
332 let mut record = record;
331 let delta = self.ingest(conversation_id, vec![record.clone()])?;
333 let delta = self.ingest(conversation_id, vec![record.clone()])?;
332 self.announce(conversation_id, !delta.is_empty());
334 let links_changed = self.attach_links(conversation_id, &mut [&mut record]).await;
335 self.announce(conversation_id, !delta.is_empty() || links_changed);
333 Ok(Some(record))
336 Ok(Some(record))
334 }
337 }
335
338
339 pub async fn attach_link_preview(
340 &self,
341 conversation_id: &str,
342 message_id: &str,
343 preview: &LinkPreview,
344 ) -> Result<()> {
345 let target = self.message_target(conversation_id, message_id)?;
346 let links_json = preview.links_json();
347 self.remote.set_message_links(&target, &links_json).await?;
348 if self
349 .store
350 .set_message_links(conversation_id, message_id, &links_json)?
351 {
352 self.announce(conversation_id, true);
353 }
354 Ok(())
355 }
356
336 pub async fn mark_read(&self, conversation_id: &str) -> Result<()> {
357 pub async fn mark_read(&self, conversation_id: &str) -> Result<()> {
337 if !matches!(self.resolve(conversation_id)?, Conversation::Chat) {
358 if !matches!(self.resolve(conversation_id)?, Conversation::Chat) {
338 return Err(Error::Unsupported("marking a channel as read"));
359 return Err(Error::Unsupported("marking a channel as read"));
crates/core/src/engine.rs +17 −3
@@ -11,6 +11,7 @@ use tokio::sync::{OnceCell, broadcast};
11 11 use crate::error::{Error, Result};
12 12 use crate::events::CoreEvent;
13 13 use crate::folders::FolderSource;
14 use crate::links::{LinkPreview, has_stored_links};
14 15 use crate::mapping::{flatten_thread, message_record};
15 16 use crate::people::DirectoryCache;
16 17 use crate::presence::Presence;
@@ -123,6 +124,8 @@ pub struct SyncEngine<R: Remote = Graph> {
123 124 pub(crate) receipts: ReceiptCache,
124 125 pub(crate) channel_folders: Mutex<HashMap<String, DriveFolder>>,
125 126 pub(crate) chat_apps: Mutex<HashMap<String, Vec<ChatApp>>>,
127 pub(crate) link_previews: Mutex<HashMap<String, Option<LinkPreview>>>,
128 pub(crate) links_backfilled: Mutex<HashSet<String>>,
126 129 }
127 130
128 131 impl<R: Remote> SyncEngine<R> {
@@ -151,6 +154,8 @@ impl<R: Remote> SyncEngine<R> {
151 154 receipts: ReceiptCache::default(),
152 155 channel_folders: Mutex::new(HashMap::new()),
153 156 chat_apps: Mutex::new(HashMap::new()),
157 link_previews: Mutex::new(HashMap::new()),
158 links_backfilled: Mutex::new(HashSet::new()),
154 159 }
155 160 }
156 161
@@ -178,13 +183,15 @@ impl<R: Remote> SyncEngine<R> {
178 183 }
179 184
180 185 pub async fn fetch_newer(&self, conversation_id: &str) -> Result<Delta> {
181 let delta = match self.resolve(conversation_id)? {
186 let mut delta = match self.resolve(conversation_id)? {
182 187 Conversation::Chat => self.fetch_newer_chat(conversation_id).await?,
183 188 Conversation::Channel { team_id } => {
184 189 self.fetch_newer_channel(&team_id, conversation_id).await?
185 190 }
186 191 };
187 self.announce(conversation_id, !delta.is_empty());
192 let links_changed = self.attach_delta_links(conversation_id, &mut delta).await
193 | self.backfill_links(conversation_id).await;
194 self.announce(conversation_id, !delta.is_empty() || links_changed);
188 195 Ok(delta)
189 196 }
190 197
@@ -379,13 +386,20 @@ impl<R: Remote> SyncEngine<R> {
379 386 pub(crate) fn ingest(
380 387 &self,
381 388 conversation_id: &str,
382 records: Vec<MessageRecord>,
389 mut records: Vec<MessageRecord>,
383 390 ) -> Result<Delta> {
384 391 let ids: Vec<String> = records
385 392 .iter()
386 393 .map(|record| record.message_id.clone())
387 394 .collect();
388 395 let existing = self.store.messages_by_id(conversation_id, &ids)?;
396 for record in &mut records {
397 if let Some(cached) = existing.get(&record.message_id)
398 && !has_stored_links(&record.links_json)
399 {
400 record.links_json.clone_from(&cached.links_json);
401 }
402 }
389 403 self.store.upsert_messages(&records)?;
390 404 self.update_chat_preview(&records)?;
391 405 let mut delta = Delta::default();
@@ -11,6 +11,7 @@ use tokio::sync::{OnceCell, broadcast};
11use crate::error::{Error, Result};
11use crate::error::{Error, Result};
12use crate::events::CoreEvent;
12use crate::events::CoreEvent;
13use crate::folders::FolderSource;
13use crate::folders::FolderSource;
14use crate::links::{LinkPreview, has_stored_links};
14use crate::mapping::{flatten_thread, message_record};
15use crate::mapping::{flatten_thread, message_record};
15use crate::people::DirectoryCache;
16use crate::people::DirectoryCache;
16use crate::presence::Presence;
17use crate::presence::Presence;
@@ -123,6 +124,8 @@ pub struct SyncEngine<R: Remote = Graph> {
123 pub(crate) receipts: ReceiptCache,
124 pub(crate) receipts: ReceiptCache,
124 pub(crate) channel_folders: Mutex<HashMap<String, DriveFolder>>,
125 pub(crate) channel_folders: Mutex<HashMap<String, DriveFolder>>,
125 pub(crate) chat_apps: Mutex<HashMap<String, Vec<ChatApp>>>,
126 pub(crate) chat_apps: Mutex<HashMap<String, Vec<ChatApp>>>,
127 pub(crate) link_previews: Mutex<HashMap<String, Option<LinkPreview>>>,
128 pub(crate) links_backfilled: Mutex<HashSet<String>>,
126}
129}
127
130
128impl<R: Remote> SyncEngine<R> {
131impl<R: Remote> SyncEngine<R> {
@@ -151,6 +154,8 @@ impl<R: Remote> SyncEngine<R> {
151 receipts: ReceiptCache::default(),
154 receipts: ReceiptCache::default(),
152 channel_folders: Mutex::new(HashMap::new()),
155 channel_folders: Mutex::new(HashMap::new()),
153 chat_apps: Mutex::new(HashMap::new()),
156 chat_apps: Mutex::new(HashMap::new()),
157 link_previews: Mutex::new(HashMap::new()),
158 links_backfilled: Mutex::new(HashSet::new()),
154 }
159 }
155 }
160 }
156
161
@@ -178,13 +183,15 @@ impl<R: Remote> SyncEngine<R> {
178 }
183 }
179
184
180 pub async fn fetch_newer(&self, conversation_id: &str) -> Result<Delta> {
185 pub async fn fetch_newer(&self, conversation_id: &str) -> Result<Delta> {
181 let delta = match self.resolve(conversation_id)? {
186 let mut delta = match self.resolve(conversation_id)? {
182 Conversation::Chat => self.fetch_newer_chat(conversation_id).await?,
187 Conversation::Chat => self.fetch_newer_chat(conversation_id).await?,
183 Conversation::Channel { team_id } => {
188 Conversation::Channel { team_id } => {
184 self.fetch_newer_channel(&team_id, conversation_id).await?
189 self.fetch_newer_channel(&team_id, conversation_id).await?
185 }
190 }
186 };
191 };
187 self.announce(conversation_id, !delta.is_empty());
192 let links_changed = self.attach_delta_links(conversation_id, &mut delta).await
193 | self.backfill_links(conversation_id).await;
194 self.announce(conversation_id, !delta.is_empty() || links_changed);
188 Ok(delta)
195 Ok(delta)
189 }
196 }
190
197
@@ -379,13 +386,20 @@ impl<R: Remote> SyncEngine<R> {
379 pub(crate) fn ingest(
386 pub(crate) fn ingest(
380 &self,
387 &self,
381 conversation_id: &str,
388 conversation_id: &str,
382 records: Vec<MessageRecord>,
389 mut records: Vec<MessageRecord>,
383 ) -> Result<Delta> {
390 ) -> Result<Delta> {
384 let ids: Vec<String> = records
391 let ids: Vec<String> = records
385 .iter()
392 .iter()
386 .map(|record| record.message_id.clone())
393 .map(|record| record.message_id.clone())
387 .collect();
394 .collect();
388 let existing = self.store.messages_by_id(conversation_id, &ids)?;
395 let existing = self.store.messages_by_id(conversation_id, &ids)?;
396 for record in &mut records {
397 if let Some(cached) = existing.get(&record.message_id)
398 && !has_stored_links(&record.links_json)
399 {
400 record.links_json.clone_from(&cached.links_json);
401 }
402 }
389 self.store.upsert_messages(&records)?;
403 self.store.upsert_messages(&records)?;
390 self.update_chat_preview(&records)?;
404 self.update_chat_preview(&records)?;
391 let mut delta = Delta::default();
405 let mut delta = Delta::default();
crates/core/src/lib.rs +3 −0
@@ -12,6 +12,8 @@ mod events;
12 12 mod folders;
13 13 mod image_size;
14 14 mod images;
15 mod link_sync;
16 mod links;
15 17 mod mapping;
16 18 mod markdown;
17 19 mod mentions;
@@ -52,6 +54,7 @@ pub use graph::{
52 54 UploadedFile,
53 55 };
54 56 pub use images::StoredImage;
57 pub use links::{LinkPreview, first_public_link, is_public_link, link_preview};
55 58 pub use mapping::{chat_record, message_record};
56 59 pub use markdown::{escape_html, markdown_to_html, plain_text_to_html};
57 60 pub use mentions::MentionInput;
@@ -12,6 +12,8 @@ mod events;
12mod folders;
12mod folders;
13mod image_size;
13mod image_size;
14mod images;
14mod images;
15mod link_sync;
16mod links;
15mod mapping;
17mod mapping;
16mod markdown;
18mod markdown;
17mod mentions;
19mod mentions;
@@ -52,6 +54,7 @@ pub use graph::{
52 UploadedFile,
54 UploadedFile,
53};
55};
54pub use images::StoredImage;
56pub use images::StoredImage;
57pub use links::{LinkPreview, first_public_link, is_public_link, link_preview};
55pub use mapping::{chat_record, message_record};
58pub use mapping::{chat_record, message_record};
56pub use markdown::{escape_html, markdown_to_html, plain_text_to_html};
59pub use markdown::{escape_html, markdown_to_html, plain_text_to_html};
57pub use mentions::MentionInput;
60pub use mentions::MentionInput;
crates/core/src/mapping.rs +2 −0
@@ -3,6 +3,7 @@ use graph::{Attachment, Chat, Mention, Message, Reaction};
3 3 use store::{ChannelRecord, ChatRecord, MemberRecord, MessageRecord, TeamRecord};
4 4
5 5 use crate::adaptive_card::card_content_text;
6 use crate::links::EMPTY_LINKS;
6 7 use crate::markdown::plain_text_to_html;
7 8 use crate::preview::OwnedPreview;
8 9 use crate::stored::{AttachmentInfo, MentionInfo, QuoteInfo, ReactionInfo};
@@ -165,6 +166,7 @@ pub fn message_record(conversation_id: &str, message: &Message) -> Option<Messag
165 166 .filter_map(mention_info)
166 167 .collect::<Vec<_>>(),
167 168 ),
169 links_json: EMPTY_LINKS.to_owned(),
168 170 })
169 171 }
170 172
@@ -3,6 +3,7 @@ use graph::{Attachment, Chat, Mention, Message, Reaction};
3use store::{ChannelRecord, ChatRecord, MemberRecord, MessageRecord, TeamRecord};
3use store::{ChannelRecord, ChatRecord, MemberRecord, MessageRecord, TeamRecord};
4
4
5use crate::adaptive_card::card_content_text;
5use crate::adaptive_card::card_content_text;
6use crate::links::EMPTY_LINKS;
6use crate::markdown::plain_text_to_html;
7use crate::markdown::plain_text_to_html;
7use crate::preview::OwnedPreview;
8use crate::preview::OwnedPreview;
8use crate::stored::{AttachmentInfo, MentionInfo, QuoteInfo, ReactionInfo};
9use crate::stored::{AttachmentInfo, MentionInfo, QuoteInfo, ReactionInfo};
@@ -165,6 +166,7 @@ pub fn message_record(conversation_id: &str, message: &Message) -> Option<Messag
165 .filter_map(mention_info)
166 .filter_map(mention_info)
166 .collect::<Vec<_>>(),
167 .collect::<Vec<_>>(),
167 ),
168 ),
169 links_json: EMPTY_LINKS.to_owned(),
168 })
170 })
169}
171}
170
172
crates/core/src/remote.rs +45 −2
@@ -1,6 +1,6 @@
1 1 use chatsvc::{
2 CardActions, ChatApp, ConversationRef, Conversations, InvokeRequest, InvokeResponse,
3 MemberHorizon, Messages, Receipts,
2 CardActions, ChatApp, ConversationRef, Conversations, InvokeRequest, InvokeResponse, LinkInfo,
3 MemberHorizon, MessageLinks, Messages, Receipts,
4 4 };
5 5 use chrono::{DateTime, Utc};
6 6 use graph::{
@@ -217,6 +217,22 @@ pub trait Remote {
217 217 async fn invoke_card(&self, _invoke: InvokeRequest) -> Result<InvokeResponse> {
218 218 Err(Error::Unsupported("card actions"))
219 219 }
220
221 async fn message_links(
222 &self,
223 _conversation: &ConversationRef,
224 _page_size: usize,
225 ) -> Result<Vec<MessageLinks>> {
226 Err(Error::Unsupported("link previews"))
227 }
228
229 async fn set_message_links(&self, _target: &MessageTarget, _links_json: &str) -> Result<()> {
230 Err(Error::Unsupported("link previews"))
231 }
232
233 async fn link_info(&self, _url: &str) -> Result<LinkInfo> {
234 Err(Error::Unsupported("link previews"))
235 }
220 236 }
221 237
222 238 impl Remote for Graph {
@@ -531,6 +547,13 @@ impl Remote for Graph {
531 547 }
532 548
533 549 async fn hosted_content(&self, url: &str) -> Result<Photo> {
550 if chatsvc::is_link_image_url(url) {
551 let image = Messages::new(self.session()).link_image(url).await?;
552 return Ok(Photo {
553 bytes: image.bytes,
554 content_type: image.content_type,
555 });
556 }
534 557 Ok(Graph::download_hosted_content(self, url).await?)
535 558 }
536 559
@@ -569,6 +592,26 @@ impl Remote for Graph {
569 592 async fn invoke_card(&self, invoke: InvokeRequest) -> Result<InvokeResponse> {
570 593 Ok(CardActions::new(self.session()).invoke(invoke).await?)
571 594 }
595
596 async fn message_links(
597 &self,
598 conversation: &ConversationRef,
599 page_size: usize,
600 ) -> Result<Vec<MessageLinks>> {
601 Ok(Messages::new(self.session())
602 .list_message_links(conversation, page_size)
603 .await?)
604 }
605
606 async fn set_message_links(&self, target: &MessageTarget, links_json: &str) -> Result<()> {
607 Ok(Messages::new(self.session())
608 .set_links(&conversation_ref(target), target.message_id(), links_json)
609 .await?)
610 }
611
612 async fn link_info(&self, url: &str) -> Result<LinkInfo> {
613 Ok(Messages::new(self.session()).link_info(url).await?)
614 }
572 615 }
573 616
574 617 fn chatsvc_conversation(target: &MessageTarget) -> Option<ConversationRef> {
@@ -1,6 +1,6 @@
1use chatsvc::{
1use chatsvc::{
2 CardActions, ChatApp, ConversationRef, Conversations, InvokeRequest, InvokeResponse,
2 CardActions, ChatApp, ConversationRef, Conversations, InvokeRequest, InvokeResponse, LinkInfo,
3 MemberHorizon, Messages, Receipts,
3 MemberHorizon, MessageLinks, Messages, Receipts,
4};
4};
5use chrono::{DateTime, Utc};
5use chrono::{DateTime, Utc};
6use graph::{
6use graph::{
@@ -217,6 +217,22 @@ pub trait Remote {
217 async fn invoke_card(&self, _invoke: InvokeRequest) -> Result<InvokeResponse> {
217 async fn invoke_card(&self, _invoke: InvokeRequest) -> Result<InvokeResponse> {
218 Err(Error::Unsupported("card actions"))
218 Err(Error::Unsupported("card actions"))
219 }
219 }
220
221 async fn message_links(
222 &self,
223 _conversation: &ConversationRef,
224 _page_size: usize,
225 ) -> Result<Vec<MessageLinks>> {
226 Err(Error::Unsupported("link previews"))
227 }
228
229 async fn set_message_links(&self, _target: &MessageTarget, _links_json: &str) -> Result<()> {
230 Err(Error::Unsupported("link previews"))
231 }
232
233 async fn link_info(&self, _url: &str) -> Result<LinkInfo> {
234 Err(Error::Unsupported("link previews"))
235 }
220}
236}
221
237
222impl Remote for Graph {
238impl Remote for Graph {
@@ -531,6 +547,13 @@ impl Remote for Graph {
531 }
547 }
532
548
533 async fn hosted_content(&self, url: &str) -> Result<Photo> {
549 async fn hosted_content(&self, url: &str) -> Result<Photo> {
550 if chatsvc::is_link_image_url(url) {
551 let image = Messages::new(self.session()).link_image(url).await?;
552 return Ok(Photo {
553 bytes: image.bytes,
554 content_type: image.content_type,
555 });
556 }
534 Ok(Graph::download_hosted_content(self, url).await?)
557 Ok(Graph::download_hosted_content(self, url).await?)
535 }
558 }
536
559
@@ -569,6 +592,26 @@ impl Remote for Graph {
569 async fn invoke_card(&self, invoke: InvokeRequest) -> Result<InvokeResponse> {
592 async fn invoke_card(&self, invoke: InvokeRequest) -> Result<InvokeResponse> {
570 Ok(CardActions::new(self.session()).invoke(invoke).await?)
593 Ok(CardActions::new(self.session()).invoke(invoke).await?)
571 }
594 }
595
596 async fn message_links(
597 &self,
598 conversation: &ConversationRef,
599 page_size: usize,
600 ) -> Result<Vec<MessageLinks>> {
601 Ok(Messages::new(self.session())
602 .list_message_links(conversation, page_size)
603 .await?)
604 }
605
606 async fn set_message_links(&self, target: &MessageTarget, links_json: &str) -> Result<()> {
607 Ok(Messages::new(self.session())
608 .set_links(&conversation_ref(target), target.message_id(), links_json)
609 .await?)
610 }
611
612 async fn link_info(&self, url: &str) -> Result<LinkInfo> {
613 Ok(Messages::new(self.session()).link_info(url).await?)
614 }
572}
615}
573
616
574fn chatsvc_conversation(target: &MessageTarget) -> Option<ConversationRef> {
617fn chatsvc_conversation(target: &MessageTarget) -> Option<ConversationRef> {
crates/core/src/stored.rs +1 −0
@@ -597,6 +597,7 @@ mod tests {
597 597 sender_id: Some("u".to_owned()),
598 598 sender_name: None,
599 599 sender_application_id: None,
600 links_json: "[]".to_owned(),
600 601 created_at: Utc::now(),
601 602 edited_at: None,
602 603 deleted: false,
@@ -597,6 +597,7 @@ mod tests {
597 sender_id: Some("u".to_owned()),
597 sender_id: Some("u".to_owned()),
598 sender_name: None,
598 sender_name: None,
599 sender_application_id: None,
599 sender_application_id: None,
600 links_json: "[]".to_owned(),
600 created_at: Utc::now(),
601 created_at: Utc::now(),
601 edited_at: None,
602 edited_at: None,
602 deleted: false,
603 deleted: false,
crates/core/tests/engine.rs +134 −0
@@ -94,6 +94,10 @@ struct Fake {
94 94 invoke_answer: Mutex<Option<chatsvc::InvokeResponse>>,
95 95 muted_states: Mutex<Vec<(String, bool)>>,
96 96 muted_fails: Mutex<bool>,
97 link_pages: Mutex<Vec<chatsvc::MessageLinks>>,
98 link_page_calls: Mutex<Vec<String>>,
99 links_put: Mutex<Vec<(String, String)>>,
100 link_info_calls: Mutex<usize>,
97 101 }
98 102
99 103 impl Fake {
@@ -625,6 +629,35 @@ impl Remote for Handle {
625 629 .unwrap_or(chatsvc::InvokeResponse::Empty))
626 630 }
627 631
632 async fn message_links(
633 &self,
634 conversation: &chatsvc::ConversationRef,
635 _page_size: usize,
636 ) -> Result<Vec<chatsvc::MessageLinks>> {
637 self.link_page_calls
638 .lock()
639 .unwrap()
640 .push(conversation.conversation_id());
641 Ok(self.link_pages.lock().unwrap().clone())
642 }
643
644 async fn set_message_links(&self, target: &MessageTarget, links_json: &str) -> Result<()> {
645 self.links_put
646 .lock()
647 .unwrap()
648 .push((describe(target), links_json.to_owned()));
649 Ok(())
650 }
651
652 async fn link_info(&self, url: &str) -> Result<chatsvc::LinkInfo> {
653 *self.link_info_calls.lock().unwrap() += 1;
654 Ok(chatsvc::LinkInfo {
655 url: url.to_owned(),
656 title: Some("Example".into()),
657 ..chatsvc::LinkInfo::default()
658 })
659 }
660
628 661 async fn presences(&self, user_ids: &[String]) -> Result<Vec<Presence>> {
629 662 let answers = self.presence_answers.lock().unwrap();
630 663 Ok(answers
@@ -3055,3 +3088,104 @@ async fn bot_messages_remember_their_application() {
3055 3088 assert_eq!(record.sender_application_id.as_deref(), Some(BOT_GUID));
3056 3089 assert_eq!(record.sender_id, None);
3057 3090 }
3091
3092 const PREVIEW_LINKS: &str =
3093 r#"[{"url":"https://a.example/x","preview":{"title":"Example"},"previewenabled":true}]"#;
3094
3095 #[tokio::test]
3096 async fn links_from_the_chat_service_survive_the_next_graph_sync() {
3097 let fake = Arc::new(Fake::default());
3098 let engine = chat_engine(&fake, small_pages()).await;
3099 fake.set_chat_messages(vec![message(
3100 1,
3101 1,
3102 "<p><a href=\"https://a.example/x\">link</a></p>",
3103 )]);
3104 *fake.link_pages.lock().unwrap() = vec![chatsvc::MessageLinks {
3105 message_id: "m0001".into(),
3106 links_json: PREVIEW_LINKS.into(),
3107 }];
3108
3109 let delta = engine.fetch_newer(CHAT).await.unwrap();
3110 assert_eq!(delta.added[0].links_json, PREVIEW_LINKS);
3111 assert_eq!(
3112 engine.open_conversation(CHAT).unwrap()[0].links_json,
3113 PREVIEW_LINKS
3114 );
3115 assert_eq!(*fake.link_page_calls.lock().unwrap(), [CHAT]);
3116
3117 let again = engine.fetch_newer(CHAT).await.unwrap();
3118 assert!(again.is_empty());
3119 assert_eq!(
3120 engine.open_conversation(CHAT).unwrap()[0].links_json,
3121 PREVIEW_LINKS
3122 );
3123 }
3124
3125 #[tokio::test]
3126 async fn messages_without_anchors_do_not_ask_the_chat_service() {
3127 let fake = Arc::new(Fake::default());
3128 let engine = chat_engine(&fake, small_pages()).await;
3129 fake.set_chat_messages(vec![message(1, 1, "<p>plain</p>")]);
3130 engine.fetch_newer(CHAT).await.unwrap();
3131 assert!(fake.link_page_calls.lock().unwrap().is_empty());
3132 }
3133
3134 #[tokio::test]
3135 async fn a_failing_chat_service_leaves_no_preview() {
3136 let fake = Arc::new(Fake::default());
3137 let engine = chat_engine(&fake, small_pages()).await;
3138 fake.set_chat_messages(vec![message(1, 1, "<a href=\"https://a.example\">x</a>")]);
3139 let delta = engine.fetch_newer(CHAT).await.unwrap();
3140 assert_eq!(delta.added[0].links_json, "[]");
3141 }
3142
3143 #[tokio::test]
3144 async fn attaching_a_preview_puts_the_links_and_keeps_them_locally() {
3145 let fake = Arc::new(Fake::default());
3146 let engine = chat_engine(&fake, small_pages()).await;
3147 let sent = engine
3148 .send_message_with_mentions(CHAT, "see https://a.example/x", None, &[])
3149 .await
3150 .unwrap();
3151 let preview = engine
3152 .link_preview_for("https://a.example/x")
3153 .await
3154 .unwrap()
3155 .unwrap();
3156
3157 engine
3158 .attach_link_preview(CHAT, &sent.message_id, &preview)
3159 .await
3160 .unwrap();
3161
3162 let put = fake.links_put.lock().unwrap().clone();
3163 assert_eq!(put.len(), 1);
3164 assert_eq!(put[0].0, sent.message_id);
3165 assert!(put[0].1.contains("\"itemid\":\"0\""));
3166 let stored = engine
3167 .store()
3168 .messages_by_id(CHAT, std::slice::from_ref(&sent.message_id))
3169 .unwrap();
3170 assert_eq!(stored[&sent.message_id].links_json, put[0].1);
3171 }
3172
3173 #[tokio::test]
3174 async fn link_infos_are_fetched_once_per_url_and_internal_links_never() {
3175 let fake = Arc::new(Fake::default());
3176 let engine = chat_engine(&fake, small_pages()).await;
3177 for _ in 0..2 {
3178 engine
3179 .link_preview_for("https://a.example/x")
3180 .await
3181 .unwrap();
3182 }
3183 assert!(
3184 engine
3185 .link_preview_for("https://contoso.sharepoint.com/x")
3186 .await
3187 .unwrap()
3188 .is_none()
3189 );
3190 assert_eq!(*fake.link_info_calls.lock().unwrap(), 1);
3191 }
@@ -94,6 +94,10 @@ struct Fake {
94 invoke_answer: Mutex<Option<chatsvc::InvokeResponse>>,
94 invoke_answer: Mutex<Option<chatsvc::InvokeResponse>>,
95 muted_states: Mutex<Vec<(String, bool)>>,
95 muted_states: Mutex<Vec<(String, bool)>>,
96 muted_fails: Mutex<bool>,
96 muted_fails: Mutex<bool>,
97 link_pages: Mutex<Vec<chatsvc::MessageLinks>>,
98 link_page_calls: Mutex<Vec<String>>,
99 links_put: Mutex<Vec<(String, String)>>,
100 link_info_calls: Mutex<usize>,
97}
101}
98
102
99impl Fake {
103impl Fake {
@@ -625,6 +629,35 @@ impl Remote for Handle {
625 .unwrap_or(chatsvc::InvokeResponse::Empty))
629 .unwrap_or(chatsvc::InvokeResponse::Empty))
626 }
630 }
627
631
632 async fn message_links(
633 &self,
634 conversation: &chatsvc::ConversationRef,
635 _page_size: usize,
636 ) -> Result<Vec<chatsvc::MessageLinks>> {
637 self.link_page_calls
638 .lock()
639 .unwrap()
640 .push(conversation.conversation_id());
641 Ok(self.link_pages.lock().unwrap().clone())
642 }
643
644 async fn set_message_links(&self, target: &MessageTarget, links_json: &str) -> Result<()> {
645 self.links_put
646 .lock()
647 .unwrap()
648 .push((describe(target), links_json.to_owned()));
649 Ok(())
650 }
651
652 async fn link_info(&self, url: &str) -> Result<chatsvc::LinkInfo> {
653 *self.link_info_calls.lock().unwrap() += 1;
654 Ok(chatsvc::LinkInfo {
655 url: url.to_owned(),
656 title: Some("Example".into()),
657 ..chatsvc::LinkInfo::default()
658 })
659 }
660
628 async fn presences(&self, user_ids: &[String]) -> Result<Vec<Presence>> {
661 async fn presences(&self, user_ids: &[String]) -> Result<Vec<Presence>> {
629 let answers = self.presence_answers.lock().unwrap();
662 let answers = self.presence_answers.lock().unwrap();
630 Ok(answers
663 Ok(answers
@@ -3055,3 +3088,104 @@ async fn bot_messages_remember_their_application() {
3055 assert_eq!(record.sender_application_id.as_deref(), Some(BOT_GUID));
3088 assert_eq!(record.sender_application_id.as_deref(), Some(BOT_GUID));
3056 assert_eq!(record.sender_id, None);
3089 assert_eq!(record.sender_id, None);
3057}
3090}
3091
3092const PREVIEW_LINKS: &str =
3093 r#"[{"url":"https://a.example/x","preview":{"title":"Example"},"previewenabled":true}]"#;
3094
3095#[tokio::test]
3096async fn links_from_the_chat_service_survive_the_next_graph_sync() {
3097 let fake = Arc::new(Fake::default());
3098 let engine = chat_engine(&fake, small_pages()).await;
3099 fake.set_chat_messages(vec![message(
3100 1,
3101 1,
3102 "<p><a href=\"https://a.example/x\">link</a></p>",
3103 )]);
3104 *fake.link_pages.lock().unwrap() = vec![chatsvc::MessageLinks {
3105 message_id: "m0001".into(),
3106 links_json: PREVIEW_LINKS.into(),
3107 }];
3108
3109 let delta = engine.fetch_newer(CHAT).await.unwrap();
3110 assert_eq!(delta.added[0].links_json, PREVIEW_LINKS);
3111 assert_eq!(
3112 engine.open_conversation(CHAT).unwrap()[0].links_json,
3113 PREVIEW_LINKS
3114 );
3115 assert_eq!(*fake.link_page_calls.lock().unwrap(), [CHAT]);
3116
3117 let again = engine.fetch_newer(CHAT).await.unwrap();
3118 assert!(again.is_empty());
3119 assert_eq!(
3120 engine.open_conversation(CHAT).unwrap()[0].links_json,
3121 PREVIEW_LINKS
3122 );
3123}
3124
3125#[tokio::test]
3126async fn messages_without_anchors_do_not_ask_the_chat_service() {
3127 let fake = Arc::new(Fake::default());
3128 let engine = chat_engine(&fake, small_pages()).await;
3129 fake.set_chat_messages(vec![message(1, 1, "<p>plain</p>")]);
3130 engine.fetch_newer(CHAT).await.unwrap();
3131 assert!(fake.link_page_calls.lock().unwrap().is_empty());
3132}
3133
3134#[tokio::test]
3135async fn a_failing_chat_service_leaves_no_preview() {
3136 let fake = Arc::new(Fake::default());
3137 let engine = chat_engine(&fake, small_pages()).await;
3138 fake.set_chat_messages(vec![message(1, 1, "<a href=\"https://a.example\">x</a>")]);
3139 let delta = engine.fetch_newer(CHAT).await.unwrap();
3140 assert_eq!(delta.added[0].links_json, "[]");
3141}
3142
3143#[tokio::test]
3144async fn attaching_a_preview_puts_the_links_and_keeps_them_locally() {
3145 let fake = Arc::new(Fake::default());
3146 let engine = chat_engine(&fake, small_pages()).await;
3147 let sent = engine
3148 .send_message_with_mentions(CHAT, "see https://a.example/x", None, &[])
3149 .await
3150 .unwrap();
3151 let preview = engine
3152 .link_preview_for("https://a.example/x")
3153 .await
3154 .unwrap()
3155 .unwrap();
3156
3157 engine
3158 .attach_link_preview(CHAT, &sent.message_id, &preview)
3159 .await
3160 .unwrap();
3161
3162 let put = fake.links_put.lock().unwrap().clone();
3163 assert_eq!(put.len(), 1);
3164 assert_eq!(put[0].0, sent.message_id);
3165 assert!(put[0].1.contains("\"itemid\":\"0\""));
3166 let stored = engine
3167 .store()
3168 .messages_by_id(CHAT, std::slice::from_ref(&sent.message_id))
3169 .unwrap();
3170 assert_eq!(stored[&sent.message_id].links_json, put[0].1);
3171}
3172
3173#[tokio::test]
3174async fn link_infos_are_fetched_once_per_url_and_internal_links_never() {
3175 let fake = Arc::new(Fake::default());
3176 let engine = chat_engine(&fake, small_pages()).await;
3177 for _ in 0..2 {
3178 engine
3179 .link_preview_for("https://a.example/x")
3180 .await
3181 .unwrap();
3182 }
3183 assert!(
3184 engine
3185 .link_preview_for("https://contoso.sharepoint.com/x")
3186 .await
3187 .unwrap()
3188 .is_none()
3189 );
3190 assert_eq!(*fake.link_info_calls.lock().unwrap(), 1);
3191}
crates/core/tests/spans.rs +1 −0
@@ -364,6 +364,7 @@ fn record_with(body_html: &str, attachments_json: &str) -> MessageRecord {
364 364 sender_id: None,
365 365 sender_name: None,
366 366 sender_application_id: None,
367 links_json: "[]".to_owned(),
367 368 created_at: chrono::DateTime::from_timestamp(1_700_000_000, 0).unwrap(),
368 369 edited_at: None,
369 370 deleted: false,
@@ -364,6 +364,7 @@ fn record_with(body_html: &str, attachments_json: &str) -> MessageRecord {
364 sender_id: None,
364 sender_id: None,
365 sender_name: None,
365 sender_name: None,
366 sender_application_id: None,
366 sender_application_id: None,
367 links_json: "[]".to_owned(),
367 created_at: chrono::DateTime::from_timestamp(1_700_000_000, 0).unwrap(),
368 created_at: chrono::DateTime::from_timestamp(1_700_000_000, 0).unwrap(),
368 edited_at: None,
369 edited_at: None,
369 deleted: false,
370 deleted: false,
crates/store/src/messages.rs +22 −3
@@ -10,7 +10,7 @@ use crate::store::Store;
10 10 use crate::time::{from_millis, optional_from_millis, optional_to_millis, to_millis};
11 11
12 12 const MESSAGE_COLUMNS: &str = "conversation_id, message_id, reply_to_id, sender_id, sender_name, created_at, \
13 edited_at, deleted, body_html, attachments_json, reactions_json, mentions_json, sender_application_id";
13 edited_at, deleted, body_html, attachments_json, reactions_json, mentions_json, sender_application_id, links_json";
14 14
15 15 impl Store {
16 16 pub fn upsert_messages(&self, messages: &[MessageRecord]) -> Result<()> {
@@ -19,14 +19,16 @@ impl Store {
19 19 {
20 20 let mut upsert = transaction.prepare_cached(&format!(
21 21 "INSERT INTO messages ({MESSAGE_COLUMNS})
22 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13)
22 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14)
23 23 ON CONFLICT (conversation_id, message_id) DO UPDATE SET
24 24 reply_to_id = excluded.reply_to_id, sender_id = excluded.sender_id,
25 25 sender_name = excluded.sender_name, created_at = excluded.created_at,
26 26 edited_at = excluded.edited_at, deleted = excluded.deleted, body_html = excluded.body_html,
27 27 attachments_json = excluded.attachments_json, reactions_json = excluded.reactions_json,
28 28 mentions_json = excluded.mentions_json,
29 sender_application_id = excluded.sender_application_id"
29 sender_application_id = excluded.sender_application_id,
30 links_json = CASE WHEN excluded.links_json IN ('', '[]')
31 THEN messages.links_json ELSE excluded.links_json END"
30 32 ))?;
31 33 for message in messages {
32 34 upsert.execute(params![
@@ -43,6 +45,7 @@ impl Store {
43 45 message.reactions_json,
44 46 message.mentions_json,
45 47 message.sender_application_id,
48 message.links_json,
46 49 ])?;
47 50 index_message(&transaction, message)?;
48 51 }
@@ -50,6 +53,21 @@ impl Store {
50 53 Ok(transaction.commit()?)
51 54 }
52 55
56 pub fn set_message_links(
57 &self,
58 conversation_id: &str,
59 message_id: &str,
60 links_json: &str,
61 ) -> Result<bool> {
62 let connection = self.lock()?;
63 let changed = connection.execute(
64 "UPDATE messages SET links_json = ?3
65 WHERE conversation_id = ?1 AND message_id = ?2 AND links_json <> ?3",
66 params![conversation_id, message_id, links_json],
67 )?;
68 Ok(changed > 0)
69 }
70
53 71 pub fn count_messages_after(
54 72 &self,
55 73 conversation_id: &str,
@@ -210,5 +228,6 @@ fn message_from_row(row: &Row<'_>) -> rusqlite::Result<MessageRecord> {
210 228 reactions_json: row.get(10)?,
211 229 mentions_json: row.get(11)?,
212 230 sender_application_id: row.get(12)?,
231 links_json: row.get(13)?,
213 232 })
214 233 }
@@ -10,7 +10,7 @@ use crate::store::Store;
10use crate::time::{from_millis, optional_from_millis, optional_to_millis, to_millis};
10use crate::time::{from_millis, optional_from_millis, optional_to_millis, to_millis};
11
11
12const MESSAGE_COLUMNS: &str = "conversation_id, message_id, reply_to_id, sender_id, sender_name, created_at, \
12const MESSAGE_COLUMNS: &str = "conversation_id, message_id, reply_to_id, sender_id, sender_name, created_at, \
13 edited_at, deleted, body_html, attachments_json, reactions_json, mentions_json, sender_application_id";
13 edited_at, deleted, body_html, attachments_json, reactions_json, mentions_json, sender_application_id, links_json";
14
14
15impl Store {
15impl Store {
16 pub fn upsert_messages(&self, messages: &[MessageRecord]) -> Result<()> {
16 pub fn upsert_messages(&self, messages: &[MessageRecord]) -> Result<()> {
@@ -19,14 +19,16 @@ impl Store {
19 {
19 {
20 let mut upsert = transaction.prepare_cached(&format!(
20 let mut upsert = transaction.prepare_cached(&format!(
21 "INSERT INTO messages ({MESSAGE_COLUMNS})
21 "INSERT INTO messages ({MESSAGE_COLUMNS})
22 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13)
22 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14)
23 ON CONFLICT (conversation_id, message_id) DO UPDATE SET
23 ON CONFLICT (conversation_id, message_id) DO UPDATE SET
24 reply_to_id = excluded.reply_to_id, sender_id = excluded.sender_id,
24 reply_to_id = excluded.reply_to_id, sender_id = excluded.sender_id,
25 sender_name = excluded.sender_name, created_at = excluded.created_at,
25 sender_name = excluded.sender_name, created_at = excluded.created_at,
26 edited_at = excluded.edited_at, deleted = excluded.deleted, body_html = excluded.body_html,
26 edited_at = excluded.edited_at, deleted = excluded.deleted, body_html = excluded.body_html,
27 attachments_json = excluded.attachments_json, reactions_json = excluded.reactions_json,
27 attachments_json = excluded.attachments_json, reactions_json = excluded.reactions_json,
28 mentions_json = excluded.mentions_json,
28 mentions_json = excluded.mentions_json,
29 sender_application_id = excluded.sender_application_id"
29 sender_application_id = excluded.sender_application_id,
30 links_json = CASE WHEN excluded.links_json IN ('', '[]')
31 THEN messages.links_json ELSE excluded.links_json END"
30 ))?;
32 ))?;
31 for message in messages {
33 for message in messages {
32 upsert.execute(params![
34 upsert.execute(params![
@@ -43,6 +45,7 @@ impl Store {
43 message.reactions_json,
45 message.reactions_json,
44 message.mentions_json,
46 message.mentions_json,
45 message.sender_application_id,
47 message.sender_application_id,
48 message.links_json,
46 ])?;
49 ])?;
47 index_message(&transaction, message)?;
50 index_message(&transaction, message)?;
48 }
51 }
@@ -50,6 +53,21 @@ impl Store {
50 Ok(transaction.commit()?)
53 Ok(transaction.commit()?)
51 }
54 }
52
55
56 pub fn set_message_links(
57 &self,
58 conversation_id: &str,
59 message_id: &str,
60 links_json: &str,
61 ) -> Result<bool> {
62 let connection = self.lock()?;
63 let changed = connection.execute(
64 "UPDATE messages SET links_json = ?3
65 WHERE conversation_id = ?1 AND message_id = ?2 AND links_json <> ?3",
66 params![conversation_id, message_id, links_json],
67 )?;
68 Ok(changed > 0)
69 }
70
53 pub fn count_messages_after(
71 pub fn count_messages_after(
54 &self,
72 &self,
55 conversation_id: &str,
73 conversation_id: &str,
@@ -210,5 +228,6 @@ fn message_from_row(row: &Row<'_>) -> rusqlite::Result<MessageRecord> {
210 reactions_json: row.get(10)?,
228 reactions_json: row.get(10)?,
211 mentions_json: row.get(11)?,
229 mentions_json: row.get(11)?,
212 sender_application_id: row.get(12)?,
230 sender_application_id: row.get(12)?,
231 links_json: row.get(13)?,
213 })
232 })
214}
233}
crates/store/src/migrations.rs +4 −0
@@ -49,6 +49,10 @@ const MIGRATIONS: &[Migration] = &[
49 49 script: include_str!("migrations/0010_name_lookup_indexes.sql"),
50 50 after: None,
51 51 },
52 Migration {
53 script: include_str!("migrations/0011_message_links.sql"),
54 after: None,
55 },
52 56 ];
53 57
54 58 pub fn latest_version() -> i64 {
@@ -49,6 +49,10 @@ const MIGRATIONS: &[Migration] = &[
49 script: include_str!("migrations/0010_name_lookup_indexes.sql"),
49 script: include_str!("migrations/0010_name_lookup_indexes.sql"),
50 after: None,
50 after: None,
51 },
51 },
52 Migration {
53 script: include_str!("migrations/0011_message_links.sql"),
54 after: None,
55 },
52];
56];
53
57
54pub fn latest_version() -> i64 {
58pub fn latest_version() -> i64 {
crates/store/src/models.rs +1 −0
@@ -71,6 +71,7 @@ pub struct MessageRecord {
71 71 pub reactions_json: String,
72 72 pub mentions_json: String,
73 73 pub sender_application_id: Option<String>,
74 pub links_json: String,
74 75 }
75 76
76 77 #[derive(Debug, Clone, PartialEq)]
@@ -71,6 +71,7 @@ pub struct MessageRecord {
71 pub reactions_json: String,
71 pub reactions_json: String,
72 pub mentions_json: String,
72 pub mentions_json: String,
73 pub sender_application_id: Option<String>,
73 pub sender_application_id: Option<String>,
74 pub links_json: String,
74}
75}
75
76
76#[derive(Debug, Clone, PartialEq)]
77#[derive(Debug, Clone, PartialEq)]
crates/store/tests/store.rs +40 −4
@@ -64,6 +64,7 @@ fn message(conversation_id: &str, message_id: &str, minute: u32) -> MessageRecor
64 64 reactions_json: "[]".to_owned(),
65 65 mentions_json: "[]".to_owned(),
66 66 sender_application_id: None,
67 links_json: "[]".to_owned(),
67 68 }
68 69 }
69 70
@@ -81,6 +82,40 @@ fn sender_application_round_trips() {
81 82 assert_eq!(found["m1"], bot_message);
82 83 }
83 84
85 #[test]
86 fn an_upsert_without_links_keeps_the_stored_links() {
87 let store = Store::open_in_memory().unwrap();
88 store.upsert_messages(&[message("c1", "m1", 1)]).unwrap();
89 let links = r#"[{"url":"https://a.example"}]"#;
90 assert!(store.set_message_links("c1", "m1", links).unwrap());
91 assert!(!store.set_message_links("c1", "m1", links).unwrap());
92
93 let edited = MessageRecord {
94 body_html: "<p>edited</p>".to_owned(),
95 ..message("c1", "m1", 1)
96 };
97 store.upsert_messages(&[edited]).unwrap();
98 let found = store.messages_by_id("c1", &["m1".to_owned()]).unwrap();
99 assert_eq!(found["m1"].links_json, links);
100 assert_eq!(found["m1"].body_html, "<p>edited</p>");
101
102 let replaced = MessageRecord {
103 links_json: r#"[{"url":"https://b.example"}]"#.to_owned(),
104 ..message("c1", "m1", 1)
105 };
106 store.upsert_messages(std::slice::from_ref(&replaced)).unwrap();
107 let found = store.messages_by_id("c1", &["m1".to_owned()]).unwrap();
108 assert_eq!(found["m1"].links_json, replaced.links_json);
109 }
110
111 #[test]
112 fn new_messages_start_without_links() {
113 let store = Store::open_in_memory().unwrap();
114 store.upsert_messages(&[message("c1", "m1", 1)]).unwrap();
115 let found = store.messages_by_id("c1", &["m1".to_owned()]).unwrap();
116 assert_eq!(found["m1"].links_json, "[]");
117 }
118
84 119 fn ids(messages: &[MessageRecord]) -> Vec<&str> {
85 120 messages
86 121 .iter()
@@ -395,11 +430,11 @@ fn file_database_uses_wal_persists_and_migrates_once() {
395 430 let path = directory.path().join("nested").join("cache.sqlite3");
396 431 {
397 432 let store = Store::open(&path).unwrap();
398 assert_eq!(store.schema_version().unwrap(), 10);
433 assert_eq!(store.schema_version().unwrap(), 11);
399 434 store.upsert_messages(&[message("c", "m1", 1)]).unwrap();
400 435 }
401 436 let reopened = Store::open(&path).unwrap();
402 assert_eq!(reopened.schema_version().unwrap(), 10);
437 assert_eq!(reopened.schema_version().unwrap(), 11);
403 438 assert_eq!(reopened.message_count("c").unwrap(), 1);
404 439 drop(reopened);
405 440 let mode: String = rusqlite_open(&path)
@@ -431,7 +466,7 @@ fn old_schema_is_upgraded_in_place() {
431 466 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 presence; DROP TABLE activity; PRAGMA user_version = 0").unwrap();
432 467 drop(connection);
433 468 let store = Store::open(&path).unwrap();
434 assert_eq!(store.schema_version().unwrap(), 10);
469 assert_eq!(store.schema_version().unwrap(), 11);
435 470 store.upsert_messages(&[message("c", "m1", 1)]).unwrap();
436 471 }
437 472
@@ -497,7 +532,7 @@ fn migration_to_v2_keeps_existing_sync_state() {
497 532 let store = Store::open(&path).unwrap();
498 533 let state = store.sync_state("c").unwrap().unwrap();
499 534 assert_eq!(state.delta_link, None);
500 assert_eq!(store.schema_version().unwrap(), 10);
535 assert_eq!(store.schema_version().unwrap(), 11);
501 536 }
502 537
503 538 #[test]
@@ -730,6 +765,7 @@ fn migration_indexes_rows_that_predate_search() {
730 765 DROP TABLE team_layout; DROP TABLE channel_layout; DROP TABLE presence; DROP TABLE activity;
731 766 DROP INDEX messages_by_sender; DROP INDEX chat_members_by_user;
732 767 ALTER TABLE messages DROP COLUMN sender_application_id;
768 ALTER TABLE messages DROP COLUMN links_json;
733 769 ALTER TABLE chats DROP COLUMN muted;
734 770 PRAGMA user_version = 3;",
735 771 )
@@ -64,6 +64,7 @@ fn message(conversation_id: &str, message_id: &str, minute: u32) -> MessageRecor
64 reactions_json: "[]".to_owned(),
64 reactions_json: "[]".to_owned(),
65 mentions_json: "[]".to_owned(),
65 mentions_json: "[]".to_owned(),
66 sender_application_id: None,
66 sender_application_id: None,
67 links_json: "[]".to_owned(),
67 }
68 }
68}
69}
69
70
@@ -81,6 +82,40 @@ fn sender_application_round_trips() {
81 assert_eq!(found["m1"], bot_message);
82 assert_eq!(found["m1"], bot_message);
82}
83}
83
84
85#[test]
86fn an_upsert_without_links_keeps_the_stored_links() {
87 let store = Store::open_in_memory().unwrap();
88 store.upsert_messages(&[message("c1", "m1", 1)]).unwrap();
89 let links = r#"[{"url":"https://a.example"}]"#;
90 assert!(store.set_message_links("c1", "m1", links).unwrap());
91 assert!(!store.set_message_links("c1", "m1", links).unwrap());
92
93 let edited = MessageRecord {
94 body_html: "<p>edited</p>".to_owned(),
95 ..message("c1", "m1", 1)
96 };
97 store.upsert_messages(&[edited]).unwrap();
98 let found = store.messages_by_id("c1", &["m1".to_owned()]).unwrap();
99 assert_eq!(found["m1"].links_json, links);
100 assert_eq!(found["m1"].body_html, "<p>edited</p>");
101
102 let replaced = MessageRecord {
103 links_json: r#"[{"url":"https://b.example"}]"#.to_owned(),
104 ..message("c1", "m1", 1)
105 };
106 store.upsert_messages(std::slice::from_ref(&replaced)).unwrap();
107 let found = store.messages_by_id("c1", &["m1".to_owned()]).unwrap();
108 assert_eq!(found["m1"].links_json, replaced.links_json);
109}
110
111#[test]
112fn new_messages_start_without_links() {
113 let store = Store::open_in_memory().unwrap();
114 store.upsert_messages(&[message("c1", "m1", 1)]).unwrap();
115 let found = store.messages_by_id("c1", &["m1".to_owned()]).unwrap();
116 assert_eq!(found["m1"].links_json, "[]");
117}
118
84fn ids(messages: &[MessageRecord]) -> Vec<&str> {
119fn ids(messages: &[MessageRecord]) -> Vec<&str> {
85 messages
120 messages
86 .iter()
121 .iter()
@@ -395,11 +430,11 @@ fn file_database_uses_wal_persists_and_migrates_once() {
395 let path = directory.path().join("nested").join("cache.sqlite3");
430 let path = directory.path().join("nested").join("cache.sqlite3");
396 {
431 {
397 let store = Store::open(&path).unwrap();
432 let store = Store::open(&path).unwrap();
398 assert_eq!(store.schema_version().unwrap(), 10);
433 assert_eq!(store.schema_version().unwrap(), 11);
399 store.upsert_messages(&[message("c", "m1", 1)]).unwrap();
434 store.upsert_messages(&[message("c", "m1", 1)]).unwrap();
400 }
435 }
401 let reopened = Store::open(&path).unwrap();
436 let reopened = Store::open(&path).unwrap();
402 assert_eq!(reopened.schema_version().unwrap(), 10);
437 assert_eq!(reopened.schema_version().unwrap(), 11);
403 assert_eq!(reopened.message_count("c").unwrap(), 1);
438 assert_eq!(reopened.message_count("c").unwrap(), 1);
404 drop(reopened);
439 drop(reopened);
405 let mode: String = rusqlite_open(&path)
440 let mode: String = rusqlite_open(&path)
@@ -431,7 +466,7 @@ fn old_schema_is_upgraded_in_place() {
431 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 presence; DROP TABLE activity; PRAGMA user_version = 0").unwrap();
466 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 presence; DROP TABLE activity; PRAGMA user_version = 0").unwrap();
432 drop(connection);
467 drop(connection);
433 let store = Store::open(&path).unwrap();
468 let store = Store::open(&path).unwrap();
434 assert_eq!(store.schema_version().unwrap(), 10);
469 assert_eq!(store.schema_version().unwrap(), 11);
435 store.upsert_messages(&[message("c", "m1", 1)]).unwrap();
470 store.upsert_messages(&[message("c", "m1", 1)]).unwrap();
436}
471}
437
472
@@ -497,7 +532,7 @@ fn migration_to_v2_keeps_existing_sync_state() {
497 let store = Store::open(&path).unwrap();
532 let store = Store::open(&path).unwrap();
498 let state = store.sync_state("c").unwrap().unwrap();
533 let state = store.sync_state("c").unwrap().unwrap();
499 assert_eq!(state.delta_link, None);
534 assert_eq!(state.delta_link, None);
500 assert_eq!(store.schema_version().unwrap(), 10);
535 assert_eq!(store.schema_version().unwrap(), 11);
501}
536}
502
537
503#[test]
538#[test]
@@ -730,6 +765,7 @@ fn migration_indexes_rows_that_predate_search() {
730 DROP TABLE team_layout; DROP TABLE channel_layout; DROP TABLE presence; DROP TABLE activity;
765 DROP TABLE team_layout; DROP TABLE channel_layout; DROP TABLE presence; DROP TABLE activity;
731 DROP INDEX messages_by_sender; DROP INDEX chat_members_by_user;
766 DROP INDEX messages_by_sender; DROP INDEX chat_members_by_user;
732 ALTER TABLE messages DROP COLUMN sender_application_id;
767 ALTER TABLE messages DROP COLUMN sender_application_id;
768 ALTER TABLE messages DROP COLUMN links_json;
733 ALTER TABLE chats DROP COLUMN muted;
769 ALTER TABLE chats DROP COLUMN muted;
734 PRAGMA user_version = 3;",
770 PRAGMA user_version = 3;",
735 )
771 )